capsule-runtime 0.11.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
use std::{
    collections::{HashMap, HashSet},
    fs,
    io::{self, Read, Write},
    net::{TcpListener, TcpStream},
    path::{Path, PathBuf},
    sync::{
        atomic::{AtomicBool, AtomicUsize, Ordering},
        Arc, Condvar, Mutex, OnceLock,
    },
    thread,
    time::Duration,
};

use capsule_runtime::{
    bindings::host::murmur::tool::run::{Status as ToolStatus, ToolInput, ToolResult},
    plan::{self, PlannedCall, SchedulerContext, StepStatus},
    CapabilityPolicy, SpawnCredential, WorkdirRoot, SPAWN_APPROVAL_HEADER, SPAWN_CREDENTIAL_HEADER,
};
use serde_json::{json, Value};
use tempfile::{tempdir, TempDir};

mod common;

/// A credential distinctive enough that a substring search over a whole workdir tree, and over
/// every step result, is a meaningful search.
const TEST_CREDENTIAL: &str = "msc1.CREDENTIALmustNEVERleakZZZ99.testsignature";

/// The session id the delegating context asks as.
const TEST_SESSION: &str = "ses_00000000000000000000000000000test";

/// The conversation the delegating context is running the plan in, and therefore the one every
/// `capsule` step's child is told it was spawned from.
const TEST_CONTEXT: &str = "ctx_00000000000000000000000000000test";

/// The `shell_allow` grant below is what makes every test built on this context need a delegated
/// cgroup v2 scope: `plan::execute` bounds the plan's whole subprocess tree before running a step,
/// and fails closed when it cannot.
fn ctx<'a>(
    workdir: PathBuf,
    invoke_tool: &'a (dyn Fn(&str, ToolInput) -> Result<ToolResult, String> + Sync),
) -> SchedulerContext<'a> {
    ctx_gated(workdir, invoke_tool, &UNGATED)
}

/// A decision point that refuses nothing, which is what a session with neither a policy hook nor
/// a `capabilities.filesystem.read_only` declaration presents.
const UNGATED: fn(&PlannedCall<'_>) -> Option<String> = |_| None;

fn ctx_gated<'a>(
    workdir: PathBuf,
    invoke_tool: &'a (dyn Fn(&str, ToolInput) -> Result<ToolResult, String> + Sync),
    gate_step: &'a (dyn Fn(&PlannedCall<'_>) -> Option<String> + Sync),
) -> SchedulerContext<'a> {
    // A stand-in records directory, `records/` in the test's directory, holding the home folder
    // every shell step needs and the `children/` a capsule step creates its child's work folder in.
    let records = records_of(&workdir);
    std::fs::create_dir_all(records.join("home")).unwrap();
    SchedulerContext {
        accessible_workdir: WorkdirRoot::open(&workdir).unwrap(),
        runtime_dir: capsule_runtime::runtime_dir::RuntimeDirRoots::new(
            WorkdirRoot::open(&workdir).unwrap(),
            WorkdirRoot::open(&workdir).unwrap(),
            WorkdirRoot::open(&workdir).unwrap(),
        )
        .with_records(WorkdirRoot::open(&records).unwrap())
        .with_home(WorkdirRoot::open(&records.join("home")).unwrap()),
        capability_policy: CapabilityPolicy {
            shell_allow: vec!["bash".to_string(), "printf".to_string()],
            spawn_allow: vec!["local/worker".to_string()],
            ..CapabilityPolicy::default()
        },
        installed_tools: HashSet::from([
            "echo".to_string(),
            "fail".to_string(),
            "slow".to_string(),
            "flaky".to_string(),
        ]),
        capsule_versions: HashMap::from([("worker".to_string(), "0.1.0".to_string())]),
        current_session_id: Some(TEST_SESSION.to_string()),
        current_context_id: Some(TEST_CONTEXT.to_string()),
        registry: worker_registry(),
        spawn_credential: Some(SpawnCredential::new(TEST_CREDENTIAL.to_string())),
        formation_id: None,
        deadline: None,
        trace: None,
        gate_step,
        invoke_tool,
        task: None,
    }
}

/// The stand-in records directory of the context built over `workdir`.
fn records_of(workdir: &Path) -> PathBuf {
    workdir.join("records")
}

/// A store holding the `local/worker` artifact every capsule step here delegates to, by its
/// bare name `worker`.
///
/// A capsule step reads its child's declared `capabilities.env.allow` out of the packed manifest
/// before it launches, so the artifact has to resolve even where the child is a stub `mur` that
/// never loads it. This one declares no variables, which is the case that leaves a child holding
/// the runtime's own names and nothing else.
fn worker_registry() -> Arc<dyn murmur_artifact::Registry> {
    static REGISTRY: OnceLock<TempDir> = OnceLock::new();
    let root = REGISTRY.get_or_init(|| {
        let dir = tempdir().unwrap();
        common::publish_capsule(dir.path(), "local/worker", "0.1.0", "artifacts: []\n", None);
        dir
    });
    Arc::new(murmur_artifact::LocalRegistry::new(root.path()))
}

fn tool_result(status: ToolStatus, data: Option<String>, summary: Option<String>) -> ToolResult {
    ToolResult {
        status,
        summary,
        data,
        data_path: None,
        truncated: false,
        metadata: Vec::new(),
        attachments: Vec::new(),
    }
}

/// [`tool_result`] for a tool that answers out of band, naming a file instead of carrying bytes.
fn tool_result_with_path(data: Option<String>, data_path: &str) -> ToolResult {
    ToolResult {
        status: ToolStatus::Passed,
        summary: None,
        data,
        data_path: Some(data_path.to_string()),
        truncated: false,
        metadata: Vec::new(),
        attachments: Vec::new(),
    }
}

/// The tool a case hands a plan that dispatches none — a `capsule` or `shell` step, or a `tool`
/// step whose dispatch is refused before it runs. Reaching it means the plan dispatched a tool
/// step the case did not expect.
fn unused_tool(_name: &str, _input: ToolInput) -> Result<ToolResult, String> {
    Ok(tool_result(
        ToolStatus::Passed,
        Some("unused".to_string()),
        None,
    ))
}

fn write_plan(workdir: &Path, plan: Value) -> PathBuf {
    let path = workdir.join("plan.json");
    fs::write(&path, serde_json::to_string(&plan).unwrap()).unwrap();
    path
}

fn find<'a>(report: &'a plan::ExecutionReport, step_id: &str) -> &'a plan::StepResult {
    report
        .results
        .iter()
        .find(|result| result.step_id == step_id)
        .unwrap()
}

#[test]
fn test_parallel_tool_steps_run_concurrently() {
    if capsule_runtime::skip_without_host_support("test_parallel_tool_steps_run_concurrently") {
        return;
    }
    // How long a step waits for its sibling to be in flight. Run sequentially, the first step
    // waits this out alone; run concurrently, the steps meet as soon as both start.
    const RENDEZVOUS_GUARD: Duration = Duration::from_secs(30);

    /// `met` latches once both steps are in flight together, so the first step to leave the
    /// rendezvous cannot strand the other.
    #[derive(Default)]
    struct Rendezvous {
        in_flight: usize,
        met: bool,
    }

    let dir = tempdir().unwrap();
    let rendezvous = Arc::new((Mutex::new(Rendezvous::default()), Condvar::new()));
    let met_sibling = Arc::new(AtomicUsize::new(0));
    let invoke_rendezvous = Arc::clone(&rendezvous);
    let invoke_met = Arc::clone(&met_sibling);
    let invoke = move |_name: &str, _input: ToolInput| {
        let (state, changed) = &*invoke_rendezvous;
        let mut state = state.lock().unwrap();
        state.in_flight += 1;
        if state.in_flight == 2 {
            state.met = true;
        }
        changed.notify_all();
        let (mut state, _) = changed
            .wait_timeout_while(state, RENDEZVOUS_GUARD, |state| !state.met)
            .unwrap();
        if state.met {
            invoke_met.fetch_add(1, Ordering::SeqCst);
        }
        state.in_flight -= 1;
        Ok(tool_result(
            ToolStatus::Passed,
            Some("ok".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"slow"},{"id":"b","tool":"slow"}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(report.completed, "{report:?}");
    assert_eq!(
        met_sibling.load(Ordering::SeqCst),
        2,
        "the two independent steps never ran at the same time"
    );
}

#[test]
fn test_dependent_step_receives_upstream_output() {
    if capsule_runtime::skip_without_host_support("test_dependent_step_receives_upstream_output") {
        return;
    }
    let dir = tempdir().unwrap();
    let inputs = Arc::new(Mutex::new(Vec::new()));
    let seen = Arc::clone(&inputs);
    let invoke = move |_name: &str, input: ToolInput| {
        let input_json = input.data.unwrap_or_default();
        seen.lock().unwrap().push(input_json.clone());
        let output = if input_json.contains("from-a") {
            "done"
        } else {
            "from-a"
        };
        Ok(tool_result(
            ToolStatus::Passed,
            Some(output.to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"a","tool":"echo"},
                {"id":"b","tool":"echo","depends_on":["a"],"input":{"value":"$a.output"}}
            ]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(report.completed, "{report:?}");
    assert!(inputs.lock().unwrap()[1].contains("from-a"));
}

#[test]
fn test_shell_step_executes() {
    if capsule_runtime::skip_without_host_support("test_shell_step_executes") {
        return;
    }
    let dir = tempdir().unwrap();
    let invoke = unused_tool;
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"sh","shell":"bash -c 'printf shell-ok'"}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(report.completed);
    assert_eq!(find(&report, "sh").output.as_deref(), Some("shell-ok"));
}

/// A plain objective reaches the child capsule as plain text.
///
/// The child pushes whatever arrives straight at its model, and nothing parses a task envelope,
/// so wrapping the objective in one would only hand the child JSON to decode before it can start.
#[test]
fn test_capsule_step_sends_objective_as_plain_text() {
    if capsule_runtime::skip_without_host_support("test_capsule_step_sends_objective_as_plain_text")
    {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::start();
    let _stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let invoke = unused_tool;
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[{"id":"worker","capsule":"worker","input":{"objective":"Echo this task"}}]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));
    std::env::remove_var("MURMUR_ROOST_URL");

    assert!(report.completed, "{report:?}");
    assert_eq!(
        find(&report, "worker").output.as_deref(),
        Some("worker-output")
    );
    // The spawn call names the capsule to start and nothing about the task; the task itself
    // rides the A2A message that follows.
    let spawned = fake_roost.spawn_request();
    assert_eq!(spawned["name"], "local/worker");
    assert!(spawned.get("input").is_none(), "{spawned}");
    assert_eq!(fake_roost.sent_text(), "Echo this task");
}

/// A bare string is the task text, delivered without the quote marks that serializing it would
/// add.
#[test]
fn test_capsule_step_sends_a_bare_string_as_plain_text() {
    if capsule_runtime::skip_without_host_support(
        "test_capsule_step_sends_a_bare_string_as_plain_text",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::start();
    let _stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let invoke = unused_tool;
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[{"id":"worker","capsule":"worker","input":"Echo this task"}]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));
    std::env::remove_var("MURMUR_ROOST_URL");

    assert!(report.completed, "{report:?}");
    assert_eq!(fake_roost.sent_text(), "Echo this task");
}

/// The shape is fixed at load time; the value is not. A capsule step therefore still takes its
/// task text from an upstream step's output.
#[test]
fn test_capsule_step_receives_interpolated_upstream_output() {
    if capsule_runtime::skip_without_host_support(
        "test_capsule_step_receives_interpolated_upstream_output",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::start();
    let _stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("analysed the thing".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"analyse","tool":"echo"},
                {
                    "id":"worker",
                    "capsule":"worker",
                    "depends_on":["analyse"],
                    "input":{"objective":"$analyse.output"}
                }
            ]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));
    std::env::remove_var("MURMUR_ROOST_URL");

    assert!(report.completed, "{report:?}");
    assert_eq!(fake_roost.sent_text(), "analysed the thing");
}

/// Runs a one-step plan whose only step is the given capsule step.
///
/// `plan::execute` validates a plan before it takes a cgroup scope or reads `MURMUR_ROOST_URL`,
/// so a refused input shape needs neither host process bounding nor a daemon to reproduce.
fn capsule_step_report(step: Value) -> plan::ExecutionReport {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| Ok(tool_result(ToolStatus::Passed, None, None));
    let plan = write_plan(dir.path(), json!({"id": "p", "steps": [step]}));

    plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke))
}

/// The plan is refused whole: one failed result for the offending step, and nothing ran.
fn assert_capsule_input_refused(input_key: Option<Value>, expected: &str) {
    let mut step = json!({"id": "worker", "capsule": "worker"});
    if let Some(input) = input_key {
        step["input"] = input;
    }
    let report = capsule_step_report(step);

    assert!(!report.completed, "{report:?}");
    assert_eq!(report.failed_step.as_deref(), Some("worker"), "{report:?}");
    assert_eq!(report.results.len(), 1, "{report:?}");
    assert_eq!(report.results[0].status, StepStatus::Failed, "{report:?}");
    let error = report.results[0].error.as_deref().unwrap_or_default();
    assert!(error.contains(expected), "{error}");
}

/// An envelope for the child's model to decode is refused rather than delivered as prose.
#[test]
fn test_capsule_step_input_refuses_a_task_envelope() {
    assert_capsule_input_refused(
        Some(json!({"task": "hello"})),
        "capsule step input has keys the child cannot receive: task",
    );
}

#[test]
fn test_capsule_step_input_refuses_instructions_beside_an_objective() {
    assert_capsule_input_refused(
        Some(json!({"objective": "x", "instructions": "y"})),
        "capsule step input has keys the child cannot receive: instructions",
    );
}

#[test]
fn test_capsule_step_input_refuses_a_companion_key_beside_an_objective() {
    assert_capsule_input_refused(
        Some(json!({"objective": "x", "render_as": "json"})),
        "capsule step input has keys the child cannot receive: render_as",
    );
}

#[test]
fn test_capsule_step_input_refuses_a_number() {
    assert_capsule_input_refused(
        Some(json!(7)),
        "capsule step input must be a string or { \"objective\": \"<text>\" }, not a number",
    );
}

#[test]
fn test_capsule_step_input_refuses_an_array() {
    assert_capsule_input_refused(
        Some(json!(["a"])),
        "capsule step input must be a string or { \"objective\": \"<text>\" }, not an array",
    );
}

#[test]
fn test_capsule_step_input_refuses_a_non_string_objective() {
    assert_capsule_input_refused(
        Some(json!({"objective": 7})),
        "capsule step input \"objective\" must be a string",
    );
}

#[test]
fn test_capsule_step_input_refuses_an_absent_input() {
    assert_capsule_input_refused(None, "capsule step has no input");
}

#[test]
fn test_if_condition_skips_step_on_false() {
    if capsule_runtime::skip_without_host_support("test_if_condition_skips_step_on_false") {
        return;
    }
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("ok".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"a","tool":"echo"},
                {"id":"b","tool":"echo","depends_on":["a"],"if":"$a.status == 'failed'"}
            ]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(report.completed);
    assert_eq!(find(&report, "b").status, StepStatus::Skipped);
}

#[test]
fn test_validation_rejects_unresolvable_tool() {
    let dir = tempdir().unwrap();
    let calls = Arc::new(AtomicUsize::new(0));
    let seen = Arc::clone(&calls);
    let invoke = |_name: &str, _input: ToolInput| {
        seen.fetch_add(1, Ordering::SeqCst);
        Ok(tool_result(
            ToolStatus::Passed,
            Some("unused".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"bad","tool":"nonexistent"}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(!report.completed);
    assert_eq!(report.failed_step.as_deref(), Some("bad"));
    assert_eq!(find(&report, "bad").status, StepStatus::Failed);
    assert_eq!(calls.load(Ordering::SeqCst), 0);
}

#[test]
fn test_on_error_continue_completes_plan() {
    if capsule_runtime::skip_without_host_support("test_on_error_continue_completes_plan") {
        return;
    }
    let dir = tempdir().unwrap();
    let invoke = |name: &str, _input: ToolInput| {
        if name == "fail" {
            Ok(tool_result(
                ToolStatus::Failed,
                None,
                Some("nope".to_string()),
            ))
        } else {
            Ok(tool_result(
                ToolStatus::Passed,
                Some("ok".to_string()),
                None,
            ))
        }
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"a","tool":"fail","on_error":"continue"},
                {"id":"b","tool":"echo","depends_on":["a"]}
            ]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(report.completed);
    assert_eq!(find(&report, "a").status, StepStatus::Failed);
    assert_eq!(find(&report, "b").status, StepStatus::Success);
}

#[test]
fn test_on_error_fail_aborts_plan() {
    if capsule_runtime::skip_without_host_support("test_on_error_fail_aborts_plan") {
        return;
    }
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Failed,
            None,
            Some("nope".to_string()),
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"a","tool":"fail","on_error":"fail"},
                {"id":"b","tool":"echo","depends_on":["a"]}
            ]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(!report.completed);
    assert_eq!(report.failed_step.as_deref(), Some("a"));
    assert!(report.results.iter().all(|result| result.step_id != "b"));
}

#[test]
fn test_retries_before_error_policy() {
    if capsule_runtime::skip_without_host_support("test_retries_before_error_policy") {
        return;
    }
    let dir = tempdir().unwrap();
    let calls = Arc::new(AtomicUsize::new(0));
    let seen = Arc::clone(&calls);
    let invoke = move |_name: &str, _input: ToolInput| {
        let attempt = seen.fetch_add(1, Ordering::SeqCst);
        if attempt < 2 {
            Ok(tool_result(
                ToolStatus::Failed,
                None,
                Some("retry".to_string()),
            ))
        } else {
            Ok(tool_result(
                ToolStatus::Passed,
                Some("ok".to_string()),
                None,
            ))
        }
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"flaky","retries":2}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(report.completed);
    assert_eq!(calls.load(Ordering::SeqCst), 3);
    assert_eq!(find(&report, "a").status, StepStatus::Success);
}

#[test]
fn test_join_point_waits_for_multiple_upstreams() {
    if capsule_runtime::skip_without_host_support("test_join_point_waits_for_multiple_upstreams") {
        return;
    }
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, input: ToolInput| {
        let data = input.data.unwrap_or_default();
        let output = if data.contains("left") && data.contains("right") {
            "joined"
        } else if data.contains("side\":\"left") {
            "left"
        } else {
            "right"
        };
        Ok(tool_result(
            ToolStatus::Passed,
            Some(output.to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"left","tool":"echo","input":{"side":"left"}},
                {"id":"right","tool":"echo","input":{"side":"right"}},
                {"id":"join","tool":"echo","depends_on":["left","right"],"input":{"l":"$left.output","r":"$right.output"}}
            ]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(report.completed);
    assert_eq!(find(&report, "join").output.as_deref(), Some("joined"));
}

/// A capsule step asks the daemon once, and then launches the child itself.
///
/// The credential reaches the daemon in a header; the approval reaches the child on its standard
/// input and nowhere else, because the argument vector and the environment of a process are
/// readable through `/proc` by anything running as the same user.
#[test]
fn test_capsule_step_asks_permission_then_launches_the_child_itself() {
    if capsule_runtime::skip_without_host_support(
        "test_capsule_step_asks_permission_then_launches_the_child_itself",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::start();
    let _stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let invoke = unused_tool;
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"worker","capsule":"worker","input":{"objective":"go"}}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));
    std::env::remove_var("MURMUR_ROOST_URL");

    assert!(report.completed, "{report:?}");

    // One request to the daemon, and it asks about one capsule by name and version while proving
    // who is asking.
    let paths: Vec<String> = fake_roost
        .requests()
        .into_iter()
        .map(|request| request.path)
        .collect();
    assert_eq!(paths, vec!["/spawn".to_string()]);
    let spawn = fake_roost.request("/spawn");
    assert_eq!(spawn.body["name"], "local/worker");
    assert_eq!(spawn.body["version"], "0.1.0");
    assert_eq!(
        spawn
            .headers
            .get(SPAWN_CREDENTIAL_HEADER)
            .map(String::as_str),
        Some(TEST_CREDENTIAL)
    );
    // The approval is not presented to the daemon at all: the child redeems it when it registers.
    assert!(!spawn.headers.contains_key(SPAWN_APPROVAL_HEADER));

    // The child was started by this runtime, on the argument vector the launcher builds.
    let argv = _stub.recorded("argv.txt");
    let child_dir = records_of(dir.path()).join("children");
    assert!(
        argv.starts_with("run --capsule local/worker --capsule-version 0.1.0 --workdir "),
        "{argv}"
    );
    assert!(argv.contains(&child_dir.display().to_string()), "{argv}");
    assert!(
        argv.ends_with(
            " --json --readiness-tokens --no-env-file --spawn-grant-stdin --contained-launch"
        ),
        "{argv}"
    );
    // A plan capsule step never runs unconfined, whatever the session that submitted it runs as.
    assert!(!argv.contains("--unconfined"), "{argv}");
    let child_workdir = argv
        .split(" --workdir ")
        .nth(1)
        .unwrap()
        .split(" --workdir-identity ")
        .next()
        .unwrap()
        .to_string();
    assert_eq!(_stub.recorded("cwd.txt").trim(), child_workdir);
    // The child is told the identity of the directory its parent created, which its staging
    // compares with the `--workdir` it opens.
    let identity = {
        use std::os::unix::fs::MetadataExt;
        let meta = std::fs::metadata(&child_workdir).unwrap();
        format!("{}:{}", meta.dev(), meta.ino())
    };
    // The child's work folder is `<records>/children/worker-<16 hex>/`, owner-only, and the plan's
    // work folder gains nothing for it.
    {
        use std::os::unix::fs::PermissionsExt;
        let child_workdir = Path::new(&child_workdir);
        assert_eq!(child_workdir.parent(), Some(child_dir.as_path()));
        let name = child_workdir.file_name().unwrap().to_string_lossy();
        assert_eq!(name.len(), "worker-".len() + 16, "{name}");
        assert_eq!(
            std::fs::metadata(child_workdir)
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o700
        );
        assert!(!dir.path().join(".murmur").exists());
    }
    assert!(
        argv.contains(&format!(" --workdir-identity {identity} --json")),
        "{argv}"
    );

    // The grant travelled on standard input, and on nothing else.
    assert_eq!(_stub.recorded("grant.txt"), TEST_APPROVAL);
    assert!(!argv.contains(TEST_APPROVAL), "{argv}");
    assert!(!argv.contains(TEST_CREDENTIAL), "{argv}");
    let env = _stub.recorded("env.txt");
    assert!(!env.contains(TEST_APPROVAL), "{env}");
    assert!(!env.contains(TEST_CREDENTIAL), "{env}");
    assert!(env.contains("MURMUR_ROOST_URL="), "{env}");
}

/// A session that was never granted a credential cannot delegate, and says so before it opens a
/// connection.
#[test]
fn test_capsule_step_without_a_credential_asks_for_nothing() {
    if capsule_runtime::skip_without_host_support(
        "test_capsule_step_without_a_credential_asks_for_nothing",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::start();
    let _stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let invoke = unused_tool;
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"worker","capsule":"worker","input":{"objective":"go"}}]}),
    );

    let mut context = ctx(dir.path().to_path_buf(), &invoke);
    context.spawn_credential = None;
    let report = plan::execute(&plan, &context);
    std::env::remove_var("MURMUR_ROOST_URL");

    assert!(!report.completed, "{report:?}");
    let error = find(&report, "worker").error.clone().unwrap();
    assert!(error.contains("holds no spawn credential"), "{error}");
    assert!(error.contains("capabilities.spawn.allow"), "{error}");
    assert!(
        fake_roost.requests().is_empty(),
        "{:?}",
        fake_roost
            .requests()
            .into_iter()
            .map(|request| request.path)
            .collect::<Vec<_>>()
    );
}

/// The credential the runtime presents is unreadable by the agent: it reaches no file under the
/// workdir and no step result, on the success path and on the client's error path alike.
#[test]
fn test_the_spawn_credential_reaches_no_file_and_no_step_result() {
    if capsule_runtime::skip_without_host_support(
        "test_the_spawn_credential_reaches_no_file_and_no_step_result",
    ) {
        return;
    }
    assert_eq!(
        format!("{:?}", SpawnCredential::new(TEST_CREDENTIAL.to_string())),
        "SpawnCredential(<redacted>)"
    );

    for refuse_spawn in [false, true] {
        let _guard = roost_env_lock().lock().unwrap();
        let dir = tempdir().unwrap();
        let fake_roost = if refuse_spawn {
            FakeRoost::refusing_spawn()
        } else {
            FakeRoost::start()
        };
        let _stub = StubMur::install(fake_roost.authority());
        std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
        let invoke = unused_tool;
        let plan = write_plan(
            dir.path(),
            json!({
                "id":"p",
                "steps":[{"id":"worker","capsule":"worker","input":{"objective":"go"}}]
            }),
        );

        // Traced, so `trace.jsonl` is one of the files the search below reads: a capsule step's
        // records name the step and its verdict, never the token that authorized it.
        let trace = appender(dir.path());
        let mut context = ctx(dir.path().to_path_buf(), &invoke);
        context.trace = Some(&trace);
        let report = plan::execute(&plan, &context);
        std::env::remove_var("MURMUR_ROOST_URL");

        assert_eq!(report.completed, !refuse_spawn, "{report:?}");
        let lines = trace_lines(dir.path());
        assert_eq!(only(&lines, "plan_step")["kind"], "capsule", "{lines:#?}");
        for result in &report.results {
            for text in [result.output.as_deref(), result.error.as_deref()]
                .into_iter()
                .flatten()
            {
                assert!(
                    !text.contains(TEST_CREDENTIAL) && !text.contains(TEST_APPROVAL),
                    "a step result carried token material (refuse_spawn={refuse_spawn}): {text}",
                );
            }
        }
        for (path, contents) in read_tree(dir.path()) {
            assert!(
                !contents.contains(TEST_CREDENTIAL) && !contents.contains(TEST_APPROVAL),
                "{} carried token material (refuse_spawn={refuse_spawn})",
                path.display(),
            );
        }
    }
}

/// Every file beneath `root`, read as lossy UTF-8 so a binary file is still searchable.
fn read_tree(root: &Path) -> Vec<(PathBuf, String)> {
    let mut found = Vec::new();
    let Ok(entries) = fs::read_dir(root) else {
        return found;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            found.extend(read_tree(&path));
        } else if let Ok(bytes) = fs::read(&path) {
            found.push((path, String::from_utf8_lossy(&bytes).to_string()));
        }
    }
    found
}

/// The approval this fake's `/spawn` hands back, and therefore the value the launched child must
/// be handed on its standard input.
const TEST_APPROVAL: &str = "msa1.APPROVALmustNEVERleakYY88.testsignature";

/// A stand-in for the `mur` binary the parent's runtime launches a child with.
///
/// The child half of a capsule step is a real subprocess started by
/// `child_launch::launch_child_capsule`: this is the program it starts. It reads the one line of
/// standard input the parent writes, records that line, its argument vector, its environment and
/// its working directory beside itself — outside the plan's workdir, so a test that scans the
/// workdir for token material is scanning what a capsule could actually reach — and prints the
/// `--json` launch line the parent parses, naming the fake daemon's `/capsule` path as its own
/// address and a records directory it creates under a scratch `HOME` this stub installs for the
/// test process, so the parent's check that the directory is under `~/.murmur/records` passes
/// without touching the developer's own home.
struct StubMur {
    dir: tempfile::TempDir,
    records_dir: PathBuf,
    home_before: Option<std::ffi::OsString>,
}

/// The session id the stub reports, and the last segment of its records directory.
const STUB_SESSION: &str = "ses_stub00000000000000000000000";

impl StubMur {
    /// Installs the stub and points [`MUR_BINARY_ENV`] at it. Every caller already holds
    /// [`roost_env_lock`], which is what keeps the process-wide variable to one test at a time.
    fn install(capsule_authority: &str) -> Self {
        Self::install_with(capsule_authority, "")
    }

    /// The same stub, staying up as one process after it reports its address — a child that is
    /// still running when its parent ends it. Its pid is recorded as `pid.txt`.
    fn install_lingering(capsule_authority: &str) -> Self {
        Self::install_with(capsule_authority, "exec sleep 300\n")
    }

    fn install_with(capsule_authority: &str, after_launch_line: &str) -> Self {
        let dir = tempdir().unwrap();
        let record = dir.path().display().to_string();
        let home = dir.path().join("home");
        let records_dir = home
            .join(".murmur")
            .join("records")
            .join("stub")
            .join(STUB_SESSION);
        let records = records_dir.display().to_string();
        let home_before = std::env::var_os("HOME");
        std::env::set_var("HOME", &home);
        let binary = dir.path().join("mur");
        fs::write(
            &binary,
            format!(
                "#!/bin/sh\n\
                 printf '%s' \"$$\" > '{record}/pid.txt'\n\
                 read -r grant\n\
                 printf '%s' \"$grant\" > '{record}/grant.txt'\n\
                 printf '%s' \"$*\" > '{record}/argv.txt'\n\
                 env > '{record}/env.txt'\n\
                 pwd > '{record}/cwd.txt'\n\
                 mkdir -p '{records}'\n\
                 printf '{{\"url\":\"{capsule_authority}/capsule\",\"session_id\":\"{STUB_SESSION}\",\"records_dir\":\"{records}\"}}\\n'\n\
                 {after_launch_line}"
            ),
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)).unwrap();
        }
        std::env::set_var(capsule_runtime::MUR_BINARY_ENV, &binary);
        Self {
            dir,
            records_dir,
            home_before,
        }
    }

    fn recorded(&self, name: &str) -> String {
        fs::read_to_string(self.dir.path().join(name))
            .unwrap_or_else(|error| panic!("the stub recorded no {name}: {error}"))
    }
}

impl Drop for StubMur {
    fn drop(&mut self) {
        std::env::remove_var(capsule_runtime::MUR_BINARY_ENV);
        match self.home_before.take() {
            Some(home) => std::env::set_var("HOME", home),
            None => std::env::remove_var("HOME"),
        }
    }
}

/// One request the fake received, kept whole so a test can assert on headers as well as body.
#[derive(Clone)]
struct RecordedRequest {
    path: String,
    headers: HashMap<String, String>,
    body: Value,
}

/// A stand-in for mur-roost *and* for the child capsule, served on one loopback listener.
///
/// `dispatch_capsule_step` speaks two protocols against this: one `POST /spawn` to mur-roost,
/// which answers with permission and nothing else, then A2A JSON-RPC against the child this
/// runtime launched — `SendMessage` to hand over the task, then `GetTask` polled until the
/// state is terminal. The child itself is [`StubMur`], which reports this fake's `/capsule` path
/// as its address, so both halves are served here and routed on the request path.
///
/// The server loop polls for connections rather than parking in a blocking `accept`, and every
/// read it makes is bounded, so `drop` can always stop it. A fake that could only be stopped by
/// the client making exactly the sequence of calls it expected would turn every failed
/// assertion into a hung test instead of a reported one — the panic unwinds into `drop`, which
/// then joins a thread waiting on a connection that is never coming.
struct FakeRoost {
    url: String,
    requests: Arc<Mutex<Vec<RecordedRequest>>>,
    sent_text: Arc<Mutex<Option<String>>>,
    shutdown: Arc<AtomicBool>,
    join: Option<thread::JoinHandle<()>>,
}

impl FakeRoost {
    fn start() -> Self {
        Self::start_with(false, true)
    }

    /// A fake whose `/spawn` refuses with `403` and echoes the request it received back in the
    /// body, so the client's error path carries as much of the exchange as it ever could.
    fn refusing_spawn() -> Self {
        Self::start_with(true, true)
    }

    /// A fake whose child accepts its task and then answers `TASK_STATE_WORKING` to every
    /// `GetTask`, so the delegation never reaches a terminal state on its own.
    fn never_finishing() -> Self {
        Self::start_with(false, false)
    }

    fn start_with(refuse_spawn: bool, finishes: bool) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        listener.set_nonblocking(true).unwrap();
        let url = format!("http://{addr}");

        let requests = Arc::new(Mutex::new(Vec::new()));
        let sent_text = Arc::new(Mutex::new(None));
        let shutdown = Arc::new(AtomicBool::new(false));

        let join = thread::spawn({
            let requests = Arc::clone(&requests);
            let sent_text = Arc::clone(&sent_text);
            let shutdown = Arc::clone(&shutdown);
            move || {
                while !shutdown.load(Ordering::SeqCst) {
                    let mut stream = match listener.accept() {
                        Ok((stream, _)) => stream,
                        Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
                            thread::sleep(Duration::from_millis(5));
                            continue;
                        }
                        Err(_) => break,
                    };
                    // `accept` on a non-blocking listener may hand back a non-blocking socket.
                    // The request reader wants a blocking one, but time-bounded, so a client
                    // that opens a connection and then says nothing cannot wedge the loop.
                    stream.set_nonblocking(false).unwrap();
                    stream
                        .set_read_timeout(Some(Duration::from_secs(5)))
                        .unwrap();

                    let (path, headers, body) = read_http_request(&mut stream);
                    let request: Value = serde_json::from_str(&body).unwrap_or(Value::Null);
                    if path == "/spawn" {
                        requests.lock().unwrap().push(RecordedRequest {
                            path: path.clone(),
                            headers,
                            body: request.clone(),
                        });
                    }
                    let (status, response) = match path.as_str() {
                        "/spawn" if refuse_spawn => (
                            403,
                            json!({
                                "error": "spawn refused by the fake",
                                "request": {"path": path, "body": request},
                            }),
                        ),
                        "/spawn" => (
                            200,
                            json!({
                                "approval": TEST_APPROVAL,
                                "name": "local/worker",
                                "version": "0.1.0",
                                "sha256": "0".repeat(64),
                                "expires_at_ms": 1_u64 << 42,
                            }),
                        ),
                        _ => {
                            let id = request.get("id").cloned().unwrap_or(Value::Null);
                            let body = match request.get("method").and_then(Value::as_str) {
                                Some("SendMessage") => {
                                    *sent_text.lock().unwrap() = Some(
                                        request["params"]["message"]["parts"][0]["text"]
                                            .as_str()
                                            .unwrap_or_default()
                                            .to_string(),
                                    );
                                    json!({"jsonrpc": "2.0", "id": id, "result": {"task": {
                                        "id": "task-1",
                                        "contextId": "ctx-1",
                                        "status": {"state": "TASK_STATE_SUBMITTED"}
                                    }}})
                                }
                                Some("GetTask") if !finishes => json!({
                                    "jsonrpc": "2.0",
                                    "id": id,
                                    "result": {
                                        "id": "task-1",
                                        "contextId": "ctx-1",
                                        "status": {"state": "TASK_STATE_WORKING"}
                                    }
                                }),
                                Some("GetTask") => json!({
                                    "jsonrpc": "2.0",
                                    "id": id,
                                    "result": {
                                        "id": "task-1",
                                        "contextId": "ctx-1",
                                        "status": {"state": "TASK_STATE_COMPLETED"},
                                        "artifacts": [{
                                            "artifactId": "response",
                                            "name": "response",
                                            "parts": [
                                                {"text": "worker-output", "mediaType": "text/plain"}
                                            ]
                                        }]
                                    }
                                }),
                                other => panic!("unexpected request {other:?} at {path}"),
                            };
                            (200, body)
                        }
                    };
                    write_http_json(&mut stream, status, &response);
                }
            }
        });

        Self {
            url,
            requests,
            sent_text,
            shutdown,
            join: Some(join),
        }
    }

    /// Host and port only, for a child that has to report an address on this listener.
    fn authority(&self) -> &str {
        self.url.trim_start_matches("http://")
    }

    /// Every `/spawn` the fake received, in order.
    fn requests(&self) -> Vec<RecordedRequest> {
        self.requests.lock().unwrap().clone()
    }

    /// The one request the fake received at `path`.
    fn request(&self, path: &str) -> RecordedRequest {
        self.requests()
            .into_iter()
            .find(|request| request.path == path)
            .unwrap_or_else(|| panic!("no {path} request was made"))
    }

    /// The body of the `POST /spawn` that asked mur-roost for permission.
    fn spawn_request(&self) -> Value {
        self.request("/spawn").body
    }

    /// The task text the step handed to the capsule over A2A `SendMessage`, exactly as it
    /// travelled in the single text part. This is where a capsule step's input lives — the spawn
    /// call above carries only the capsule's name and version. Returned unparsed: what the
    /// child's model receives is this string, so that is what the tests assert on.
    fn sent_text(&self) -> String {
        self.sent_text.lock().unwrap().clone().unwrap()
    }
}

impl Drop for FakeRoost {
    fn drop(&mut self) {
        self.shutdown.store(true, Ordering::SeqCst);
        if let Some(join) = self.join.take() {
            let _ = join.join();
        }
    }
}

fn roost_env_lock() -> &'static Mutex<()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
}

/// Read one HTTP request, returning its request-target path, its headers (keyed lowercase) and
/// its body.
fn read_http_request(stream: &mut TcpStream) -> (String, HashMap<String, String>, String) {
    let mut buffer = Vec::new();
    let mut chunk = [0_u8; 4096];
    let header_end;
    loop {
        let read = stream.read(&mut chunk).unwrap();
        if read == 0 {
            return (String::new(), HashMap::new(), String::new());
        }
        buffer.extend_from_slice(&chunk[..read]);
        if let Some(index) = buffer.windows(4).position(|window| window == b"\r\n\r\n") {
            header_end = index;
            break;
        }
    }

    let headers = String::from_utf8_lossy(&buffer[..header_end]);
    let path = headers
        .lines()
        .next()
        .and_then(|request_line| request_line.split_whitespace().nth(1))
        .unwrap_or_default()
        .to_string();
    let header_map: HashMap<String, String> = headers
        .lines()
        .skip(1)
        .filter_map(|line| {
            let (key, value) = line.split_once(':')?;
            Some((key.trim().to_ascii_lowercase(), value.trim().to_string()))
        })
        .collect();
    let content_length = header_map
        .get("content-length")
        .and_then(|value| value.parse::<usize>().ok())
        .unwrap_or(0);

    let mut body = buffer[header_end + 4..].to_vec();
    while body.len() < content_length {
        let read = stream.read(&mut chunk).unwrap();
        if read == 0 {
            break;
        }
        body.extend_from_slice(&chunk[..read]);
    }

    (
        path,
        header_map,
        String::from_utf8_lossy(&body[..content_length]).to_string(),
    )
}

fn write_http_json(stream: &mut TcpStream, status: u16, body: &Value) {
    let reason = if status == 200 { "OK" } else { "Forbidden" };
    let body = body.to_string();
    let response = format!(
        "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
        body.len(),
        body
    );
    stream.write_all(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

#[test]
fn test_cycle_is_reported_without_running_steps() {
    if capsule_runtime::skip_without_host_support("test_cycle_is_reported_without_running_steps") {
        return;
    }
    let dir = tempdir().unwrap();
    let calls = Arc::new(AtomicUsize::new(0));
    let seen = Arc::clone(&calls);
    let invoke = move |_name: &str, _input: ToolInput| {
        seen.fetch_add(1, Ordering::SeqCst);
        Ok(tool_result(
            ToolStatus::Passed,
            Some("unused".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"a","tool":"echo","depends_on":["b"]},
                {"id":"b","tool":"echo","depends_on":["a"]}
            ]
        }),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(!report.completed);
    assert_eq!(report.failed_step.as_deref(), Some("a"));
    assert_eq!(find(&report, "a").status, StepStatus::Failed);
    assert_eq!(calls.load(Ordering::SeqCst), 0);
}

#[test]
fn test_tool_data_path_reads_file_beneath_workdir() {
    if capsule_runtime::skip_without_host_support("test_tool_data_path_reads_file_beneath_workdir")
    {
        return;
    }
    let dir = tempdir().unwrap();
    fs::create_dir_all(dir.path().join("out")).unwrap();
    fs::write(dir.path().join("out/full.txt"), "the whole result").unwrap();
    let invoke = |_name: &str, _input: ToolInput| Ok(tool_result_with_path(None, "out/full.txt"));
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"echo"}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    assert!(report.completed, "{report:?}");
    assert_eq!(find(&report, "a").status, StepStatus::Success);
    assert_eq!(
        find(&report, "a").output.as_deref(),
        Some("the whole result")
    );
}

#[test]
fn test_tool_data_path_absolute_is_refused() {
    if capsule_runtime::skip_without_host_support("test_tool_data_path_absolute_is_refused") {
        return;
    }
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| Ok(tool_result_with_path(None, "/etc/passwd"));
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"echo"}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    let step = find(&report, "a");
    assert_eq!(step.status, StepStatus::Failed);
    assert_eq!(step.output, None);
    let error = step.error.as_deref().unwrap();
    assert!(error.contains("outside_root"), "{error}");
    assert!(
        error.contains("echo") && error.contains("/etc/passwd"),
        "{error}"
    );
    assert!(!format!("{report:?}").contains("root:x:"), "{report:?}");
}

#[test]
fn test_tool_data_path_parent_escape_is_refused() {
    if capsule_runtime::skip_without_host_support("test_tool_data_path_parent_escape_is_refused") {
        return;
    }
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("secret.txt"), "SECRETcontentsZZZ").unwrap();
    let workdir = dir.path().join("session");
    fs::create_dir_all(&workdir).unwrap();
    let invoke = |_name: &str, _input: ToolInput| Ok(tool_result_with_path(None, "../secret.txt"));
    let plan = write_plan(
        &workdir,
        json!({"id":"p","steps":[{"id":"a","tool":"echo"}]}),
    );

    let report = plan::execute(&plan, &ctx(workdir.clone(), &invoke));

    let step = find(&report, "a");
    assert_eq!(step.status, StepStatus::Failed);
    assert_eq!(step.output, None);
    assert!(
        step.error.as_deref().unwrap().contains("outside_root"),
        "{step:?}"
    );
    assert!(
        !format!("{report:?}").contains("SECRETcontentsZZZ"),
        "{report:?}"
    );
}

#[test]
fn test_tool_data_path_symlink_escape_is_refused() {
    if capsule_runtime::skip_without_host_support("test_tool_data_path_symlink_escape_is_refused") {
        return;
    }
    let dir = tempdir().unwrap();
    fs::write(dir.path().join("secret.txt"), "SECRETcontentsZZZ").unwrap();
    let workdir = dir.path().join("session");
    fs::create_dir_all(workdir.join("out")).unwrap();
    std::os::unix::fs::symlink(dir.path().join("secret.txt"), workdir.join("out/leak.txt"))
        .unwrap();
    let invoke = |_name: &str, _input: ToolInput| Ok(tool_result_with_path(None, "out/leak.txt"));
    let plan = write_plan(
        &workdir,
        json!({"id":"p","steps":[{"id":"a","tool":"echo"}]}),
    );

    let report = plan::execute(&plan, &ctx(workdir.clone(), &invoke));

    let step = find(&report, "a");
    assert_eq!(step.status, StepStatus::Failed);
    assert_eq!(step.output, None);
    assert!(
        step.error.as_deref().unwrap().contains("symlink_refused"),
        "{step:?}"
    );
    assert!(
        !format!("{report:?}").contains("SECRETcontentsZZZ"),
        "{report:?}"
    );
}

#[test]
fn test_tool_in_band_data_wins_over_data_path() {
    if capsule_runtime::skip_without_host_support("test_tool_in_band_data_wins_over_data_path") {
        return;
    }
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result_with_path(
            Some("in-band".to_string()),
            "/etc/passwd",
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"echo"}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    let step = find(&report, "a");
    assert_eq!(step.status, StepStatus::Success);
    assert_eq!(step.output.as_deref(), Some("in-band"));
    assert!(!format!("{report:?}").contains("root:x:"), "{report:?}");
}

#[test]
fn test_tool_data_path_missing_file_fails_step() {
    if capsule_runtime::skip_without_host_support("test_tool_data_path_missing_file_fails_step") {
        return;
    }
    let dir = tempdir().unwrap();
    fs::create_dir_all(dir.path().join("out")).unwrap();
    let invoke =
        |_name: &str, _input: ToolInput| Ok(tool_result_with_path(None, "out/missing.txt"));
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"echo"}]}),
    );

    let report = plan::execute(&plan, &ctx(dir.path().to_path_buf(), &invoke));

    let step = find(&report, "a");
    assert_eq!(step.status, StepStatus::Failed);
    assert_eq!(step.output, None);
    assert!(
        step.error.as_deref().unwrap().contains("not_found"),
        "{step:?}"
    );
}

// ── Per-step trace records ───────────────────────────────────────────────────

/// The session node the appender in these tests hangs a run's `plan_start` off.
const TEST_SESSION_EVENT: &str = "evt_00000000000000000000000000session";

/// [`ctx`] with a trace appender attached and every subprocess grant dropped.
///
/// Dropping `shell_allow` and `spawn_allow` is what lets these tests run on a host that cannot
/// delegate a cgroup v2 scope: with neither grant, `plan::execute` needs no delegated scope.
fn traced_ctx<'a>(
    workdir: PathBuf,
    invoke_tool: &'a (dyn Fn(&str, ToolInput) -> Result<ToolResult, String> + Sync),
    appender: &'a capsule_runtime::PlanTraceAppender,
) -> SchedulerContext<'a> {
    let mut context = ctx(workdir, invoke_tool);
    context.capability_policy = CapabilityPolicy::default();
    context.trace = Some(appender);
    context
}

fn appender(workdir: &Path) -> capsule_runtime::PlanTraceAppender {
    capsule_runtime::PlanTraceAppender::open(
        &WorkdirRoot::open(workdir).unwrap(),
        TEST_SESSION.to_string(),
        TEST_SESSION_EVENT.to_string(),
    )
    .unwrap()
}

/// Every line of `<workdir>/trace.jsonl`, each parsed as its own JSON object.
fn trace_lines(workdir: &Path) -> Vec<Value> {
    let raw = fs::read_to_string(workdir.join("trace.jsonl")).unwrap();
    raw.lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| serde_json::from_str::<Value>(line).unwrap_or_else(|e| panic!("{line}: {e}")))
        .collect()
}

fn of_type<'a>(lines: &'a [Value], event_type: &str) -> Vec<&'a Value> {
    lines
        .iter()
        .filter(|line| line["event_type"] == event_type)
        .collect()
}

fn only<'a>(lines: &'a [Value], event_type: &str) -> &'a Value {
    let found = of_type(lines, event_type);
    assert_eq!(found.len(), 1, "{event_type}: {lines:#?}");
    found[0]
}

/// Every line opens with the five identity fields, in the order every other event type writes
/// them. Read off the raw text because parsing a line into a [`Value`] sorts its keys.
fn assert_identity_order(workdir: &Path) {
    for line in fs::read_to_string(workdir.join("trace.jsonl"))
        .unwrap()
        .lines()
    {
        assert!(line.starts_with("{\"event_type\":"), "{line}");
        let mut at = 0;
        for key in [
            "event_type",
            "event_id",
            "parent_id",
            "session_id",
            "timestamp",
        ] {
            let needle = format!("\"{key}\":");
            let found = line[at..]
                .find(&needle)
                .unwrap_or_else(|| panic!("{key} is missing or out of order: {line}"));
            at += found + needle.len();
        }
    }
}

/// Every line a plan run writes names this session and hangs off the node it should.
fn assert_identity(line: &Value, session_event: &str) {
    assert_eq!(line["session_id"], TEST_SESSION, "{line}");
    assert!(
        line["event_id"].as_str().unwrap().starts_with("evt_"),
        "{line}"
    );
    assert_eq!(line["parent_id"], session_event, "{line}");
}

#[test]
fn test_trace_records_a_two_step_plan_run() {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("out".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"a","tool":"echo","input":{"x":1}},
                {"id":"b","tool":"echo","depends_on":["a"]}
            ]
        }),
    );

    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_ctx(dir.path().to_path_buf(), &invoke, &trace),
    );
    assert!(report.completed, "{report:?}");

    assert_identity_order(dir.path());
    let lines = trace_lines(dir.path());
    let start = only(&lines, "plan_start");
    assert_identity(start, TEST_SESSION_EVENT);
    assert_eq!(start["plan_id"], "p");
    assert_eq!(start["step_count"], 2);
    assert_eq!(
        start["steps"],
        json!([
            {"step_id":"a","kind":"tool","depends_on":[],"has_condition":false},
            {"step_id":"b","kind":"tool","depends_on":["a"],"has_condition":false}
        ])
    );

    // Every later line of the run hangs off the plan node.
    let plan_node = start["event_id"].as_str().unwrap();
    for line in lines
        .iter()
        .filter(|line| line["event_type"] != "plan_start")
    {
        assert_identity(line, plan_node);
    }

    let starts = of_type(&lines, "plan_step_start");
    assert_eq!(starts.len(), 2, "{lines:#?}");
    assert_eq!(starts[0]["step_id"], "a");
    assert_eq!(starts[1]["step_id"], "b");
    assert_eq!(starts[1]["depends_on"], json!(["a"]));

    let steps = of_type(&lines, "plan_step");
    assert_eq!(steps.len(), 2, "{lines:#?}");
    for step in &steps {
        assert_eq!(step["plan_id"], "p");
        assert_eq!(step["kind"], "tool");
        assert_eq!(step["status"], "success");
        assert_eq!(step["attempts"], 1);
        assert!(step.get("error").is_none(), "{step}");
    }
    assert_eq!(steps[0]["input"], json!({"x":1}));
    // `b` declares no input, so the key is absent rather than written as null.
    assert!(steps[1].get("input").is_none(), "{}", steps[1]);

    // The first step settles before the second is dispatched: the dependency edge is legible
    // from the file order alone.
    let order: Vec<String> = lines
        .iter()
        .map(|line| format!("{}:{}", line["event_type"], line["step_id"]))
        .collect();
    let settled_a = order
        .iter()
        .position(|e| e == "\"plan_step\":\"a\"")
        .unwrap();
    let started_b = order
        .iter()
        .position(|e| e == "\"plan_step_start\":\"b\"")
        .unwrap();
    assert!(settled_a < started_b, "{order:?}");

    let end = only(&lines, "plan_end");
    assert_eq!(end["plan_id"], "p");
    assert_eq!(end["outcome"], "completed");
    assert_eq!(end["steps_total"], 2);
    assert_eq!(end["steps_succeeded"], 2);
    assert_eq!(end["steps_failed"], 0);
    assert_eq!(end["steps_skipped"], 0);
    assert!(end.get("failed_step").is_none(), "{end}");
    assert!(end.get("reason").is_none(), "{end}");
}

#[test]
fn test_trace_counts_every_attempt_of_a_retried_failure() {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Failed,
            None,
            Some("tool said no".to_string()),
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"fail","retries":2}]}),
    );

    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_ctx(dir.path().to_path_buf(), &invoke, &trace),
    );
    assert!(!report.completed, "{report:?}");

    let lines = trace_lines(dir.path());
    let step = only(&lines, "plan_step");
    assert_eq!(step["status"], "failed");
    assert_eq!(step["attempts"], 3);
    assert_eq!(step["error"], "tool said no");

    let end = only(&lines, "plan_end");
    assert_eq!(end["outcome"], "failed");
    assert_eq!(end["failed_step"], "a");
    assert_eq!(end["steps_failed"], 1);
    assert!(
        !lines.iter().any(|line| line["status"] == "success"),
        "{lines:#?}"
    );
}

#[test]
fn test_trace_records_a_condition_false_skip_as_never_dispatched() {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("out".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"a","tool":"echo"},
                {"id":"b","tool":"echo","depends_on":["a"],"if":"$a.status == 'failed'"}
            ]
        }),
    );

    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_ctx(dir.path().to_path_buf(), &invoke, &trace),
    );
    assert_eq!(find(&report, "b").status, StepStatus::Skipped, "{report:?}");

    let lines = trace_lines(dir.path());
    assert_eq!(
        only(&lines, "plan_start")["steps"][1]["has_condition"],
        json!(true)
    );

    // Dispatched: `a` only. A step that never ran must not read as one that ran.
    let starts = of_type(&lines, "plan_step_start");
    assert_eq!(starts.len(), 1, "{lines:#?}");
    assert_eq!(starts[0]["step_id"], "a");

    let skipped = of_type(&lines, "plan_step")
        .into_iter()
        .find(|line| line["step_id"] == "b")
        .unwrap();
    assert_eq!(skipped["status"], "skipped");
    assert_eq!(skipped["attempts"], 0);
    assert_eq!(skipped["duration_ms"], 0);
    assert!(skipped.get("error").is_none(), "{skipped}");

    let end = only(&lines, "plan_end");
    assert_eq!(end["outcome"], "completed");
    assert_eq!(end["steps_skipped"], 1);
    assert_eq!(end["steps_succeeded"], 1);
}

/// The trace and the returned report never disagree: `on_error: "skip"` demotes a failed step to
/// skipped in the report, and the line the scheduler writes reads the same.
#[test]
fn test_trace_reads_an_on_error_skip_demotion_as_skipped() {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Failed,
            None,
            Some("tool said no".to_string()),
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"fail","on_error":"skip"}]}),
    );

    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_ctx(dir.path().to_path_buf(), &invoke, &trace),
    );
    assert_eq!(find(&report, "a").status, StepStatus::Skipped, "{report:?}");

    let lines = trace_lines(dir.path());
    let step = only(&lines, "plan_step");
    assert_eq!(step["status"], "skipped");
    assert_eq!(step["attempts"], 1);
    // The demotion keeps the step's own error text, exactly as the report does.
    assert_eq!(step["error"], "tool said no");
    assert_eq!(only(&lines, "plan_end")["steps_skipped"], 1);
}

#[test]
fn test_a_rejected_plan_writes_its_shape_and_no_step_lines() {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("out".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"not-installed"}]}),
    );

    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_ctx(dir.path().to_path_buf(), &invoke, &trace),
    );
    assert!(!report.completed, "{report:?}");

    let lines = trace_lines(dir.path());
    assert_eq!(only(&lines, "plan_start")["step_count"], 1);
    assert!(of_type(&lines, "plan_step_start").is_empty(), "{lines:#?}");
    assert!(of_type(&lines, "plan_step").is_empty(), "{lines:#?}");

    let end = only(&lines, "plan_end");
    assert_eq!(end["outcome"], "failed");
    assert_eq!(end["failed_step"], "a");
    assert_eq!(end["steps_total"], 1);
    assert_eq!(end["steps_succeeded"], 0);
    assert!(
        end["reason"].as_str().unwrap().contains("is not installed"),
        "{end}"
    );
}

#[test]
fn test_a_malformed_plan_file_describes_no_dag() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("plan.json");
    fs::write(&path, "{ not json").unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("out".to_string()),
            None,
        ))
    };

    let trace = appender(dir.path());
    let report = plan::execute(
        &path,
        &traced_ctx(dir.path().to_path_buf(), &invoke, &trace),
    );
    assert!(!report.completed, "{report:?}");

    assert_identity_order(dir.path());
    let lines = trace_lines(dir.path());
    assert!(of_type(&lines, "plan_start").is_empty(), "{lines:#?}");
    let end = only(&lines, "plan_end");
    // No plan node to hang off: the summary parents to the session instead.
    assert_identity(end, TEST_SESSION_EVENT);
    assert_eq!(end["plan_id"], "");
    assert_eq!(end["outcome"], "failed");
    assert_eq!(end["failed_step"], "plan");
    assert_eq!(end["steps_total"], 0);
    assert!(
        end["reason"]
            .as_str()
            .unwrap()
            .contains("failed to parse plan JSON"),
        "{end}"
    );
}

/// A tool step carries what the tool declared about itself, so a plan run and an agent turn are
/// scored on the same resource history by `mur trace`.
#[test]
fn test_a_tool_step_carries_the_metadata_the_tool_declared() {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(ToolResult {
            status: ToolStatus::Passed,
            summary: None,
            data: Some("out".to_string()),
            data_path: None,
            truncated: false,
            metadata: vec![
                ("state_effect".to_string(), "read".to_string()),
                ("resource_id".to_string(), "src/lib.rs".to_string()),
            ],
            attachments: Vec::new(),
        })
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id":"p",
            "steps":[
                {"id":"a","tool":"echo","input":{"path":"src/lib.rs"}},
                {"id":"b","shell":"true"}
            ]
        }),
    );

    let trace = appender(dir.path());
    let mut context = traced_ctx(dir.path().to_path_buf(), &invoke, &trace);
    // `b` is refused by validation, which is enough to prove the shape a non-tool step gets in
    // `plan_start` without granting this test a subprocess and the cgroup scope that needs.
    context.capability_policy.shell_allow = Vec::new();
    let report = plan::execute(&plan, &context);
    assert!(!report.completed, "{report:?}");

    let lines = trace_lines(dir.path());
    assert_eq!(only(&lines, "plan_start")["steps"][1]["kind"], "shell");
    assert!(of_type(&lines, "plan_step").is_empty(), "{lines:#?}");

    // And again with the plan the validator accepts, to read the tool step's own line.
    let dir = tempdir().unwrap();
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"echo","input":{"path":"src/lib.rs"}}]}),
    );
    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_ctx(dir.path().to_path_buf(), &invoke, &trace),
    );
    assert!(report.completed, "{report:?}");

    let lines = trace_lines(dir.path());
    let step = only(&lines, "plan_step");
    assert_eq!(step["state_effect"], "read");
    assert_eq!(step["resource_id"], "src/lib.rs");
    assert_eq!(step["input"], json!({"path":"src/lib.rs"}));
}

/// A tool that declares nothing writes neither key, rather than writing them empty.
#[test]
fn test_an_undeclared_tool_step_omits_the_metadata_keys() {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("out".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"echo"}]}),
    );

    let trace = appender(dir.path());
    plan::execute(
        &plan,
        &traced_ctx(dir.path().to_path_buf(), &invoke, &trace),
    );

    let step = only(&trace_lines(dir.path()), "plan_step").clone();
    assert!(step.get("state_effect").is_none(), "{step}");
    assert!(step.get("resource_id").is_none(), "{step}");
}

/// The opt-in: a context carrying no appender opens no file and writes no line.
#[test]
fn test_no_appender_writes_no_trace_file() {
    let dir = tempdir().unwrap();
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("out".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"a","tool":"echo"}]}),
    );

    let mut context = ctx(dir.path().to_path_buf(), &invoke);
    context.capability_policy = CapabilityPolicy::default();
    let report = plan::execute(&plan, &context);

    assert!(report.completed, "{report:?}");
    assert!(!dir.path().join("trace.jsonl").exists());
}

// ── Delegation records ───────────────────────────────────────────────────────
//
// A `capsule` step launches a child on the same terms the agent-facing `delegate-task` tool does,
// and records it on the same terms: the same two event types, off the same session node, out of
// the same event structs. Nothing here names the plan or the step, because a reader of a trace
// must not be able to tell which surface launched a child.

/// [`ctx`] with a trace appender attached and every subprocess grant kept.
///
/// Unlike [`traced_ctx`], which drops `spawn_allow` so its cases run on a host that cannot
/// delegate a cgroup v2 scope, these cases delegate for real — so they keep the grant and stand
/// down behind [`capsule_runtime::skip_without_host_support`] instead.
fn traced_capsule_ctx<'a>(
    workdir: PathBuf,
    invoke_tool: &'a (dyn Fn(&str, ToolInput) -> Result<ToolResult, String> + Sync),
    appender: &'a capsule_runtime::PlanTraceAppender,
) -> SchedulerContext<'a> {
    let mut context = ctx(workdir, invoke_tool);
    context.trace = Some(appender);
    context
}

/// Every `delegation_start`, paired with the `delegation` line carrying the same id and the
/// positions of both in the file.
fn delegation_pairs(lines: &[Value]) -> Vec<(usize, &Value, usize, &Value)> {
    lines
        .iter()
        .enumerate()
        .filter(|(_, line)| line["event_type"] == "delegation_start")
        .map(|(at, start)| {
            let id = start["delegation_id"].as_str().unwrap();
            let (end_at, end) = lines
                .iter()
                .enumerate()
                .find(|(_, line)| line["event_type"] == "delegation" && line["delegation_id"] == id)
                .unwrap_or_else(|| panic!("no delegation line joins {id}: {lines:#?}"));
            (at, start, end_at, end)
        })
        .collect()
}

/// Three `capsule` steps with no `depends_on` between them run at once, and the parent's trace
/// carries one record pair per child — three distinct `dlg_` ids, each opened before it is closed.
#[test]
fn test_three_concurrent_capsule_steps_record_three_delegations() {
    if capsule_runtime::skip_without_host_support(
        "test_three_concurrent_capsule_steps_record_three_delegations",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::start();
    let _stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let plan = write_plan(
        dir.path(),
        json!({
            "id": "fan-out",
            "steps": [
                {"id": "one", "capsule": "worker", "input": {"objective": "first"}},
                {"id": "two", "capsule": "worker", "input": {"objective": "second"}},
                {"id": "three", "capsule": "worker", "input": {"objective": "third"}}
            ]
        }),
    );

    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_capsule_ctx(dir.path().to_path_buf(), &unused_tool, &trace),
    );
    std::env::remove_var("MURMUR_ROOST_URL");
    assert!(report.completed, "{report:?}");

    let lines = trace_lines(dir.path());
    let starts = of_type(&lines, "delegation_start");
    let ends = of_type(&lines, "delegation");
    assert_eq!(starts.len(), 3, "{lines:#?}");
    assert_eq!(ends.len(), 3, "{lines:#?}");
    // The plan-step records this run also writes are a different pair describing a different
    // thing; nothing else in the file is a delegation record.
    assert_eq!(
        lines
            .iter()
            .filter(|line| line["event_type"]
                .as_str()
                .unwrap()
                .starts_with("delegation"))
            .count(),
        6,
        "{lines:#?}"
    );

    let mut ids = Vec::new();
    for (start_at, start, end_at, end) in delegation_pairs(&lines) {
        assert_identity(start, TEST_SESSION_EVENT);
        assert_identity(end, TEST_SESSION_EVENT);
        let id = start["delegation_id"].as_str().unwrap();
        assert!(
            id.strip_prefix("dlg_").is_some_and(|rest| !rest.is_empty()
                && rest
                    .chars()
                    .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase())),
            "{id}"
        );
        for key in ["capsule", "version", "child_session_id", "child_workdir"] {
            assert!(!start[key].as_str().unwrap().is_empty(), "{key}: {start}");
        }
        // The start always reaches disk while the child is still in flight, so it is always the
        // earlier of the two lines.
        assert!(start_at < end_at, "{start} came after {end}");
        assert_eq!(end["outcome"], "completed", "{end}");
        assert!(end["reason"].is_null(), "{end}");
        assert_eq!(end["capsule"], start["capsule"], "{end}");
        assert_eq!(end["child_session_id"], start["child_session_id"], "{end}");
        ids.push(id.to_string());
    }
    ids.sort();
    ids.dedup();
    assert_eq!(ids.len(), 3, "{lines:#?}");

    // Nothing naming the plan, the step or the surface that launched the child is on either
    // record: that is what makes a plan's delegation indistinguishable from a `delegate-task` one.
    for line in starts.into_iter().chain(ends) {
        for key in ["plan_id", "step_id", "surface", "kind"] {
            assert!(line.get(key).is_none(), "{key} is on {line}");
        }
    }
}

/// Each child a `capsule` step launches is told which session and conversation spawned it, and
/// under which delegation — the same handle a `delegate-task` child is launched with.
#[test]
fn test_a_capsule_step_launches_its_child_naming_its_parent() {
    if capsule_runtime::skip_without_host_support(
        "test_a_capsule_step_launches_its_child_naming_its_parent",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::start();
    let stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"worker","capsule":"worker","input":{"objective":"go"}}]}),
    );

    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_capsule_ctx(dir.path().to_path_buf(), &unused_tool, &trace),
    );
    std::env::remove_var("MURMUR_ROOST_URL");
    assert!(report.completed, "{report:?}");

    let env = stub.recorded("env.txt");
    let value = env
        .lines()
        .find_map(|line| line.strip_prefix("MURMUR_SPAWNER="))
        .unwrap_or_else(|| panic!("the child was launched with no MURMUR_SPAWNER: {env}"));
    let handle = capsule_runtime::SpawnerHandle::parse(value).unwrap();

    assert_eq!(handle.session_id, TEST_SESSION);
    assert_eq!(handle.context_id, TEST_CONTEXT);
    // Lineage only: this delegation's answer arrives on the connection the step is holding, so
    // there is nowhere for the child to report and no address for it to report to.
    assert_eq!(handle.report_to, None);

    let lines = trace_lines(dir.path());
    assert_eq!(
        only(&lines, "delegation_start")["delegation_id"]
            .as_str()
            .unwrap(),
        handle.delegation_id,
    );
}

/// A refusal launched nothing, so it opens no row: one terminal line naming no child, carrying
/// the daemon's own sentence — the same sentence the step failed with.
#[test]
fn test_a_refused_capsule_step_delegation_is_traced_with_the_daemons_reason() {
    if capsule_runtime::skip_without_host_support(
        "test_a_refused_capsule_step_delegation_is_traced_with_the_daemons_reason",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::refusing_spawn();
    let _stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let plan = write_plan(
        dir.path(),
        json!({"id":"p","steps":[{"id":"worker","capsule":"worker","input":{"objective":"go"}}]}),
    );

    let trace = appender(dir.path());
    let report = plan::execute(
        &plan,
        &traced_capsule_ctx(dir.path().to_path_buf(), &unused_tool, &trace),
    );
    std::env::remove_var("MURMUR_ROOST_URL");
    assert!(!report.completed, "{report:?}");

    let lines = trace_lines(dir.path());
    assert!(of_type(&lines, "delegation_start").is_empty(), "{lines:#?}");
    let end = only(&lines, "delegation");
    assert_identity(end, TEST_SESSION_EVENT);
    assert_eq!(end["outcome"], "refused", "{end}");
    assert!(end["delegation_id"].is_null(), "{end}");
    assert!(end["child_session_id"].is_null(), "{end}");
    assert_eq!(end["capsule"], "local/worker", "{end}");
    assert_eq!(
        end["reason"].as_str().unwrap(),
        find(&report, "worker").error.as_deref().unwrap(),
    );
}

/// A plan that delegates to nobody writes no delegation record, whether it was handed an appender
/// or not — and with no appender it opens no `trace.jsonl` at all.
#[test]
fn test_a_plan_with_no_capsule_steps_writes_no_trace_file() {
    // Its shell step is a real subprocess, so it wants the same bounded host every other case
    // that starts one does.
    if capsule_runtime::skip_without_host_support(
        "test_a_plan_with_no_capsule_steps_writes_no_trace_file",
    ) {
        return;
    }
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("out".to_string()),
            None,
        ))
    };

    for traced in [true, false] {
        let dir = tempdir().unwrap();
        let plan = write_plan(
            dir.path(),
            json!({
                "id": "p",
                "steps": [
                    {"id": "a", "tool": "echo", "input": {"x": 1}},
                    {"id": "b", "shell": "printf hello", "depends_on": ["a"]}
                ]
            }),
        );

        // `PlanTraceAppender::open` creates the file, so the traced run is asserted on the
        // delegation records it holds rather than on the file not existing.
        let report = if traced {
            let trace = appender(dir.path());
            let mut context = ctx(dir.path().to_path_buf(), &invoke);
            context.capability_policy.spawn_allow = Vec::new();
            context.trace = Some(&trace);
            let report = plan::execute(&plan, &context);
            let lines = trace_lines(dir.path());
            assert!(of_type(&lines, "delegation_start").is_empty(), "{lines:#?}");
            assert!(of_type(&lines, "delegation").is_empty(), "{lines:#?}");
            report
        } else {
            let mut context = ctx(dir.path().to_path_buf(), &invoke);
            context.capability_policy.spawn_allow = Vec::new();
            let report = plan::execute(&plan, &context);
            assert!(!dir.path().join("trace.jsonl").exists());
            report
        };
        assert!(report.completed, "traced={traced}: {report:?}");
    }
}

// ── The task a plan runs for ──────────────────────────────────────────────────

/// A [`plan::PlanTask`] that records what the scheduler told it and reports cancelled once
/// `canceled` is raised.
#[derive(Default)]
struct RecordingTask {
    canceled: AtomicBool,
    started: Mutex<Vec<String>>,
    settled: Mutex<Vec<String>>,
}

impl plan::PlanTask for RecordingTask {
    fn is_canceled(&self) -> bool {
        self.canceled.load(Ordering::SeqCst)
    }

    fn delegation_started(&self, launch: &capsule_runtime::DelegationLaunch) {
        self.started
            .lock()
            .unwrap()
            .push(launch.delegation_id.clone());
    }

    /// Always the step's to close: nothing here takes rows the way a task's end does.
    fn delegation_settled(&self, delegation_id: &str) -> bool {
        self.settled.lock().unwrap().push(delegation_id.to_string());
        true
    }
}

/// Whether a process with this pid still exists, reaped or not.
fn process_exists(pid: &str) -> bool {
    Path::new("/proc").join(pid.trim()).exists()
}

/// A cancel that lands while a `capsule` step's sub-capsule is running ends that sub-capsule from
/// inside the step, records it `terminated` in the child's own directory, and stops the plan: the
/// step is not retried, its dependant never runs, and a step that was already running beside it
/// keeps its own result. The delegation's row is left to the task, so the step closes nothing.
#[test]
fn test_a_cancelled_task_ends_its_capsule_steps_sub_capsule() {
    if capsule_runtime::skip_without_host_support(
        "test_a_cancelled_task_ends_its_capsule_steps_sub_capsule",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::never_finishing();
    let stub = StubMur::install_lingering(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let invoke = |_name: &str, _input: ToolInput| {
        Ok(tool_result(
            ToolStatus::Passed,
            Some("side-output".to_string()),
            None,
        ))
    };
    let plan = write_plan(
        dir.path(),
        json!({
            "id": "p",
            "steps": [
                {"id": "slow", "capsule": "worker", "input": "hold the line", "retries": 2},
                {"id": "after", "tool": "echo", "depends_on": ["slow"], "input": {"text": "never"}},
                {"id": "side", "tool": "echo", "input": {"text": "beside"}}
            ]
        }),
    );

    let task = RecordingTask::default();
    let ctx = SchedulerContext {
        task: Some(&task),
        ..ctx(dir.path().to_path_buf(), &invoke)
    };
    let raised_at = Mutex::new(None);
    let (report, returned_at) = thread::scope(|scope| {
        scope.spawn(|| {
            let deadline = std::time::Instant::now() + Duration::from_secs(30);
            while task.started.lock().unwrap().is_empty() {
                if std::time::Instant::now() >= deadline {
                    return;
                }
                thread::sleep(Duration::from_millis(20));
            }
            thread::sleep(Duration::from_secs(1));
            *raised_at.lock().unwrap() = Some(std::time::Instant::now());
            task.canceled.store(true, Ordering::SeqCst);
        });
        let report = plan::execute(&plan, &ctx);
        (report, std::time::Instant::now())
    });
    std::env::remove_var("MURMUR_ROOST_URL");

    let raised_at = raised_at
        .into_inner()
        .unwrap()
        .unwrap_or_else(|| panic!("the child never started: {report:?}"));
    let took = returned_at.duration_since(raised_at);
    assert!(
        took < Duration::from_secs(3),
        "execute returned {took:?} after the cancel"
    );

    assert!(report.canceled, "{report:?}");
    assert!(!report.completed);
    assert_eq!(report.failed_step, None);
    let slow = find(&report, "slow");
    assert_eq!(slow.status, StepStatus::Failed);
    assert_eq!(slow.error.as_deref(), Some(plan::CANCELED_STEP_ERROR));
    let after = find(&report, "after");
    assert_eq!(after.status, StepStatus::Skipped);
    assert_eq!(
        after.error.as_deref(),
        Some(plan::CANCELED_BEFORE_STEP_ERROR)
    );
    assert_eq!(find(&report, "side").status, StepStatus::Success);

    assert_eq!(task.started.lock().unwrap().len(), 1);
    assert!(task.settled.lock().unwrap().is_empty());

    let pid = stub.recorded("pid.txt");
    assert!(!process_exists(&pid), "the stub child {pid} is still there");
    let children: Vec<PathBuf> = fs::read_dir(records_of(dir.path()).join("children"))
        .unwrap()
        .flatten()
        .map(|entry| entry.path())
        .collect();
    assert_eq!(children.len(), 1, "{children:?}");
    let completion: Value = serde_json::from_str(
        &fs::read_to_string(stub.records_dir.join("completion.json"))
            .expect("the ended child's outcome is recorded"),
    )
    .unwrap();
    assert_eq!(completion["status"], "terminated", "{completion}");
    assert_eq!(completion["reported_by"], "launcher", "{completion}");
    assert_eq!(completion["delivered"], json!(false), "{completion}");
    assert_eq!(
        completion["detail"],
        capsule_runtime::delegation::PARENT_ENDED_DETAIL,
        "{completion}"
    );
    assert_eq!(
        completion["delegation_id"],
        json!(task.started.lock().unwrap()[0]),
        "{completion}"
    );
}

/// A task nobody cancels is told about its step's child once on launch and once on settling, for
/// the same id, and the step writes its own terminal `delegation` line as it does with no task.
#[test]
fn test_a_capsule_step_that_completes_settles_its_own_delegation() {
    if capsule_runtime::skip_without_host_support(
        "test_a_capsule_step_that_completes_settles_its_own_delegation",
    ) {
        return;
    }
    let _guard = roost_env_lock().lock().unwrap();
    let dir = tempdir().unwrap();
    let fake_roost = FakeRoost::start();
    let _stub = StubMur::install(fake_roost.authority());
    std::env::set_var("MURMUR_ROOST_URL", &fake_roost.url);
    let plan = write_plan(
        dir.path(),
        json!({"id": "p", "steps": [{"id": "worker", "capsule": "worker", "input": "go"}]}),
    );

    let trace = appender(dir.path());
    let task = RecordingTask::default();
    let report = plan::execute(
        &plan,
        &SchedulerContext {
            task: Some(&task),
            ..traced_capsule_ctx(dir.path().to_path_buf(), &unused_tool, &trace)
        },
    );
    std::env::remove_var("MURMUR_ROOST_URL");

    assert!(report.completed && !report.canceled, "{report:?}");
    let started = task.started.lock().unwrap().clone();
    let settled = task.settled.lock().unwrap().clone();
    assert_eq!(started.len(), 1, "{started:?}");
    assert_eq!(settled, started);

    let lines = trace_lines(dir.path());
    let ended = only(&lines, "delegation");
    assert_eq!(ended["outcome"], "completed", "{ended}");
    assert_eq!(ended["delegation_id"], json!(started[0]), "{ended}");
    assert_eq!(only(&lines, "plan_end")["outcome"], "completed");
}