aither-sandbox 0.26.0

Terminal-first command execution with heel sandboxing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
//! Terminal command tool implementation with heel sandboxing.
//!
//! Provides the main `terminal` tool that LLMs use to execute terminal work.
//! Despite the historical tool name, execution does not have to go through a
//! literal `terminal` process: simple commands may be executed directly, while shell
//! syntax falls back to a real shell when needed.
//! Commands run in a sandbox with configurable permission modes.
//!
//! Each `TerminalTool` works in one shared working directory. All terminal
//! executions share this directory, but each execution gets a fresh sandbox
//! (new TTY/process). The ids the model addresses — task ids, stored output
//! names, subagent spaces — are leased from the terminal's
//! [`AnyIdAllocator`](aither_core::AnyIdAllocator).

use crate::foreground_wait::ForegroundWait;
use crate::grants::{GitDirAccess, GrantSet, TerminalGrants};
use crate::heel_binary::SharedHeelBinary;
use crate::memory::{
    AnyContainerMemory, AnyFootprintReader, AnyFootprintRegistry, FootprintReader,
    FootprintRegistry, JobMemory, ProbedContainerMemory, ResponseWindow, SystemFootprints,
};
use crate::outage::Outages;
use std::{
    borrow::Cow,
    future::Future,
    io::{Read, Write},
    net::{SocketAddr, TcpListener as StdTcpListener, TcpStream as StdTcpStream},
    path::{Path, PathBuf},
    pin::Pin,
    process::Stdio,
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
    time::Duration,
};

use aither_core::llm::{CallIdentity, ToolContext};
use aither_core::llm::{
    CommandOutcome, CommandResult, CommandStream, Interruption, IntoToolResult, StoredFile, Tool,
    ToolResult,
};
use aither_core::{AnyIdAllocator, IdLease, IdsExhausted};
use askama::Template;
use async_channel::{Receiver, Sender};
use async_io::Async;
use executor_core::{Executor, Task};
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
#[cfg(target_os = "linux")]
use heel::supervisor::{TreeControl, TreeReport};
use heel::{
    Access, Audited, CpuPriority, DomainRequest, Grant, IoPriority, IpcRouter, NetworkAuditLog,
    NetworkPolicy, ProcessPriority, ResolvedPath, Sandbox, SandboxConfig, SecurityConfig,
    StdioConfig, WorkingDir,
};
/// On platforms without `heel supervise` a wait produces no report.
#[cfg(not(target_os = "linux"))]
struct TreeReport;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use shell_words::split as split_shell_words;
use tracing::{debug, info, warn};

#[cfg(all(unix, feature = "jobserver"))]
use crate::jobserver::{JobBroker, JobPool, job_broker_channel};
use crate::{
    ContainerPath, MountRoot, PolicyRefusal, PreparedTools, ScriptOrigin, ScriptOutcome,
    ToolDistribution, ToolRuntimeError,
    builtin::builtin_router,
    command::{
        AnyCommandGate, AnyCommandObserver, CommandBlocked, CommandRole, GateDecision, ToolRegistry,
    },
    job_registry::{JobRegistry, JobStatus, PendingCompletion, job_registry_channel},
    output::{INLINE_OUTPUT_LIMIT, MediaResolution, OutputFormat, OutputStore, stored_path},
    permission::{PermissionError, PermissionHandler, PermissionRequest, Review, TerminalMode},
    process_tree::{JobMarker, JobProcess, JobTree},
    script_language::ScriptLanguage,
    shell_session::{
        BridgeAddress, ContainerExecOutcome, ContainerShellRuntime, ExecLifetime, ShellBackend,
        ShellRuntimeAvailability, ShellSessionRegistry, SshRuntimeProfile,
    },
    stdin_watch::{
        EpisodeDetector, FeedCounter, LocalStdinProbe, STDIN_WATCH_INTERVAL, StdinWatchSignal,
    },
    subagent::{
        AnySubagentSpaces, CommitLedger, CommittingWorktree, ImportBudget, ImportLimits,
        LaunchHistory, Launcher, PreparedSpace, ResolvedGrant, RunSpace, Spelling, SubagentGit,
        SubagentGrant, SubagentGrantError, SubagentSpaces, canonical as canonical_path,
    },
};

mod subagent_git;

pub fn erase_terminal_tool<T>(tool: T) -> crate::command::DynTerminalToolEntry
where
    T: Tool + 'static,
{
    use crate::command::{DynTerminalToolEntry, DynToolHandler};
    use aither_core::llm::tool::ToolDefinition;

    let definition = ToolDefinition::new(&tool);
    let tool = Arc::new(tool);
    let handler: DynToolHandler = Arc::new(move |args: &str, cx: ToolContext| {
        let tool = tool.clone();
        let args = args.to_string();
        Box::pin(async move {
            let parsed = match serde_json::from_str::<T::Arguments>(&args) {
                Ok(parsed) => parsed,
                Err(error) => return ToolResult::error(format!("Parse error: {error}")),
            };
            match tool.call(parsed, cx).await {
                Ok(output) => output
                    .into_tool_result()
                    .unwrap_or_else(|error| ToolResult::error(format!("Error: {error}"))),
                Err(error) => ToolResult::error(format!("Error: {error}")),
            }
        })
    });

    DynTerminalToolEntry {
        definition,
        handler,
    }
}

/// Opens a daily-rotated network audit log under `dir`, creating the directory if needed.
///
/// Keeps at most `max_files` rotated files. Attach the log with
/// [`TerminalTool::with_network_audit_log`] to record every sandboxed
/// network policy decision.
///
/// # Errors
/// Returns an error when the directory cannot be created or the log cannot
/// be opened.
pub async fn open_network_audit_log(
    dir: impl AsRef<Path>,
    max_files: usize,
) -> Result<NetworkAuditLog, TerminalError> {
    let dir = dir.as_ref();
    async_fs::create_dir_all(dir).await?;
    NetworkAuditLog::rolling_daily(dir, max_files).map_err(|error| {
        TerminalError::SandboxSetup(format!("failed to open network audit log: {error}"))
    })
}

#[derive(Clone)]
struct PermissionNetworkPolicy<P> {
    permission_handler: Arc<P>,
}

impl<P: PermissionHandler + 'static> NetworkPolicy for PermissionNetworkPolicy<P> {
    async fn check(&self, request: &DomainRequest) -> bool {
        self.permission_handler
            .authorize_domain(request.host(), request.port())
            .await
    }
}

fn parse_direct_command(script: &str) -> Result<(String, Vec<String>), TerminalError> {
    let parts = split_shell_words(script)
        .map_err(|error| TerminalError::Execution(format!("failed to parse command: {error}")))?;
    let Some((program, args)) = parts.split_first() else {
        return Err(TerminalError::Execution(
            "command must not be empty".to_string(),
        ));
    };
    Ok((program.clone(), args.to_vec()))
}

enum TerminalLaunch {
    Direct { program: String, args: Vec<String> },
    Shell { program: String, args: Vec<String> },
}

fn script_requires_shell(script: &str) -> bool {
    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;

    for ch in script.chars() {
        if escaped {
            escaped = false;
            continue;
        }

        match ch {
            '\\' if !in_single => escaped = true,
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            '\n' | '\r' | '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '*' | '?' | '['
            | ']' | '{' | '}' | '!' | '~'
                if !in_single && !in_double =>
            {
                return true;
            }
            _ => {}
        }
    }

    false
}

fn looks_like_env_assignment(token: &str) -> bool {
    let Some((name, _value)) = token.split_once('=') else {
        return false;
    };
    !name.is_empty() && name.chars().all(|c| c == '_' || c.is_ascii_alphanumeric())
}

fn is_shell_builtin(program: &str) -> bool {
    matches!(
        program,
        "alias"
            | "bg"
            | "break"
            | "cd"
            | "command"
            | "continue"
            | "eval"
            | "exec"
            | "exit"
            | "export"
            | "fg"
            | "jobs"
            | "read"
            | "readonly"
            | "return"
            | "set"
            | "shift"
            | "source"
            | "times"
            | "trap"
            | "type"
            | "ulimit"
            | "umask"
            | "unalias"
            | "unset"
    )
}

/// The program and arguments that run `script` in a shell. Windows runs
/// `cmd.exe`; every other platform runs `managed_shell`, the managed bash.
fn shell_launch(managed_shell: &str, script: &str) -> (String, Vec<String>) {
    #[cfg(windows)]
    {
        let _ = managed_shell;
        let shell = std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string());
        return (shell, vec!["/C".to_string(), script.to_string()]);
    }

    #[cfg(not(windows))]
    {
        (
            managed_shell.to_string(),
            crate::tool_runtime::shell_arguments(script),
        )
    }
}

/// The shell script that runs `script`, written in `language`, for the job
/// `task_id`.
fn launch_script<'a>(
    language: ScriptLanguage,
    script: &'a str,
    task_id: &str,
) -> Result<Cow<'a, str>, TerminalError> {
    language.launch_script(script, task_id).map_err(|error| {
        TerminalError::Execution(format!("failed to render the launch script: {error}"))
    })
}

/// Turns `script` into the process to launch. A shell launch with a `report`
/// file records the shell's final directory there when it exits; a direct
/// command cannot change directory, so it reports nothing.
fn build_terminal_launch(
    managed_shell: &str,
    script: &str,
    report: Option<&Path>,
) -> Result<TerminalLaunch, TerminalError> {
    let script = script.trim();
    if script.is_empty() {
        return Err(TerminalError::Execution(
            "command must not be empty".to_string(),
        ));
    }

    match direct_command(script)? {
        Some((program, args)) => Ok(TerminalLaunch::Direct { program, args }),
        None => shell_launch_reporting(managed_shell, script, report),
    }
}

/// The program and arguments of a script that runs without a shell, or
/// `None` when it needs one.
fn direct_command(script: &str) -> Result<Option<(String, Vec<String>)>, TerminalError> {
    if script_requires_shell(script) {
        return Ok(None);
    }
    let (program, args) = parse_direct_command(script)?;
    if looks_like_env_assignment(&program) || is_shell_builtin(&program) {
        return Ok(None);
    }
    Ok(Some((program, args)))
}

/// Whether a local launch of `script` runs in a shell, the only way a
/// command can change directory.
fn runs_in_shell(script: &str) -> bool {
    matches!(direct_command(script.trim()), Ok(None))
}

/// A command killed because its `timeout` bound passed, with the UTC times it
/// started and was killed at.
///
/// [`SandboxNotices::command_killed`](crate::SandboxNotices::command_killed)
/// renders the sentence the model reads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeoutKill {
    /// The `timeout` the command was bounded by.
    pub timeout: Duration,
    /// When the command started.
    pub started: jiff::Timestamp,
    /// When the kill was issued.
    pub killed: jiff::Timestamp,
}

/// What the kill watchdog of one job records: when the job started, and when
/// the watchdog issued the kill, if it did.
#[derive(Debug)]
struct TimeoutWatch {
    timeout: Duration,
    started: jiff::Timestamp,
    killed: std::sync::OnceLock<jiff::Timestamp>,
}

impl TimeoutWatch {
    fn new(timeout: Duration) -> Self {
        Self {
            timeout,
            started: jiff::Timestamp::now(),
            killed: std::sync::OnceLock::new(),
        }
    }

    /// The kill, once the watchdog has issued one.
    fn kill(&self) -> Option<TimeoutKill> {
        self.killed.get().map(|killed| TimeoutKill {
            timeout: self.timeout,
            started: self.started,
            killed: *killed,
        })
    }
}

#[derive(Template)]
#[template(path = "carry_cwd.sh", escape = "none")]
struct CarryCwdTemplate<'a> {
    escaped_report: &'a str,
    escaped_script: &'a str,
}

fn shell_launch_reporting(
    managed_shell: &str,
    script: &str,
    report: Option<&Path>,
) -> Result<TerminalLaunch, TerminalError> {
    let Some(report) = report else {
        let (program, args) = shell_launch(managed_shell, script);
        return Ok(TerminalLaunch::Shell { program, args });
    };
    let script = carry_cwd_script(script, &report.to_string_lossy())?;
    let (program, args) = shell_launch(managed_shell, &script);
    Ok(TerminalLaunch::Shell { program, args })
}

/// `script`, run through `eval`, followed by a trailer that writes the
/// shell's final directory to `report`, a path as the shell sees it, and
/// exits with the script's status.
///
/// The report is not written from an `EXIT` trap: setting one makes a
/// non-interactive bash catch SIGTERM, and a child it has just forked still
/// carries that handler until it resets its signals, so a `kill` sent in that
/// window is swallowed and the process it names runs on. `eval` keeps the
/// trailer out of reach of the script's own syntax, such as an unterminated
/// here-document. A script that ends through `exit` writes no report.
fn carry_cwd_script(script: &str, report: &str) -> Result<String, TerminalError> {
    let escaped_report = shell_escape(report);
    let escaped_script = shell_escape(script);
    CarryCwdTemplate {
        escaped_report: &escaped_report,
        escaped_script: &escaped_script,
    }
    .render()
    .map_err(|error| {
        TerminalError::Execution(format!("failed to render directory report: {error}"))
    })
}

async fn ensure_mode_allowed<P: PermissionHandler>(
    permission_handler: &P,
    mode: TerminalMode,
    script: &str,
    language: ScriptLanguage,
) -> Result<(), TerminalError> {
    if !mode.requires_approval() {
        return Ok(());
    }

    let allowed = permission_handler.check(mode, script, language).await?;
    if allowed {
        Ok(())
    } else {
        Err(TerminalError::PermissionDenied(mode))
    }
}

/// Execute terminal commands in a sandboxed environment.
///
/// The primary interface to all system capabilities. Scripts run in a sandbox
/// with full read access to the host filesystem but writes contained to a
/// dedicated working directory.
///
/// ## Output Handling
///
/// By default, stdout is **compressed** before being returned. Compression
/// is semantics-preserving: the meaning is identical to the raw output, but
/// the representation may differ. Specifically:
///
/// - **JSON** outputs (arrays of objects or single objects) are automatically
///   converted to **TSV** with dot-notation flattened column headers, but
///   only when the TSV is smaller than the original JSON.
/// - **Source code** outputs (detected via content analysis) are folded
///   using syntax-aware block folding with line numbers. The full raw
///   output is saved to a file whose URL is included in the result.
/// - **Empty lines** and **invisible/control characters** are stripped.
///
/// If you need the exact verbatim output (e.g., for checksums, binary
/// protocols, or diffing), either set `raw: true`, pipe through further
/// processing in the script, or redirect to a file within the script.
///
/// Large outputs are automatically saved to file to manage context. When this
/// happens, you receive the file path and can process it using standard Unix
/// tools (head, tail, grep, less) or pipe through `ask` for summarization.
///
/// ## Built-in Commands
///
/// IPC-backed commands are configured by the host application and are exposed
/// inside the terminal runtime as ordinary CLI commands. Inspect the
/// application-provided command list and each command's `--help` output instead
/// of assuming a fixed built-in command inventory.
///
/// ## Execution Modes
///
/// Each call selects its own runtime mode and starts a fresh shell; only a
/// successful `cd` carries over to the next call. `timeout` is required:
/// it is the job's maximum runtime in seconds — the job and its process
/// tree are killed when it passes — and it may be at most 120 minutes.
///
/// By default the call waits in the foreground for up to 10 seconds. A
/// command still running then **promotes to a background task**: the call
/// returns the task id and the output captured so far, and the job keeps
/// running under its `timeout` bound. Manage it with `terminal_read`
/// (incremental output), `terminal_input` (stdin) and `terminal_kill`.
/// Set `background: true` to detach immediately instead of waiting.
///
/// `language` is `shell` by default; `python` runs `script` as Python source,
/// without a shell wrapper.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TerminalArgs {
    /// Short human-readable explanation of what this command is doing.
    /// This is shown in the UI instead of echoing the shell source.
    pub description: String,

    /// The terminal command payload to execute.
    pub script: String,

    /// The language of `script`.
    /// - "shell" (default): shell source
    /// - "python": Python source, run from a file so tracebacks carry line numbers
    #[serde(default)]
    pub language: ScriptLanguage,

    /// Runtime execution mode.
    /// - "default": local runtime execution with network enabled
    /// - "sandboxed": local runtime execution with network denied
    /// - "unsafe": direct host execution (heel profile only)
    /// - "ssh": execute on a preconfigured SSH server (`ssh_server_id` required when multiple are configured)
    #[serde(default)]
    pub mode: TerminalExecutionMode,

    /// SSH server identifier used when `mode` is `ssh`.
    /// Optional when exactly one SSH server is configured.
    #[serde(default)]
    pub ssh_server_id: Option<String>,

    /// Expected output format for proper handling.
    /// - "text" (default): plain text
    /// - "image": image data (auto-loaded to context)
    /// - "video": video data
    /// - "binary": binary data
    /// - "auto": auto-detect
    #[serde(default)]
    pub expect: OutputFormat,

    /// Requested delivery resolution for media returned to the model.
    /// - "auto" (default): preserve the source resolution
    /// - "low": downscale to a 512px bounding box
    /// - "medium": downscale to a 1024px bounding box
    /// - "high": downscale to a 2048px bounding box
    /// - "native": preserve original media bytes without resizing
    #[serde(default)]
    pub resolution: MediaResolution,

    /// Maximum number of output lines to include inline.
    /// For foreground executions, this is the inline line budget
    /// before output offloads to file.
    /// For executions detached with `background: true` or promoted past
    /// the foreground window, only the first `max_lines` are returned
    /// immediately, while full output is redirected to file.
    /// Clamped to 800 max.
    /// Default: 200.
    #[serde(default = "default_max_lines")]
    pub max_lines: u32,

    /// When true, skip all output compression and return the verbatim
    /// stdout bytes. Use this when you need exact byte-level fidelity
    /// (checksums, binary protocols, diff inputs). Default: false.
    #[serde(default)]
    pub raw: bool,

    /// Maximum runtime of the command in seconds. Required. The command and
    /// its process tree are killed when it passes; the value may be at most
    /// 7200 (120 minutes).
    pub timeout: u64,

    /// Start the command detached and return immediately with its task id
    /// instead of waiting in the foreground. Default: false — the call
    /// waits up to the foreground window and promotes a still-running
    /// command to a background task.
    #[serde(default)]
    pub background: bool,
}

/// Requested terminal execution backend.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TerminalExecutionMode {
    /// Use the tool default.
    #[default]
    Default,
    /// Use the sandboxed backend.
    Sandboxed,
    /// Use unsafe local execution.
    Unsafe,
    /// Use SSH execution.
    Ssh,
}

const fn default_max_lines() -> u32 {
    200
}

const MAX_LINES_CEILING: u32 = 800;

/// How long a `terminal` call waits in the foreground before a still-running
/// command promotes to a background task.
pub const DEFAULT_FOREGROUND_WAIT: Duration = Duration::from_secs(10);
/// How long the agent has to act on a final memory warning by default.
pub const DEFAULT_RESPONSE_WINDOW: Duration = Duration::from_secs(120);
/// The default of the most bytes a subagent's sandbox may send the host while
/// its commits are imported into the main repository.
pub const DEFAULT_SUBAGENT_IMPORT_LIMIT: u64 = 1024 * 1024 * 1024;
/// Largest `timeout` a command accepts.
pub const DEFAULT_TIMEOUT_CAP: Duration = Duration::from_secs(120 * 60);
/// A background job still running after this long produces one system alert.
pub const DEFAULT_LONG_JOB_ALERT_AFTER: Duration = Duration::from_secs(40 * 60);

/// Time bounds applied to every execution this terminal spawns.
#[derive(Debug, Clone)]
struct TerminalLimits {
    /// Foreground wait before a `terminal` call promotes to a background
    /// task.
    foreground_wait: ForegroundWait,
    /// Maximum accepted `timeout` for a command.
    timeout_cap: Duration,
    /// Runtime after which a background job produces a long-running alert.
    long_job_alert: Duration,
    /// Most bytes a subagent's sandbox may send while its commits are
    /// imported; shared with every terminal derived from this one, and
    /// adjustable at runtime.
    subagent_import: ImportBudget,
    /// How long the agent has to act on a final memory warning; adjustable
    /// at runtime and shared with every terminal derived from this one.
    response_window: ResponseWindow,
    /// Reads what the terminal's jobs hold of the machine's memory.
    footprints: AnyFootprintReader,
    /// Shares the total the agent's jobs hold with the machine's other
    /// agents; `None` when the embedder configured no registry.
    footprint_registry: Option<AnyFootprintRegistry>,
}

impl Default for TerminalLimits {
    fn default() -> Self {
        Self {
            response_window: ResponseWindow::new(DEFAULT_RESPONSE_WINDOW),
            footprints: AnyFootprintReader::new(SystemFootprints),
            footprint_registry: None,
            foreground_wait: ForegroundWait::new(DEFAULT_FOREGROUND_WAIT),
            timeout_cap: DEFAULT_TIMEOUT_CAP,
            long_job_alert: DEFAULT_LONG_JOB_ALERT_AFTER,
            subagent_import: ImportBudget::new(DEFAULT_SUBAGENT_IMPORT_LIMIT),
        }
    }
}

/// A background job that crossed the long-running threshold.
///
/// Sent through the terminal's alert channel once per job; the agent turns
/// it into a durable system alert.
#[derive(Debug, Clone)]
pub struct LongRunningJob {
    /// Task ID of the job, a word leased from the terminal's id allocator.
    pub task_id: String,
    /// The script the job runs.
    pub script: String,
    /// How long the job had been running when the alert fired.
    pub elapsed: Duration,
}

/// A background job whose stdin pipe has a reader waiting for input.
///
/// Sent once per blocking episode: the job is not alerted again until it has
/// been fed through `terminal_input` and blocks anew.
#[derive(Debug, Clone)]
pub struct StdinBlockedJob {
    /// Task ID of the job.
    pub task_id: String,
    /// The script the job runs.
    pub script: String,
}

/// A background job whose stdin watch failed; carries the probe's error.
///
/// Sent once: after a failure the job can no longer report being blocked on
/// stdin.
#[derive(Debug, Clone)]
pub struct StdinProbeFailedJob {
    /// Task ID of the job.
    pub task_id: String,
    /// The script the job runs.
    pub script: String,
    /// Why the watch failed.
    pub error: String,
}

/// Why the next foreground command does not start where the last one left
/// the shell.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectoryResetReason {
    /// The command failed, so the directory it ended in is not carried.
    Failed,
    /// The command ended through `exit` or a signal and reported no
    /// directory.
    Unreported,
    /// The directory it ended in lies outside the paths the terminal may
    /// read.
    OutsideReadable,
    /// The directory it ended in lies outside the container's workspace
    /// mount.
    OutsideWorkspace,
    /// The directory no longer exists.
    Removed,
}

/// The working directory carried between foreground commands was reset.
///
/// Sent once per reset, at the moment it happens.
#[derive(Debug, Clone)]
pub struct DirectoryReset {
    /// The directory the next command runs in, as the command sees it.
    pub dir: PathBuf,
    /// Why the shell's directory was not carried.
    pub reason: DirectoryResetReason,
}

/// The most processes a [`DescendantsKilled`] alert names.
const KILLED_PROCESSES_NAMED: usize = 8;

/// Processes a foreground command left running when its shell exited, killed
/// with it.
///
/// Sent once per command, at the moment they were killed.
#[derive(Debug, Clone)]
pub struct DescendantsKilled {
    /// The first processes killed, at most eight.
    pub processes: Vec<JobProcess>,
    /// How many more were killed beyond those named.
    pub omitted: usize,
}

impl DescendantsKilled {
    fn new(mut killed: Vec<JobProcess>) -> Self {
        let omitted = killed.len().saturating_sub(KILLED_PROCESSES_NAMED);
        killed.truncate(KILLED_PROCESSES_NAMED);
        Self {
            processes: killed,
            omitted,
        }
    }
}

/// A system alert about a background job, or about the carried working
/// directory, delivered through the terminal's alert channel.
#[derive(Debug, Clone)]
pub enum JobAlert {
    /// A foreground command's shell exited while descendants were still
    /// running, and they were killed.
    DescendantsKilled(DescendantsKilled),
    /// The directory carried between foreground commands was reset.
    DirectoryReset(DirectoryReset),
    /// The job crossed the long-running threshold.
    LongRunning(LongRunningJob),
    /// The job is waiting for input on its stdin.
    StdinBlocked(StdinBlockedJob),
    /// Watching the job's stdin failed; no blocked-on-stdin alert can follow.
    StdinProbeFailed(StdinProbeFailedJob),
    /// A monitor collected new output lines from its watched job.
    MonitorIncrement(crate::monitor::MonitorIncrement),
    /// A monitor saw no new output for its stall window.
    MonitorStalled(crate::monitor::MonitorStalled),
    /// A monitor ended, reporting why.
    MonitorEnded(crate::monitor::MonitorEnded),
}

/// A command that ran to completion.
#[derive(Debug, Clone)]
pub struct CompletedCommand {
    /// stdout output.
    pub stdout: CommandStream,

    /// stderr output (if non-empty).
    pub stderr: Option<CommandStream>,

    /// Exit code of the script.
    pub exit_code: i32,

    /// Sleep and offline intervals the command ran through.
    pub interruptions: Vec<Interruption>,
}

impl From<CompletedCommand> for CommandResult {
    fn from(command: CompletedCommand) -> Self {
        Self {
            stdout: command.stdout,
            stderr: command.stderr,
            outcome: CommandOutcome::Exited {
                code: command.exit_code,
            },
            interruptions: command.interruptions,
        }
    }
}

/// A job `terminal` has just detached as a background task — started with
/// `background: true` or promoted past the foreground window.
///
/// Sent through the terminal's started-task channel once per launched job;
/// the agent turns it into a durable reminder and a `background_task_started`
/// event.
#[derive(Debug, Clone)]
pub struct StartedBackgroundTask {
    /// Task ID of the job, a word leased from the terminal's id allocator.
    pub task_id: String,
    /// First lines of the redirected output; empty when nothing was written yet.
    pub output_preview: String,
    /// File receiving the full redirected output.
    pub output_file: StoredFile,
}

#[derive(Clone)]
struct BackgroundStartup {
    tx: async_channel::Sender<Result<(), String>>,
    reported: Arc<AtomicBool>,
}

impl BackgroundStartup {
    fn new(tx: async_channel::Sender<Result<(), String>>) -> Self {
        Self {
            tx,
            reported: Arc::new(AtomicBool::new(false)),
        }
    }

    async fn report_ready(&self) {
        if self
            .reported
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
        {
            let _ = self.tx.send(Ok(())).await;
        }
    }

    async fn report_failure(&self, error: &TerminalError) {
        if self
            .reported
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
        {
            let _ = self.tx.send(Err(error.to_string())).await;
        }
    }
}

/// A completed background task result.
#[derive(Debug)]
pub struct CompletedTask {
    /// The task ID, a word leased from the terminal's id allocator.
    pub task_id: String,
    /// The original script that was executed.
    pub script: String,
    /// The result of execution.
    pub result: Result<CompletedCommand, TerminalError>,
    /// Why the job was killed — its `timeout` bound, `terminal_kill` or a
    /// memory runaway — or `None` when it exited on its own.
    pub kill: Option<crate::KillCause>,
    /// Set when the kill was the `timeout` bound passing.
    pub timeout_kill: Option<TimeoutKill>,
    /// Keeps the job in its registry, and its task id leased, until the agent
    /// takes the completion by dropping it; `None` for a command the registry
    /// never registered and for one whose call returned its result.
    pub pending: Option<PendingCompletion>,
}

/// Stage of a permission-lifecycle event for `terminal`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionEventStage {
    /// Permission request is waiting for a decision.
    Waiting,
    /// Permission request has been resolved.
    Resolved,
}

/// Permission-lifecycle event emitted by `terminal` while waiting for approval.
#[derive(Debug, Clone)]
pub struct PermissionEvent {
    /// Requested terminal mode.
    pub mode: TerminalMode,
    /// Script awaiting permission.
    pub script: String,
    /// The language of `script`.
    pub language: ScriptLanguage,
    /// Permission lifecycle stage.
    pub stage: PermissionEventStage,
}

/// Receiver for completed background tasks.
///
/// This can be cloned and used independently of the `TerminalTool` to poll for
/// completed background tasks. Multiple receivers share the same channel,
/// so completed tasks are distributed among receivers.
#[derive(Clone)]
pub struct BackgroundTaskReceiver {
    rx: Receiver<CompletedTask>,
    alert_rx: Receiver<JobAlert>,
    started_rx: Receiver<StartedBackgroundTask>,
    running_tasks: Arc<AtomicUsize>,
}

/// Sender half of a [`BackgroundTaskReceiver`] channel.
///
/// A `TerminalTool` owns the sender side internally; the exposed pair lets
/// tests and embedders drive a receiver without a live terminal backend:
/// `task_started`/`task_finished` move the running counter the receiver's
/// `has_running` reads, and the `send_*` methods deliver the same payloads
/// spawned executions produce.
#[derive(Clone, Debug)]
pub struct BackgroundTaskSender {
    completed_tx: Sender<CompletedTask>,
    alert_tx: Sender<JobAlert>,
    started_tx: Sender<StartedBackgroundTask>,
    running_tasks: Arc<AtomicUsize>,
}

impl BackgroundTaskSender {
    /// Records a task start: `has_running` on the paired receiver turns true.
    pub fn task_started(&self) {
        self.running_tasks.fetch_add(1, Ordering::AcqRel);
    }

    /// Records a task end: decrements the running counter.
    ///
    /// # Panics
    ///
    /// Panics when more tasks are finished than were started — the counter
    /// can never go negative, so a mismatched pair is a bug in the driver.
    pub fn task_finished(&self) {
        let previous = self.running_tasks.fetch_sub(1, Ordering::AcqRel);
        assert!(
            previous > 0,
            "task_finished without a matching task_started"
        );
    }

    /// Delivers a completed-task event to the receiver.
    pub async fn send_completed(&self, task: CompletedTask) {
        let _ = self.completed_tx.send(task).await;
    }

    /// Delivers a job alert to the receiver.
    pub async fn send_alert(&self, alert: JobAlert) {
        let _ = self.alert_tx.send(alert).await;
    }

    /// Delivers a background-task-started event to the receiver.
    pub async fn send_started(&self, task: StartedBackgroundTask) {
        let _ = self.started_tx.send(task).await;
    }
}

/// Creates a standalone [`BackgroundTaskSender`]/[`BackgroundTaskReceiver`]
/// pair disconnected from any `TerminalTool`, mirroring
/// [`job_registry_channel`](crate::job_registry_channel).
#[must_use]
pub fn background_task_channel() -> (BackgroundTaskSender, BackgroundTaskReceiver) {
    let (completed_tx, rx) = async_channel::unbounded();
    let (alert_tx, alert_rx) = async_channel::unbounded();
    let (started_tx, started_rx) = async_channel::unbounded();
    let running_tasks = Arc::new(AtomicUsize::new(0));
    (
        BackgroundTaskSender {
            completed_tx,
            alert_tx,
            started_tx,
            running_tasks: running_tasks.clone(),
        },
        BackgroundTaskReceiver {
            rx,
            alert_rx,
            started_rx,
            running_tasks,
        },
    )
}

impl BackgroundTaskReceiver {
    /// Takes all completed background tasks without blocking.
    ///
    /// Returns an empty vector if no tasks have completed.
    #[must_use]
    pub fn take_completed(&self) -> Vec<CompletedTask> {
        let mut completed = Vec::new();
        while let Ok(task) = self.rx.try_recv() {
            completed.push(task);
        }
        completed
    }

    /// Takes all pending job alerts without blocking.
    ///
    /// A job produces at most one [`JobAlert::LongRunning`], and one
    /// [`JobAlert::StdinBlocked`] per blocking episode.
    #[must_use]
    pub fn take_job_alerts(&self) -> Vec<JobAlert> {
        let mut alerts = Vec::new();
        while let Ok(alert) = self.alert_rx.try_recv() {
            alerts.push(alert);
        }
        alerts
    }

    /// Takes all freshly started background tasks without blocking.
    ///
    /// Each entry names a job `terminal` has just detached; a job produces
    /// exactly one.
    #[must_use]
    pub fn take_started(&self) -> Vec<StartedBackgroundTask> {
        let mut started = Vec::new();
        while let Ok(task) = self.started_rx.try_recv() {
            started.push(task);
        }
        started
    }

    /// Checks if there are any completed tasks waiting.
    #[must_use]
    pub fn has_completed(&self) -> bool {
        !self.rx.is_empty()
    }

    /// Checks if there are any background tasks still running.
    ///
    /// This works by checking the sender count - `TerminalTool` holds one sender,
    /// and each running background task holds a cloned sender.
    #[must_use]
    pub fn has_running(&self) -> bool {
        self.running_tasks.load(Ordering::Acquire) > 0
    }

    /// Waits for the next completed task.
    ///
    /// Returns `None` if the channel is closed (all senders dropped).
    pub async fn recv(&self) -> Option<CompletedTask> {
        self.rx.recv().await.ok()
    }

    /// Waits for a completed task with a timeout.
    ///
    /// Returns `None` if no task completes within the timeout or if the channel is closed.
    pub async fn recv_timeout(&self, duration: std::time::Duration) -> Option<CompletedTask> {
        futures_lite::future::or(async { self.rx.recv().await.ok() }, async {
            futures_lite::future::yield_now().await;
            async_io::Timer::after(duration).await;
            None
        })
        .await
    }

    /// Waits for the next completed task or job alert.
    ///
    /// Cancel-safe: an event is taken only when this future completes, so a
    /// caller racing it against other work loses nothing. A closed channel
    /// never ends the wait.
    pub async fn recv_event(&self) -> BackgroundTaskEvent {
        futures_lite::future::or(
            async {
                match self.rx.recv().await {
                    Ok(task) => BackgroundTaskEvent::Completed(Box::new(task)),
                    Err(_) => std::future::pending().await,
                }
            },
            async {
                match self.alert_rx.recv().await {
                    Ok(alert) => BackgroundTaskEvent::Alert(alert),
                    Err(_) => std::future::pending().await,
                }
            },
        )
        .await
    }

    /// Waits for the next completed task or job alert, bounded by `duration`.
    ///
    /// Returns `None` when nothing arrives in time; a closed channel never
    /// ends the wait early.
    pub async fn recv_event_timeout(
        &self,
        duration: std::time::Duration,
    ) -> Option<BackgroundTaskEvent> {
        futures_lite::future::or(
            async {
                match self.rx.recv().await {
                    Ok(task) => Some(BackgroundTaskEvent::Completed(Box::new(task))),
                    // A closed channel never yields again; only the timer
                    // may end the wait, or callers would spin.
                    Err(_) => std::future::pending().await,
                }
            },
            futures_lite::future::or(
                async {
                    match self.alert_rx.recv().await {
                        Ok(alert) => Some(BackgroundTaskEvent::Alert(alert)),
                        Err(_) => std::future::pending().await,
                    }
                },
                async {
                    futures_lite::future::yield_now().await;
                    async_io::Timer::after(duration).await;
                    None
                },
            ),
        )
        .await
    }
}

/// What ended a [`BackgroundTaskReceiver::recv_event_timeout`] wait.
#[derive(Debug)]
pub enum BackgroundTaskEvent {
    /// A background task completed; boxed to keep the enum small.
    Completed(Box<CompletedTask>),
    /// A job alert arrived.
    Alert(JobAlert),
}

impl std::fmt::Debug for BackgroundTaskReceiver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BackgroundTaskReceiver")
            .field("pending", &self.rx.len())
            .field("pending_alerts", &self.alert_rx.len())
            .field("pending_started", &self.started_rx.len())
            .field("running_tasks", &self.running_tasks.load(Ordering::Acquire))
            .finish()
    }
}

/// Receiver for permission wait/resume events.
#[derive(Clone)]
pub struct PermissionEventReceiver {
    rx: Receiver<PermissionEvent>,
}

impl PermissionEventReceiver {
    /// Takes pending permission events without blocking.
    #[must_use]
    pub fn take_pending(&self) -> Vec<PermissionEvent> {
        let mut events = Vec::new();
        while let Ok(event) = self.rx.try_recv() {
            events.push(event);
        }
        events
    }

    /// Waits for the next permission event.
    pub async fn recv(&self) -> Option<PermissionEvent> {
        self.rx.recv().await.ok()
    }
}

impl std::fmt::Debug for PermissionEventReceiver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PermissionEventReceiver")
            .field("pending", &self.rx.len())
            .finish()
    }
}

/// Launches subagents from one terminal: every subagent it creates runs with
/// at most that terminal's authority.
///
/// Each terminal that serves a registry owns one, handed to its terminal-bound
/// commands through its [`TerminalBinding`].
#[derive(Clone, Debug)]
pub struct TerminalToolFactory {
    tx: Sender<TerminalToolRequest>,
}

/// One request to a terminal's launcher: the grant the subagent launches with
/// and where the finished tool goes.
#[derive(Debug)]
struct TerminalToolRequest {
    grant: SubagentGrant,
    observer: Option<AnyCommandObserver>,
    gate: Option<AnyCommandGate>,
    caller: Option<PathBuf>,
    reply: Sender<Result<crate::command::DynTerminalTool, SubagentGrantError>>,
}

/// Errors that can occur when requesting a subagent terminal tool.
#[derive(Debug, thiserror::Error)]
pub enum TerminalToolFactoryError {
    /// The launching terminal is gone.
    #[error("terminal tool factory is not available")]
    Unavailable,
    /// The factory failed to return a tool.
    #[error("terminal tool factory failed to return a tool")]
    NoResponse,
    /// The subagent's grant cannot be given.
    #[error(transparent)]
    Grant(#[from] SubagentGrantError),
}

impl TerminalToolFactory {
    /// Requests a new subagent terminal tool from the terminal this launcher
    /// belongs to.
    ///
    /// The tool serves the subagent registry and runs in a space of its own
    /// inside the launching terminal's working directory; `grant` is
    /// everything it may write beyond that space, and must lie inside what the
    /// launching terminal can write. The commands it calls are told to
    /// `observer`, and every shell command it runs is put to `gate`. When the
    /// launching terminal has [`SubagentSpaces`], they prepare the space
    /// first and are told `caller`, the directory the launch is asked for
    /// from (the launching terminal's working directory when `None`).
    ///
    /// # Errors
    /// Returns an error when the launching terminal is gone or does not
    /// respond, when the grant cannot be given, or when the space cannot be
    /// prepared.
    pub async fn create(
        &self,
        grant: SubagentGrant,
        observer: Option<AnyCommandObserver>,
        gate: Option<AnyCommandGate>,
        caller: Option<&Path>,
    ) -> Result<crate::command::DynTerminalTool, TerminalToolFactoryError> {
        let (reply, reply_rx) = async_channel::bounded(1);
        self.tx
            .send(TerminalToolRequest {
                grant,
                observer,
                gate,
                caller: caller.map(Path::to_path_buf),
                reply,
            })
            .await
            .map_err(|_| TerminalToolFactoryError::Unavailable)?;
        Ok(reply_rx
            .recv()
            .await
            .map_err(|_| TerminalToolFactoryError::NoResponse)??)
    }
}

/// Serves a terminal's launch requests: their grants are resolved one at a
/// time, so the grants handed out from it are recorded in one place, and
/// each launch then goes on, its space prepared, beside the others.
///
/// `source` is the terminal with its registry not yet bound: it holds no
/// handle to its own launcher, so the loop ends once every terminal-bound
/// command holding the launcher is gone.
async fn serve_launches<P, E>(
    requests: Receiver<TerminalToolRequest>,
    source: TerminalTool<P, E, Launching>,
) where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    let mut history = LaunchHistory::default();
    while let Ok(TerminalToolRequest {
        grant,
        observer,
        gate,
        caller,
        reply,
    }) = requests.recv().await
    {
        let resolved = match source.resolve_launch(&mut history, grant).await {
            Ok(resolved) => resolved,
            Err(error) => {
                if reply.send(Err(error)).await.is_err() {
                    warn!("terminal tool factory response channel dropped");
                }
                continue;
            }
        };
        let source = source.clone();
        source
            .executor
            .clone()
            .spawn(async move {
                let tool = source
                    .launch_resolved(resolved, observer, gate, caller.as_deref())
                    .await
                    .map(TerminalTool::to_dyn);
                if reply.send(tool).await.is_err() {
                    warn!("terminal tool factory response channel dropped");
                }
            })
            .detach();
    }
}

/// What a terminal hands the commands bound to it: where it works, the
/// launcher for the subagents it starts and the runner for the scripts it
/// runs for them.
#[derive(Clone, Debug)]
pub struct TerminalBinding {
    launcher: TerminalToolFactory,
    runner: TerminalRunner,
    working_dir: PathBuf,
    role: CommandRole,
    observer: Option<AnyCommandObserver>,
    executor: Arc<executor_core::AnyExecutor>,
    ids: AnyIdAllocator,
}

impl TerminalBinding {
    /// The allocator the terminal leases its model-facing ids from, for a
    /// command bound to it that names things for the model too.
    #[must_use]
    pub const fn id_allocator(&self) -> &AnyIdAllocator {
        &self.ids
    }

    /// The executor the terminal runs its tasks on, for work that must
    /// outlive the call that started it.
    #[must_use]
    pub fn executor(&self) -> &executor_core::AnyExecutor {
        &self.executor
    }

    /// Launches subagents from this terminal, within its authority.
    #[must_use]
    pub const fn launcher(&self) -> &TerminalToolFactory {
        &self.launcher
    }

    /// Runs scripts on this terminal, under its policy.
    #[must_use]
    pub const fn runner(&self) -> &TerminalRunner {
        &self.runner
    }

    /// The terminal's working directory: the main agent's sandbox, or a
    /// subagent's own space.
    #[must_use]
    pub fn working_dir(&self) -> &Path {
        &self.working_dir
    }

    /// The role the terminal's command registry serves: the main agent's, or
    /// a subagent's at any depth.
    #[must_use]
    pub const fn role(&self) -> CommandRole {
        self.role
    }

    /// The observer told about the commands this terminal's registry serves.
    #[must_use]
    pub const fn observer(&self) -> Option<&AnyCommandObserver> {
        self.observer.as_ref()
    }
}

/// A script a [`TerminalRunner`] runs to its end.
#[derive(Debug, Clone)]
pub struct TerminalScript {
    script: String,
    working_dir: PathBuf,
    timeout: Duration,
    mode: TerminalMode,
}

impl TerminalScript {
    /// `script`, started in `working_dir` on the host and killed with its
    /// process tree once `timeout` passes, in [`TerminalMode::Sandboxed`].
    /// For a container terminal, `working_dir` lies in its workspace mount.
    #[must_use]
    pub fn new(
        script: impl Into<String>,
        working_dir: impl Into<PathBuf>,
        timeout: Duration,
    ) -> Self {
        Self {
            script: script.into(),
            working_dir: working_dir.into(),
            timeout,
            mode: TerminalMode::Sandboxed,
        }
    }

    /// Runs the script in `mode`; an unsafe one is put to the terminal's
    /// permission handler like any unsafe command.
    #[must_use]
    pub const fn with_mode(mut self, mode: TerminalMode) -> Self {
        self.mode = mode;
        self
    }
}

/// Why a [`TerminalRunner`] run did not run to an end.
#[derive(Debug, thiserror::Error)]
pub enum TerminalRunError {
    /// The terminal that served the command is gone.
    #[error("the terminal serving this command is gone")]
    TerminalGone,
    /// The timeout is zero or above the terminal's cap.
    #[error("timeout must be between 1 and {} seconds", .cap.as_secs())]
    Timeout {
        /// The longest timeout the terminal accepts.
        cap: Duration,
    },
    /// A command policy refused the script.
    #[error(transparent)]
    Refused(PolicyRefusal),
    /// The terminal's command gate blocked the script.
    #[error(transparent)]
    Blocked(crate::Refused<CommandBlocked>),
    /// The terminal runs in a container that declares no workspace mount,
    /// so no host directory maps into it.
    #[error("the container declares no workspace mount, so a run cannot start in a host directory")]
    NoWorkspaceMount,
    /// The working directory lies outside the container's workspace mount.
    #[error(transparent)]
    OutsideWorkspace(#[from] crate::MountRootError),
    /// The terminal could not run the script: no backend for its mode, a
    /// refused permission or a failed execution.
    #[error(transparent)]
    Terminal(#[from] TerminalError),
    /// Every model-facing id is leased, so the command has no task id.
    #[error(transparent)]
    Ids(#[from] IdsExhausted),
}

/// Runs scripts on the terminal that serves a terminal-bound command.
///
/// A run is under that terminal's whole policy: its grants, network policy,
/// backend (local sandbox or container), command gate, permission handler,
/// process priority, environment and jobserver. Each run is a job of the
/// terminal, listed and killable like any other, but never announced as a
/// background task: its end is told to the caller alone.
///
/// Cloning shares the terminal.
#[derive(Clone)]
pub struct TerminalRunner(Arc<dyn TerminalRunnerImpl>);

impl TerminalRunner {
    /// Runs `script` to its end, through the foreground window and past it,
    /// and returns its exit status and output; a run its timeout killed ends
    /// [`CommandOutcome::Killed`].
    ///
    /// # Errors
    /// Returns an error when the terminal is gone, the timeout is out of
    /// range, the terminal's policy refuses the script, the working
    /// directory does not map into the terminal's container, or the
    /// execution fails.
    pub async fn run(&self, script: TerminalScript) -> Result<CommandResult, TerminalRunError> {
        self.0.run(script).await
    }
}

impl std::fmt::Debug for TerminalRunner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TerminalRunner").finish_non_exhaustive()
    }
}

/// The object-safe twin behind [`TerminalRunner`].
trait TerminalRunnerImpl: Send + Sync {
    fn run(
        &self,
        script: TerminalScript,
    ) -> Pin<Box<dyn Future<Output = Result<CommandResult, TerminalRunError>> + Send + '_>>;
}

/// A terminal's runner: the terminal, as configured when its registry was
/// bound, and that bound registry.
///
/// The registry is held weakly: it holds the commands, which hold this
/// runner, so the terminal's copy here holds no registry of its own and the
/// runner ends with the terminal.
struct BoundRunner<P, E> {
    terminal: TerminalTool<P, E, Unconfigured>,
    registry: std::sync::Weak<ToolRegistry>,
}

impl<P, E> TerminalRunnerImpl for BoundRunner<P, E>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    fn run(
        &self,
        script: TerminalScript,
    ) -> Pin<Box<dyn Future<Output = Result<CommandResult, TerminalRunError>> + Send + '_>> {
        Box::pin(async move {
            let registry = self
                .registry
                .upgrade()
                .ok_or(TerminalRunError::TerminalGone)?;
            self.terminal
                .clone()
                .map_state(|Unconfigured| Running { registry })
                .run_to_end(script)
                .await
        })
    }
}

/// The registry state of the copy of a terminal one run executes on: the
/// terminal's bound registry, held for the run.
#[derive(Clone, Debug)]
struct Running {
    registry: Arc<ToolRegistry>,
}

impl RegistryState for Running {
    fn registry(&self) -> &Arc<ToolRegistry> {
        &self.registry
    }
}

/// The terminal tool for executing scripts in a sandbox.
///
/// Creates a shared working directory that persists across all executions,
/// named by heel with four random words; that name is not one of the leased
/// model-facing ids. Each execution creates a fresh sandbox but shares the
/// working directory.
///
/// The executor type `E` determines how async tasks are spawned for the IPC server.
/// Use `TokioExecutor` when running in a tokio runtime.
/// Marker type for a terminal tool without a configured registry.
#[derive(Clone, Debug)]
pub struct Unconfigured;

/// Marker type for a terminal tool with a configured registry, bound to the
/// terminal.
#[derive(Clone, Debug)]
pub struct Configured {
    registry: Arc<ToolRegistry>,
    binding: TerminalBinding,
}

/// The registry state of the copy of a terminal its launch loop holds: the
/// registry is not bound, so the copy holds no handle to its own launcher.
#[derive(Clone, Debug)]
pub struct Launching {
    registry: Arc<ToolRegistry>,
}

/// A registry state a terminal can launch subagents from.
///
/// Sealed: declared `pub` only so it may bound the `TerminalTool` impl that
/// launches subagents; it lives in this private module and is not
/// re-exported.
pub trait RegistryState: Clone + Send + Sync {
    /// The registry the terminal serves; a subagent's registry derives from it.
    fn registry(&self) -> &Arc<ToolRegistry>;
}

impl RegistryState for Configured {
    fn registry(&self) -> &Arc<ToolRegistry> {
        &self.registry
    }
}

impl RegistryState for Launching {
    fn registry(&self) -> &Arc<ToolRegistry> {
        &self.registry
    }
}

/// What a subagent's terminal holds that the main agent's does not.
#[derive(Clone, Debug)]
struct SubagentAuthority {
    /// Keeps the word naming its space leased while the terminal lives.
    _space_name: IdLease,
    /// The worktrees it may commit in, with their git data; it hands on no
    /// other commit grant.
    committing: Vec<CommittingWorktree>,
    /// Runs git in its sandbox, as it, for the host's view of its commits.
    git: SubagentGit,
    /// Where its commands run when its home backend is a container: its
    /// space and granted paths, mapped through the container's workspace
    /// mount when it was launched.
    container: Option<ContainerConfinement>,
    /// What the launcher's [`SubagentSpaces`] made in its space; `None` when
    /// the launcher has none.
    prepared: Option<PreparedSpace>,
}

/// A subagent launch whose grant is resolved: everything the launch still
/// needs from what the launching terminal handed out.
struct ResolvedLaunch {
    /// The launching terminal's working directory and grants, canonical.
    authority: Vec<PathBuf>,
    /// Where the subagent's space goes.
    spaces_root: PathBuf,
    /// The container workspace mount, for a container terminal.
    mount: Option<MountRoot>,
    granted: ResolvedGrant,
}

/// The main agent's working directory, carried from one foreground command
/// to the next. `None` inside means the terminal's own working directory.
#[derive(Clone, Default)]
struct CarriedDir(Arc<Mutex<Option<PathBuf>>>);

impl CarriedDir {
    fn get(&self) -> Option<PathBuf> {
        self.0.lock().expect("carried directory lock").clone()
    }

    fn set(&self, dir: Option<PathBuf>) {
        *self.0.lock().expect("carried directory lock") = dir;
    }
}

/// Where a command starts, and for a foreground command of the main agent,
/// the report of the directory it ended in.
#[derive(Clone)]
struct CwdCarry {
    /// Where the command starts.
    start: Option<PathBuf>,
    /// The file the command's shell writes its final directory to when it
    /// exits; `None` for a command that carries no directory, such as a
    /// script a [`TerminalRunner`] runs.
    report: Option<PathBuf>,
    /// Set for a container command: the workspace mount that maps the host
    /// paths above into the container and back.
    container: Option<ContainerCarry>,
    /// Whether the command runs in a shell and so writes the report; a
    /// direct command cannot change directory and writes none.
    shell: bool,
}

/// How a container command spells its start and directory report.
#[derive(Clone)]
struct ContainerCarry {
    mount: MountRoot,
    /// Where the container sees the report file, when there is one.
    report: Option<ContainerPath>,
    /// Where the command starts inside the container.
    start: ContainerPath,
}

/// The terminal tool for executing scripts in a sandbox.
pub struct TerminalTool<P, E, State = Unconfigured> {
    /// Shared working directory, named by heel with four random words (e.g.,
    /// `amber-forest-thunder-pearl/`) rather than a leased id.
    working_dir: PathBuf,
    /// Runtime registry for container and ssh execution metadata.
    shell_sessions: ShellSessionRegistry,
    /// Permission handler wrapped in Arc for sharing between parent and child tools.
    permission_handler: Arc<P>,
    executor: E,
    /// Leases the words naming what the model addresses: task ids, stored
    /// outputs and subagent spaces. Shared with the output store and every
    /// subagent terminal launched from this one.
    ids: AnyIdAllocator,
    output_store: OutputStore,
    job_registry: JobRegistry,
    /// Channel for receiving completed background tasks.
    completed_rx: Receiver<CompletedTask>,
    /// Channel for sending completed background tasks (cloned for each background task).
    completed_tx: Sender<CompletedTask>,
    /// Channel for receiving long-running job alerts.
    alert_rx: Receiver<JobAlert>,
    /// Channel for sending long-running job alerts (cloned for each watchdog).
    alert_tx: Sender<JobAlert>,
    /// Channel for receiving freshly started background tasks.
    started_rx: Receiver<StartedBackgroundTask>,
    /// Channel for announcing freshly started background tasks.
    started_tx: Sender<StartedBackgroundTask>,
    /// Time bounds applied to spawned executions.
    limits: TerminalLimits,
    /// Number of still-running spawned executions associated with this tool.
    running_tasks: Arc<AtomicUsize>,
    /// Channel for permission lifecycle events.
    permission_rx: Receiver<PermissionEvent>,
    /// Channel sender for permission lifecycle events.
    permission_tx: Sender<PermissionEvent>,
    /// Filesystem grants, shared by every clone; commands snapshot them at
    /// launch.
    grants: TerminalGrants,
    /// Set on a subagent's terminal, never on the main agent's.
    subagent: Option<SubagentAuthority>,
    /// The working directory the next foreground command starts in; held on
    /// the main agent's terminal only, a subagent's commands always start in
    /// its own space.
    carried_dir: Option<CarriedDir>,
    /// Extra environment variables resolved for each spawned execution.
    env_source: Option<Arc<dyn TerminalEnvSource>>,
    /// Rolling audit log recording every sandboxed network policy decision.
    network_audit: Option<NetworkAuditLog>,
    /// Scheduling priority applied to every sandboxed execution.
    priority: ProcessPriority,
    /// Shared jobserver token broker, when configured.
    #[cfg(all(unix, feature = "jobserver"))]
    jobserver: Option<JobBroker>,
    /// The verified `heel` binary every sandbox this tool creates carries,
    /// shared by its clones and its subagents' tools.
    heel: SharedHeelBinary,
    /// Records the outages commands run through.
    outages: Outages,
    /// Prepares the space of every subagent launched from this terminal and,
    /// at any depth, from theirs.
    subagent_spaces: Option<AnySubagentSpaces>,
    /// Tool registry state.
    registry: State,
}

// Manual Clone impl because P doesn't need to be Clone (we use Arc<P>)
impl<P, E: Clone, State: Clone> Clone for TerminalTool<P, E, State> {
    fn clone(&self) -> Self {
        Self {
            working_dir: self.working_dir.clone(),
            shell_sessions: self.shell_sessions.clone(),
            permission_handler: self.permission_handler.clone(),
            executor: self.executor.clone(),
            ids: self.ids.clone(),
            output_store: self.output_store.clone(),
            job_registry: self.job_registry.clone(),
            completed_rx: self.completed_rx.clone(),
            completed_tx: self.completed_tx.clone(),
            alert_rx: self.alert_rx.clone(),
            alert_tx: self.alert_tx.clone(),
            started_rx: self.started_rx.clone(),
            started_tx: self.started_tx.clone(),
            limits: self.limits.clone(),
            running_tasks: self.running_tasks.clone(),
            permission_rx: self.permission_rx.clone(),
            permission_tx: self.permission_tx.clone(),
            grants: self.grants.clone(),
            subagent: self.subagent.clone(),
            carried_dir: self.carried_dir.clone(),
            env_source: self.env_source.clone(),
            network_audit: self.network_audit.clone(),
            priority: self.priority,
            #[cfg(all(unix, feature = "jobserver"))]
            jobserver: self.jobserver.clone(),
            heel: self.heel.clone(),
            outages: self.outages.clone(),
            subagent_spaces: self.subagent_spaces.clone(),
            registry: self.registry.clone(),
        }
    }
}

impl<P, E: Executor + Clone + 'static> TerminalTool<P, E, Unconfigured> {
    /// Injects the runtime configuration used by `terminal` execution mode resolution.
    ///
    /// The registry is configuration to prepare with [`Self::initialize_tools`];
    /// a registry that is already prepared is installed with
    /// [`Self::adopt_prepared_tools`], which checks it against this terminal.
    ///
    /// # Panics
    /// Panics if `sessions` is already prepared.
    #[must_use]
    pub fn with_shell_sessions(mut self, sessions: ShellSessionRegistry) -> Self {
        assert!(
            sessions.prepared_tools.is_none(),
            "a prepared shell session registry is installed with adopt_prepared_tools"
        );
        self.shell_sessions = sessions;
        self
    }

    /// Sets dynamic runtime availability for terminal execution.
    #[must_use]
    pub fn with_shell_runtime_availability(
        mut self,
        availability: crate::shell_session::ShellRuntimeAvailability,
    ) -> Self {
        self.shell_sessions = self.shell_sessions.with_availability(availability);
        self
    }

    /// Adds container runtime metadata for container-backed terminal execution.
    #[must_use]
    pub fn with_container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
        self.shell_sessions = self.shell_sessions.with_container_runtime(runtime);
        self
    }

    /// Records every sandboxed network policy decision — allowed or denied —
    /// into the given rolling audit log.
    #[must_use]
    pub fn with_network_audit_log(mut self, log: NetworkAuditLog) -> Self {
        self.network_audit = Some(log);
        self
    }

    /// Has `spaces` prepare the space of every subagent launched from this
    /// terminal and, at any depth, from theirs, before the subagent's
    /// terminal exists. A launch whose space cannot be prepared fails with
    /// the error `spaces` gives.
    #[must_use]
    pub fn with_subagent_spaces(mut self, spaces: impl SubagentSpaces) -> Self {
        self.subagent_spaces = Some(AnySubagentSpaces::new(spaces));
        self
    }

    /// Leases every word this terminal names something with for the model —
    /// a command's task id, a stored output's file name, a subagent's space —
    /// from `ids`, as do the subagent terminals launched from it and the
    /// `subagent` command bound to it. A terminal given none leases from its
    /// own [`AnyIdAllocator::default`].
    #[must_use]
    pub fn with_id_allocator(mut self, ids: AnyIdAllocator) -> Self {
        self.output_store = OutputStore::at(self.output_store.dir().to_path_buf(), ids.clone());
        self.ids = ids;
        self
    }

    /// Creates a new terminal tool with permission handler and executor.
    ///
    /// Creates a working directory under the specified parent directory, which
    /// heel names with four random words (not a leased id). The executor is
    /// used to spawn async tasks for the IPC server.
    ///
    /// # Errors
    /// Returns an error when the working directory or output store cannot be created.
    pub async fn new_in(
        parent_dir: impl AsRef<std::path::Path>,
        permission_handler: P,
        executor: E,
    ) -> Result<Self, TerminalError> {
        let parent_dir = parent_dir.as_ref();

        // Ensure parent directory exists
        async_fs::create_dir_all(parent_dir).await?;

        // heel names the working directory with four random words; it is
        // not a leased model-facing id.
        let working_dir = WorkingDir::random_in(parent_dir).map_err(|e| {
            TerminalError::SandboxSetup(format!("failed to create working dir: {e}"))
        })?;
        // Resolved once, as in `new_exact`.
        let working_dir_path =
            dunce::simplified(&async_fs::canonicalize(working_dir.path()).await?).to_path_buf();

        info!(working_dir = %working_dir_path.display(), "created terminal tool working directory");

        // Create outputs directory inside working dir
        let ids = AnyIdAllocator::default();
        let output_store = OutputStore::new(working_dir_path.join("outputs"), ids.clone()).await?;

        // Start job registry service
        let (job_registry, job_registry_service) = job_registry_channel();
        executor
            .spawn(async move { job_registry_service.serve().await })
            .detach();

        // Create channel for background task completion (unbounded to not block spawned tasks)
        let (completed_tx, completed_rx) = async_channel::unbounded();
        let (alert_tx, alert_rx) = async_channel::unbounded();
        let (started_tx, started_rx) = async_channel::unbounded();
        let running_tasks = Arc::new(AtomicUsize::new(0));
        let (permission_tx, permission_rx) = async_channel::unbounded();

        Ok(Self {
            working_dir: working_dir_path,
            shell_sessions: ShellSessionRegistry::new(ShellRuntimeAvailability::default()),
            permission_handler: Arc::new(permission_handler),
            executor,
            ids,
            output_store,
            job_registry,
            completed_rx,
            completed_tx,
            alert_rx,
            alert_tx,
            started_rx,
            started_tx,
            limits: TerminalLimits::default(),
            running_tasks,
            permission_rx,
            permission_tx,
            grants: TerminalGrants::new(),
            subagent: None,
            carried_dir: Some(CarriedDir::default()),
            env_source: None,
            network_audit: None,
            priority: ProcessPriority::default(),
            #[cfg(all(unix, feature = "jobserver"))]
            jobserver: None,
            heel: SharedHeelBinary::default(),
            outages: Outages::none(),
            subagent_spaces: None,
            registry: Unconfigured,
        })
    }

    /// Creates a new terminal tool with permission handler and executor,
    /// using the provided directory directly as the working directory.
    ///
    /// Unlike `new_in` which creates a random subdirectory, this method
    /// uses the exact path provided. Use this when you want explicit control
    /// over the working directory location.
    ///
    /// # Errors
    /// Returns an error when the working directory or output store cannot be created.
    pub async fn new_exact(
        working_dir: impl AsRef<std::path::Path>,
        permission_handler: P,
        executor: E,
    ) -> Result<Self, TerminalError> {
        // Ensure working directory exists, then resolve it once: heel and the
        // directory report both use this spelling, and a symlink in the given
        // one is not necessarily granted inside the sandbox.
        async_fs::create_dir_all(working_dir.as_ref()).await?;
        let working_dir_path =
            dunce::simplified(&async_fs::canonicalize(working_dir.as_ref()).await?).to_path_buf();

        // Create outputs directory inside working dir
        let ids = AnyIdAllocator::default();
        let output_store = OutputStore::new(working_dir_path.join("outputs"), ids.clone()).await?;

        // Start job registry service
        let (job_registry, job_registry_service) = job_registry_channel();
        executor
            .spawn(async move { job_registry_service.serve().await })
            .detach();

        // Create channel for background task completion (unbounded to not block spawned tasks)
        let (completed_tx, completed_rx) = async_channel::unbounded();
        let (alert_tx, alert_rx) = async_channel::unbounded();
        let (started_tx, started_rx) = async_channel::unbounded();
        let running_tasks = Arc::new(AtomicUsize::new(0));
        let (permission_tx, permission_rx) = async_channel::unbounded();

        Ok(Self {
            working_dir: working_dir_path,
            shell_sessions: ShellSessionRegistry::new(ShellRuntimeAvailability::default()),
            permission_handler: Arc::new(permission_handler),
            executor,
            ids,
            output_store,
            job_registry,
            completed_rx,
            completed_tx,
            alert_rx,
            alert_tx,
            started_rx,
            started_tx,
            limits: TerminalLimits::default(),
            running_tasks,
            permission_rx,
            permission_tx,
            grants: TerminalGrants::new(),
            subagent: None,
            carried_dir: Some(CarriedDir::default()),
            env_source: None,
            network_audit: None,
            priority: ProcessPriority::default(),
            #[cfg(all(unix, feature = "jobserver"))]
            jobserver: None,
            heel: SharedHeelBinary::default(),
            outages: Outages::none(),
            subagent_spaces: None,
            registry: Unconfigured,
        })
    }
}

impl<P, E, State> TerminalTool<P, E, State> {
    /// Moves every part into a terminal with another registry state.
    fn map_state<Next>(self, state: impl FnOnce(State) -> Next) -> TerminalTool<P, E, Next> {
        TerminalTool {
            working_dir: self.working_dir,
            shell_sessions: self.shell_sessions,
            permission_handler: self.permission_handler,
            executor: self.executor,
            ids: self.ids,
            output_store: self.output_store,
            job_registry: self.job_registry,
            completed_rx: self.completed_rx,
            completed_tx: self.completed_tx,
            alert_rx: self.alert_rx,
            alert_tx: self.alert_tx,
            started_rx: self.started_rx,
            started_tx: self.started_tx,
            limits: self.limits,
            running_tasks: self.running_tasks,
            permission_rx: self.permission_rx,
            permission_tx: self.permission_tx,
            grants: self.grants,
            subagent: self.subagent,
            carried_dir: self.carried_dir,
            env_source: self.env_source,
            network_audit: self.network_audit,
            priority: self.priority,
            #[cfg(all(unix, feature = "jobserver"))]
            jobserver: self.jobserver,
            heel: self.heel,
            outages: self.outages,
            subagent_spaces: self.subagent_spaces,
            registry: state(self.registry),
        }
    }
}

impl<P, E> TerminalTool<P, E, Unconfigured>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    /// Attaches a tool registry to this terminal tool, enabling IPC command
    /// dispatch.
    ///
    /// The terminal gets its own launcher for the subagents it starts, and
    /// the registry's terminal-bound commands are built for it.
    #[must_use]
    pub fn with_registry(self, registry: Arc<ToolRegistry>) -> TerminalTool<P, E, Configured> {
        let registry = Arc::new(
            Arc::unwrap_or_clone(registry)
                .with_terminal_controls(self.job_registry(), self.output_store.clone()),
        );
        self.map_state(|Unconfigured| Launching { registry })
            .into_served()
    }
}

#[cfg(test)]
impl<P, E> TerminalTool<P, E, Configured>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    /// A subagent terminal with an empty grant, told to no observer or gate.
    async fn subagent_without_grant(&self) -> Result<Self, SubagentGrantError> {
        self.subagent(&mut LaunchHistory::default(), SubagentGrant::new(), None)
            .await
    }
}

impl<P, E> TerminalTool<P, E, Launching>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    /// Starts this terminal's launcher and binds its registry to it and to
    /// its runner.
    fn into_served(self) -> TerminalTool<P, E, Configured> {
        let (launcher, requests) = async_channel::unbounded();
        // A run starts where it is told and leaves the main agent's carried
        // directory alone.
        let mut runs_on = self.clone().map_state(|_| Unconfigured);
        runs_on.carried_dir = None;
        let mut binding = None;
        let registry = Arc::new_cyclic(|bound| {
            let served = TerminalBinding {
                launcher: TerminalToolFactory { tx: launcher },
                runner: TerminalRunner(Arc::new(BoundRunner {
                    terminal: runs_on,
                    registry: bound.clone(),
                })),
                working_dir: self.working_dir.clone(),
                role: self.registry.registry.role(),
                observer: self.registry.registry.observer().cloned(),
                executor: Arc::new(executor_core::AnyExecutor::new(self.executor.clone())),
                ids: self.ids.clone(),
            };
            let registry = ToolRegistry::clone(&self.registry.registry).bind(&served);
            binding = Some(served);
            registry
        });
        let binding = binding.expect("binding the registry builds the binding");
        let source = self.clone();
        self.executor
            .spawn(async move { serve_launches(requests, source).await })
            .detach();
        self.map_state(|Launching { .. }| Configured { registry, binding })
    }
}

/// Supplies extra environment variables resolved for each spawned execution.
///
/// Implemented by embedders that need values decided at command time —
/// secrets read from a live store, per-call overrides — rather than at tool
/// construction. `Vec<(String, String)>` implements it for static pairs.
pub trait TerminalEnvSource: std::fmt::Debug + Send + Sync {
    /// `(name, value)` pairs injected into the spawned command's environment.
    fn env(&self) -> Vec<(String, String)>;
}

impl TerminalEnvSource for Vec<(String, String)> {
    fn env(&self) -> Vec<(String, String)> {
        self.clone()
    }
}

impl<P, E, State> TerminalTool<P, E, State>
where
    E: Executor + Clone + 'static,
    State: Clone,
{
    /// Adds additional writable paths to the sandbox configuration.
    ///
    /// These paths will be writable in sandboxed and network modes.
    #[must_use]
    pub fn with_writable_paths(self, paths: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
        for path in paths {
            self.grants.add_writable(path.into());
        }
        self
    }

    /// Adds additional readable (but not writable) paths to the sandbox configuration.
    ///
    /// These paths will be readable in all sandbox modes, even in strict
    /// filesystem mode where reads outside the sandbox are normally denied.
    #[must_use]
    pub fn with_readable_paths(self, paths: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
        for path in paths {
            self.grants.add_readable(path.into());
        }
        self
    }

    /// Denies sandboxed local commands reading these absolute paths and
    /// everything beneath them, in addition to heel's credential table
    /// (`~/.ssh`, `~/.config/gh`, keychains and other credential stores).
    /// Every other path on the host is readable; writes stay limited to the
    /// granted paths.
    #[must_use]
    pub fn with_read_denied_paths(
        self,
        paths: impl IntoIterator<Item = impl Into<PathBuf>>,
    ) -> Self {
        for path in paths {
            self.grants.deny_read(path.into());
        }
        self
    }

    /// Injects extra environment variables into every command this tool
    /// spawns in the home environment.
    ///
    /// The source is resolved per execution, so values it returns reflect
    /// the moment each command launches. Injection applies to the local and
    /// container backends; SSH targets are deliberately excluded so
    /// host-side values (for example secrets) never reach remote machines.
    /// Caller-provided names override the session's computed environment.
    #[must_use]
    pub fn with_env_source(mut self, source: impl TerminalEnvSource + 'static) -> Self {
        self.env_source = Some(Arc::new(source));
        self
    }

    /// Injects a fixed set of environment variables into every spawned
    /// command; a convenience for [`Self::with_env_source`] over static pairs.
    #[must_use]
    pub fn with_envs(self, envs: impl IntoIterator<Item = (String, String)>) -> Self {
        self.with_env_source(envs.into_iter().collect::<Vec<_>>())
    }

    /// Lowers the scheduling priority of the commands this tool runs.
    ///
    /// The priority is applied to every sandbox the tool creates — one-shot
    /// commands, persistent shell sessions and background jobs — and is
    /// inherited by everything they spawn. Container executions run the script
    /// through the image's own `heel run`, so the image needs a `heel` binary
    /// when a non-normal priority is configured. SSH executions are not
    /// affected: the remote host runs its own `heel`, managed outside this
    /// configuration.
    #[must_use]
    pub const fn with_process_priority(mut self, priority: ProcessPriority) -> Self {
        self.priority = priority;
        self
    }

    /// Shares a jobserver token pool across every command this tool runs.
    ///
    /// `pool` is the host-provided shared pool (a `fifo:` jobserver). Each
    /// command — foreground or background — gets its own fifo beneath
    /// `fifo_dir` (created if missing, broker-owned, kept out of command
    /// working directories), exported through
    /// `MAKEFLAGS=--jobserver-auth=fifo:PATH`. The broker moves tokens
    /// between the pool and each fifo on demand and returns every token
    /// once the command's whole process tree is gone: the fifo's read end
    /// reports EOF only when its last writer — including surviving
    /// grandchildren — has exited. Commands never see the shared pool
    /// directly, so killed commands cannot leak tokens.
    ///
    /// A container command's fifo is made inside the container, where its
    /// `MAKEFLAGS` names it, and brokered against the same pool by a relay
    /// run with the image's managed `python3`, with the same accounting. SSH
    /// commands fail while a pool is configured rather than running
    /// unbounded.
    ///
    /// # Errors
    /// Returns an error when the fifo directory cannot be created or the
    /// broker's readiness poller cannot be set up.
    #[cfg(all(unix, feature = "jobserver"))]
    pub fn with_jobserver_pool(
        mut self,
        pool: JobPool,
        fifo_dir: impl AsRef<Path>,
    ) -> Result<Self, TerminalError> {
        let (broker, service) = job_broker_channel(pool, fifo_dir)?;
        self.executor
            .spawn(async move { service.serve().await })
            .detach();
        self.jobserver = Some(broker);
        Ok(self)
    }

    /// Sets how long a `terminal` call waits in the foreground before a
    /// still-running command promotes to a background task. Defaults to
    /// [`DEFAULT_FOREGROUND_WAIT`].
    #[must_use]
    pub fn with_foreground_wait(self, wait: Duration) -> Self {
        self.limits.foreground_wait.set_normal(wait);
        self
    }

    /// A handle on the foreground window, shared with every terminal derived
    /// from this one: a longer window put in force through it applies to the
    /// next foreground wait of each of them.
    #[must_use]
    pub fn foreground_wait(&self) -> ForegroundWait {
        self.limits.foreground_wait.clone()
    }

    /// Sets how long the agent has to act on a final memory warning before
    /// the job it names is killed. Defaults to [`DEFAULT_RESPONSE_WINDOW`].
    #[must_use]
    pub fn with_response_window(self, window: Duration) -> Self {
        self.limits.response_window.set(window);
        self
    }

    /// A handle on the response window, shared with every terminal derived
    /// from this one: a window set through it applies to the next final
    /// warning of each of them.
    #[must_use]
    pub fn response_window(&self) -> ResponseWindow {
        self.limits.response_window.clone()
    }

    /// Reads job footprints and the machine's physical memory through
    /// `reader` instead of the platform's own.
    #[must_use]
    pub fn with_footprint_reader(mut self, reader: impl FootprintReader) -> Self {
        self.limits.footprints = AnyFootprintReader::new(reader);
        self
    }

    /// Shares the memory this terminal's jobs hold with the machine's other
    /// agents through `registry`, so a final warning can name the agent that
    /// contributes the most when all agents together exceed physical memory.
    #[must_use]
    pub fn with_footprint_registry(mut self, registry: impl FootprintRegistry) -> Self {
        self.limits.footprint_registry = Some(AnyFootprintRegistry::new(registry));
        self
    }

    /// The memory the terminal's jobs hold, for a guard that warns about and
    /// kills a runaway job.
    #[must_use]
    ///
    /// The machine the embedder runs on is always judged. When the terminal
    /// runs in a container, the container's own memory limit is judged too,
    /// read inside the container. Jobs of a remote execution environment are
    /// never judged.
    pub fn job_memory(&self) -> JobMemory {
        let memory = JobMemory::new(
            self.job_registry(),
            self.limits.footprints.clone(),
            self.limits.footprint_registry.clone(),
            self.limits.response_window.clone(),
        );
        match self.container_probe() {
            Some(probe) => {
                memory.with_container(AnyContainerMemory::new(ProbedContainerMemory::new(probe)))
            }
            None => memory,
        }
    }

    /// A reader of the container the agent works in, when the terminal's
    /// home environment is a container; `None` when it is the local
    /// machine. A remote execution environment is never a home environment.
    #[must_use]
    pub fn container_probe(&self) -> Option<crate::ContainerProbe> {
        if self.shell_sessions.resolve_local_backend() != Ok(ShellBackend::Container) {
            return None;
        }
        self.shell_sessions
            .container_runtime()
            .map(ContainerShellRuntime::probe)
    }

    /// Sets the largest `timeout` a command accepts.
    /// Defaults to [`DEFAULT_TIMEOUT_CAP`].
    #[must_use]
    pub const fn with_timeout_cap(mut self, cap: Duration) -> Self {
        self.limits.timeout_cap = cap;
        self
    }

    /// Sets the most bytes a subagent's sandbox may send the host while the
    /// commits it made are imported into the main repository; a pack or answer
    /// that exceeds it fails the import. `0` leaves the bytes unbounded.
    /// Defaults to [`DEFAULT_SUBAGENT_IMPORT_LIMIT`]. Each piece of an import's
    /// sandboxed work is bounded in time by the foreground limit.
    ///
    /// The setting can be changed while the terminal and the subagents it
    /// launches run, through [`Self::subagent_import_budget`].
    #[must_use]
    pub fn with_subagent_import_limit(self, bytes: u64) -> Self {
        self.limits.subagent_import.set(bytes);
        self
    }

    /// A handle on the setting [`Self::with_subagent_import_limit`] sets,
    /// shared with every subagent this terminal launches: a change through it
    /// applies to the next import of each of them.
    #[must_use]
    pub fn subagent_import_budget(&self) -> ImportBudget {
        self.limits.subagent_import.clone()
    }

    /// Sets how long a background job may run before it produces one system
    /// alert naming it. Defaults to [`DEFAULT_LONG_JOB_ALERT_AFTER`].
    #[must_use]
    pub const fn with_long_job_alert_after(mut self, after: Duration) -> Self {
        self.limits.long_job_alert = after;
        self
    }

    /// Records the sleep and offline intervals `connectivity` reports during
    /// each command, and states them in the command's result and, for a
    /// background job, its completion alert.
    ///
    /// Terminals launched for subagents share the record. Only commands that
    /// start after this call are recorded.
    #[cfg(feature = "connectivity")]
    #[must_use]
    pub fn with_connectivity(mut self, connectivity: &aither_connectivity::Connectivity) -> Self {
        self.outages = Outages::watching(connectivity, &self.executor);
        self
    }

    /// Initializes tools before agent construction or command execution.
    ///
    /// # Errors
    /// Rejects preparation failures and writable grants that expose managed tools.
    pub async fn initialize_tools(
        mut self,
        distribution: &ToolDistribution,
        cache_root: &Path,
    ) -> Result<Self, ToolRuntimeError>
    where
        P: PermissionHandler,
        State: Send,
    {
        self.shell_sessions = self
            .shell_sessions
            .initialize_tools(distribution, cache_root)
            .await?;
        if let Some(tools) = self.local_home_tools()? {
            tools.ensure_readonly(self.writable_grants().iter()).await?;
            let heel = self
                .heel
                .get()
                .await
                .map_err(|error| ToolRuntimeError::SshBootstrap(error.to_string()))?;
            tools
                .verify_local_versions(self.executor.clone(), heel)
                .await?;
        }
        Ok(self)
    }

    /// Adopts a registry that [`Self::initialize_tools`] already prepared for
    /// another terminal.
    ///
    /// Only the checks that depend on this terminal run again: its working
    /// directory and writable paths must not expose the managed tool
    /// directory. Artifact downloads, integrity hashing, version probes and SSH
    /// bootstrap — with its connection consent — are not repeated.
    ///
    /// # Errors
    /// Rejects a registry that is not prepared, one whose home backend,
    /// container or SSH server set changed after preparation, and writable
    /// grants that expose the managed tools.
    pub async fn adopt_prepared_tools(
        mut self,
        sessions: ShellSessionRegistry,
    ) -> Result<Self, ToolRuntimeError>
    where
        P: PermissionHandler,
        State: Send,
    {
        sessions.prepared_catalog()?;
        self.shell_sessions = sessions;
        if let Some(tools) = self.local_home_tools()? {
            tools.ensure_readonly(self.writable_grants().iter()).await?;
        }
        Ok(self)
    }

    /// Prepared tools of the local home backend, when this terminal runs on it.
    fn local_home_tools(&self) -> Result<Option<&PreparedTools<PathBuf>>, ToolRuntimeError> {
        match self.shell_sessions.resolve_local_backend() {
            Ok(ShellBackend::Local) => self.shell_sessions.local_tools().map(Some),
            _ => Ok(None),
        }
    }

    /// The paths this terminal grants write access to, which must not expose
    /// the managed tools.
    fn writable_grants(&self) -> Vec<PathBuf> {
        let grants = self.grants.snapshot();
        std::iter::once(self.working_dir.clone())
            .chain(grants.writable.iter().cloned())
            .collect()
    }

    /// Initialized session configuration shared with child terminals.
    #[must_use]
    pub const fn shell_sessions(&self) -> &ShellSessionRegistry {
        &self.shell_sessions
    }

    /// Operational context from successfully initialized environments.
    ///
    /// # Errors
    /// Fails when no tools are prepared or a backend configuration has changed.
    pub fn prepared_tools_context(&self) -> Result<String, ToolRuntimeError> {
        self.shell_sessions.prepared_catalog()?.render()
    }

    /// Returns the working directory path.
    pub const fn working_dir(&self) -> &PathBuf {
        &self.working_dir
    }

    /// Returns the outputs directory path.
    pub fn outputs_dir(&self) -> PathBuf {
        self.working_dir.join("outputs")
    }

    /// Returns the output store.
    pub const fn output_store(&self) -> &OutputStore {
        &self.output_store
    }

    /// The allocator this terminal leases its model-facing ids from.
    pub const fn id_allocator(&self) -> &AnyIdAllocator {
        &self.ids
    }

    /// Returns the job registry handle.
    pub fn job_registry(&self) -> JobRegistry {
        self.job_registry.clone()
    }

    /// Returns a receiver for completed background tasks.
    /// Sender on the job-alert channel a watch task reports through;
    /// `monitor` clones it for every pump it spawns.
    pub(crate) fn job_alert_sender(&self) -> Sender<JobAlert> {
        self.alert_tx.clone()
    }

    /// The executor backing this terminal, for spawning watch tasks.
    pub const fn executor(&self) -> &E {
        &self.executor
    }

    /// Paths mounted readable for commands, besides the working directory.
    /// The shared runtime grant handle: adding a grant through it affects
    /// every command launched afterwards, on this terminal and its clones.
    pub fn grants(&self) -> TerminalGrants {
        self.grants.clone()
    }

    ///
    /// The returned `BackgroundTaskReceiver` can be used independently of the `TerminalTool`
    /// to poll for completed background tasks. This is useful for integrating with
    /// the Agent's main loop.
    pub fn background_receiver(&self) -> BackgroundTaskReceiver {
        BackgroundTaskReceiver {
            rx: self.completed_rx.clone(),
            alert_rx: self.alert_rx.clone(),
            started_rx: self.started_rx.clone(),
            running_tasks: self.running_tasks.clone(),
        }
    }

    /// Returns a receiver for permission lifecycle events.
    pub fn permission_receiver(&self) -> PermissionEventReceiver {
        PermissionEventReceiver {
            rx: self.permission_rx.clone(),
        }
    }

    /// Takes all completed background tasks without blocking.
    ///
    /// Returns an empty vector if no tasks have completed.
    /// The agent should call this after each turn to check for completed background tasks.
    pub fn take_completed(&self) -> Vec<CompletedTask> {
        let mut completed = Vec::new();
        while let Ok(task) = self.completed_rx.try_recv() {
            completed.push(task);
        }
        completed
    }

    /// Checks if there are any pending background tasks.
    pub fn has_pending_tasks(&self) -> bool {
        !self.completed_rx.is_empty() || self.running_tasks.load(Ordering::Acquire) > 0
    }
}

/// The directory, inside a launching terminal's working directory, that holds
/// the spaces of the subagents it launches.
const SUBAGENT_SPACES_DIR: &str = "subagent-spaces";

impl<P, E, State> TerminalTool<P, E, State>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
    State: RegistryState,
{
    /// Creates the terminal tool of a subagent this terminal launches, as
    /// [`Self::resolve_launch`] and [`Self::launch_resolved`] do one after
    /// the other.
    #[cfg(test)]
    pub(crate) async fn subagent(
        &self,
        history: &mut LaunchHistory,
        grant: SubagentGrant,
        caller: Option<&Path>,
    ) -> Result<TerminalTool<P, E, Configured>, SubagentGrantError> {
        let resolved = self.resolve_launch(history, grant).await?;
        self.launch_resolved(resolved, None, None, caller).await
    }

    /// Resolves the grant of a subagent this terminal launches: it never
    /// exceeds what this terminal can write or commit. `history` records what
    /// the main agent's terminal handed out.
    ///
    /// # Errors
    /// Returns an error when `grant` names a path this terminal cannot write
    /// or a commit it cannot grant, when the grant cannot be resolved, or when
    /// a container session has no workspace mount.
    async fn resolve_launch(
        &self,
        history: &mut LaunchHistory,
        grant: SubagentGrant,
    ) -> Result<ResolvedLaunch, SubagentGrantError> {
        // Grants are compared by real path, so every path of the subagent's
        // view is canonical.
        let working_dir = canonical_path(&self.working_dir).await?;
        let mut authority = vec![working_dir.clone()];
        for path in &self.grants.snapshot().writable {
            authority.push(canonical_path(path).await?);
        }
        let spaces_root = working_dir.join(SUBAGENT_SPACES_DIR);
        let mount = self.container_mount().await?;
        let granted = grant
            .resolve(
                Launcher {
                    writable: &authority,
                    committing: self
                        .subagent
                        .as_ref()
                        .map(|subagent| subagent.committing.as_slice()),
                    spaces_root: &spaces_root,
                    spelling: mount
                        .as_ref()
                        .map_or_else(Spelling::host, Spelling::through),
                },
                history,
            )
            .await?;
        self.registry
            .registry()
            .record_committed(&granted.committing);
        Ok(ResolvedLaunch {
            authority,
            spaces_root,
            mount,
            granted,
        })
    }

    /// Creates the terminal tool of a subagent this terminal launches with
    /// the grant `resolved` holds.
    ///
    /// The subagent shares the permission handler, output store and prepared
    /// tools, serves the subagent registry (so nothing reserved for the main
    /// agent is reachable, however deep subagents nest) with its
    /// terminal-bound commands built for it, and has its own launcher and
    /// background task tracking. It works in a space of its own inside this
    /// terminal's working directory, which this terminal's
    /// [`SubagentSpaces`] fill first; everything this terminal can write is
    /// read-only to it, apart from what the grant hands over. The commands
    /// it calls are told to `observer`, and every shell command it runs is
    /// put to `gate`.
    ///
    /// # Errors
    /// Returns an error when a container session cannot express the
    /// subagent's paths, or when the subagent's space cannot be created or
    /// prepared.
    #[allow(clippy::too_many_lines)]
    async fn launch_resolved(
        &self,
        ResolvedLaunch {
            authority,
            spaces_root,
            mount,
            granted,
        }: ResolvedLaunch,
        observer: Option<AnyCommandObserver>,
        gate: Option<AnyCommandGate>,
        caller: Option<&Path>,
    ) -> Result<TerminalTool<P, E, Configured>, SubagentGrantError> {
        async_fs::create_dir_all(&spaces_root)
            .await
            .map_err(|source| SubagentGrantError::Space {
                path: spaces_root.clone(),
                source,
            })?;
        // The space is named by a leased word the subagent's terminal holds
        // for as long as it lives. A word a space of an earlier terminal
        // already has stays leased until a free one is found, so the
        // allocator hands out another.
        let mut taken = Vec::new();
        let (space_name, space, container) = loop {
            let name = self.ids.lease()?;
            let space = spaces_root.join(name.as_str());
            let container = mount
                .as_ref()
                .map(|mount| container_confinement_for(mount, &space, &granted.writable))
                .transpose()?;
            match async_fs::create_dir(&space).await {
                Ok(()) => break (name, space, container),
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
                    taken.push(name);
                }
                Err(source) => {
                    return Err(SubagentGrantError::Space {
                        path: space,
                        source,
                    });
                }
            }
        };
        drop(taken);
        let prepared = match &self.subagent_spaces {
            Some(spaces) => {
                let launcher = &authority[0];
                let run = RunSpace {
                    space: &space,
                    launcher,
                    caller: caller.unwrap_or(launcher),
                };
                match prepare_space(spaces, run).await {
                    Ok(prepared) => Some(prepared),
                    Err(error) => {
                        // No run ever worked in the space, so it is no one's
                        // to keep.
                        if let Err(removal) = async_fs::remove_dir_all(&space).await {
                            warn!(
                                space = %space.display(),
                                %removal,
                                "cannot remove a subagent space whose preparation failed"
                            );
                        }
                        return Err(error);
                    }
                }
            }
            None => None,
        };

        let (completed_tx, completed_rx) = async_channel::unbounded();
        let (alert_tx, alert_rx) = async_channel::unbounded();
        let (started_tx, started_rx) = async_channel::unbounded();
        let running_tasks = Arc::new(AtomicUsize::new(0));
        let (permission_tx, permission_rx) = async_channel::unbounded();
        let (job_registry, job_registry_service) = job_registry_channel();
        self.executor
            .spawn(async move { job_registry_service.serve().await })
            .detach();
        let grants = TerminalGrants::derived(&self.grants, authority, granted.writable.clone());
        let readable_paths = grants.snapshot().readable.clone();
        let git = match (&container, mount) {
            (Some(confinement), Some(mount)) => {
                SubagentGit::new(Arc::new(subagent_git::ContainerGit {
                    executor: self.executor.clone(),
                    shell_sessions: self.shell_sessions.clone(),
                    confinement: confinement.clone(),
                    mount,
                    priority: self.priority,
                }))
            }
            _ => SubagentGit::new(Arc::new(subagent_git::LocalGit {
                executor: self.executor.clone(),
                working_dir: space.clone(),
                writable: granted.writable,
                readable: readable_paths,
                committing: granted.committing.clone(),
                priority: self.priority,
                heel: self.heel.clone(),
            })),
        };
        let registry = Arc::new(
            self.registry
                .registry()
                .for_subagent(observer, gate)
                .with_terminal_controls(job_registry.clone(), self.output_store.clone()),
        );
        let launching = TerminalTool {
            working_dir: space,
            shell_sessions: self.shell_sessions.clone(),
            permission_handler: self
                .permission_handler
                .for_subagent()
                .map_or_else(|| self.permission_handler.clone(), Arc::new),
            executor: self.executor.clone(),
            ids: self.ids.clone(),
            output_store: self.output_store.clone(),
            job_registry,
            completed_rx,
            completed_tx,
            alert_rx,
            alert_tx,
            started_rx,
            started_tx,
            limits: self.limits.clone(),
            running_tasks,
            permission_rx,
            permission_tx,
            grants,
            subagent: Some(SubagentAuthority {
                _space_name: space_name,
                committing: granted.committing,
                git,
                container,
                prepared,
            }),
            carried_dir: None,
            env_source: self.env_source.clone(),
            network_audit: self.network_audit.clone(),
            priority: self.priority,
            #[cfg(all(unix, feature = "jobserver"))]
            jobserver: self.jobserver.clone(),
            heel: self.heel.clone(),
            outages: self.outages.clone(),
            subagent_spaces: self.subagent_spaces.clone(),
            registry: Launching { registry },
        };
        Ok(launching.into_served())
    }

    /// What this terminal's launcher prepared in its space; `None` for the
    /// main agent's terminal and when the launcher has no
    /// [`SubagentSpaces`].
    fn prepared_space(&self) -> Option<PreparedSpace> {
        self.subagent
            .as_ref()
            .and_then(|subagent| subagent.prepared.clone())
    }

    /// The workspace mount of this terminal's home container, with its host
    /// side canonical, spelling every path of a subagent's view inside the
    /// container. `None` outside a container.
    async fn container_mount(&self) -> Result<Option<MountRoot>, SubagentGrantError> {
        if self.shell_sessions.resolve_local_backend() != Ok(ShellBackend::Container) {
            return Ok(None);
        }
        let mount = self
            .shell_sessions
            .container_runtime()
            .and_then(ContainerShellRuntime::workspace_mount)
            .ok_or(SubagentGrantError::NoContainerMount)?;
        // The mount is compared by real path, like everything it maps.
        Ok(Some(MountRoot::new(
            canonical_path(&mount.host_root).await?,
            mount.container_root.clone(),
        )))
    }
}

/// Has `spaces` prepare `run`'s space and confines what they name to it.
async fn prepare_space(
    spaces: &AnySubagentSpaces,
    run: RunSpace<'_>,
) -> Result<PreparedSpace, SubagentGrantError> {
    spaces
        .prepare(run)
        .await
        .map_err(|source| SubagentGrantError::Preparation {
            space: run.space.to_path_buf(),
            source,
        })?
        .confine(run.space)
        .await
}

/// The sandbox a subagent's commands run in inside a container: its space and
/// granted paths, spelled through the container's workspace mount.
fn container_confinement_for(
    mount: &MountRoot,
    space: &Path,
    writable: &[PathBuf],
) -> Result<ContainerConfinement, SubagentGrantError> {
    let map = |path: &Path| {
        mount
            .container_path(path)
            .map_err(|source| SubagentGrantError::OutsideContainerMount {
                path: path.to_path_buf(),
                source,
            })
    };
    Ok(ContainerConfinement {
        working_dir: map(space)?,
        writable: writable
            .iter()
            .map(|path| map(path))
            .collect::<Result<_, _>>()?,
    })
}

impl<P, E> TerminalTool<P, E, Configured>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    /// Returns a receiver for the `terminal` calls in which a command
    /// registered with
    /// [`ToolRegistryBuilder::kept_through_compaction`](crate::ToolRegistryBuilder::kept_through_compaction)
    /// succeeded.
    #[must_use]
    pub fn kept_receiver(&self) -> crate::command::KeptExchangeReceiver {
        self.registry().kept_receiver()
    }

    /// What this terminal hands the commands bound to it: its working
    /// directory and the launcher for the subagents it starts.
    #[must_use]
    pub const fn binding(&self) -> &TerminalBinding {
        &self.registry.binding
    }

    /// Lists the commits of the subagent this terminal serves, when it holds a
    /// commit grant.
    fn commit_ledger(&self) -> Option<CommitLedger> {
        self.subagent.as_ref().and_then(|subagent| {
            CommitLedger::new(
                &subagent.committing,
                subagent.git.clone(),
                ImportLimits {
                    bytes: self.limits.subagent_import.clone(),
                    time: self.limits.foreground_wait.get(),
                },
            )
        })
    }

    /// Converts this `TerminalTool` into a type-erased `DynTerminalTool`.
    ///
    /// This is useful for creating child terminal tools for subagents where
    /// the concrete type cannot be known at compile time.
    ///
    /// # Panics
    /// Panics when execution environments have not completed tool initialization.
    pub fn to_dyn(self) -> crate::command::DynTerminalTool {
        use crate::command::DynTerminalTool;

        let background_receiver = self.background_receiver();
        let permission_receiver = self.permission_receiver();
        let kept_receiver = self.kept_receiver();
        let job_registry = self.job_registry();
        let working_dir = self.working_dir().clone();
        let command_names = self.registry().available_tool_names();
        let commit_ledger = self.commit_ledger();
        let prepared_space = self.prepared_space();
        let role = self.registry().role();
        let notices = self.registry().notices().clone();
        let prepared_tools = self
            .shell_sessions
            .prepared_catalog()
            .expect("terminal tools must be initialized before exposing child capabilities")
            .clone();
        let entries = vec![erase_terminal_tool(self)];

        DynTerminalTool {
            entries,
            background_receiver,
            permission_receiver,
            kept_receiver,
            job_registry,
            working_dir,
            command_names,
            prepared_tools,
            commit_ledger,
            prepared_space,
            role,
            notices,
        }
    }
}

/// The execution path every terminal state that serves a registry shares:
/// a `terminal` call and a [`TerminalRunner`] run go through it alike.
impl<P, E, S> TerminalTool<P, E, S>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
    S: RegistryState,
{
    fn registry(&self) -> &Arc<ToolRegistry> {
        self.registry.registry()
    }

    fn resolve_execution_target(
        &self,
        mode: TerminalExecutionMode,
        ssh_server_id: Option<&str>,
    ) -> Result<ExecutionTarget, TerminalError> {
        match mode {
            TerminalExecutionMode::Default => self.resolve_default_target(),
            TerminalExecutionMode::Sandboxed => self.resolve_home_target(TerminalMode::Sandboxed),
            TerminalExecutionMode::Unsafe => self.resolve_home_target(TerminalMode::Unsafe),
            TerminalExecutionMode::Ssh => self.resolve_ssh_target(ssh_server_id),
        }
    }

    fn resolve_default_target(&self) -> Result<ExecutionTarget, TerminalError> {
        if self.shell_sessions.resolve_local_backend().is_ok() {
            self.resolve_home_target(TerminalMode::Sandboxed)
        } else {
            self.resolve_ssh_target(None)
        }
    }

    fn resolve_home_target(&self, mode: TerminalMode) -> Result<ExecutionTarget, TerminalError> {
        let backend = self
            .shell_sessions
            .resolve_local_backend()
            .map_err(TerminalError::InvalidTarget)?;
        if mode == TerminalMode::Unsafe && backend != ShellBackend::Local {
            return Err(TerminalError::InvalidTarget(
                "unsafe mode is only available in heel local runtime".into(),
            ));
        }
        let backend = match backend {
            ShellBackend::Local => {
                ExecutionBackend::Local(self.shell_sessions.local_tools()?.clone())
            }
            ShellBackend::Container => ExecutionBackend::Container {
                runtime: self
                    .shell_sessions
                    .container_runtime()
                    .cloned()
                    .ok_or(ToolRuntimeError::MissingContainerRuntime)?,
                tools: self.shell_sessions.container_tools()?.clone(),
                confinement: self
                    .subagent
                    .as_ref()
                    .and_then(|subagent| subagent.container.clone()),
            },
            ShellBackend::Ssh => unreachable!("the home backend is never SSH"),
        };
        Ok(ExecutionTarget { mode, backend })
    }

    fn resolve_ssh_target(
        &self,
        ssh_server_id: Option<&str>,
    ) -> Result<ExecutionTarget, TerminalError> {
        self.shell_sessions
            .ensure_ssh_available()
            .map_err(TerminalError::InvalidTarget)?;
        let server = ssh_server_id
            .map_or_else(
                || self.shell_sessions.default_ssh_server(),
                |id| self.shell_sessions.resolve_ssh_server(id),
            )
            .map_err(TerminalError::InvalidTarget)?;
        let (runtime, tools) = self.shell_sessions.ssh_tools(&server)?;
        Ok(ExecutionTarget {
            mode: TerminalMode::Sandboxed,
            backend: ExecutionBackend::Ssh {
                target: server.target,
                runtime: runtime.clone(),
                tools: tools.clone(),
            },
        })
    }

    async fn ensure_permission_allowed(
        &self,
        mode: TerminalMode,
        script: &str,
        language: ScriptLanguage,
    ) -> Result<(), TerminalError> {
        if mode.requires_approval() {
            match self
                .permission_handler
                .review(&PermissionRequest::Command {
                    mode,
                    script,
                    language,
                })
                .await
            {
                Review::Approved => return Ok(()),
                Review::Denied(reason) => {
                    return Err(TerminalError::from(PermissionError::Denied(reason)));
                }
                Review::Passed => {}
            }
        }
        let permission_waits = self
            .permission_handler
            .will_wait_for_approval(mode, script, language)
            .await;
        if permission_waits {
            self.emit_permission_event(mode, script, language, PermissionEventStage::Waiting)
                .await;
        }
        let permission_result =
            ensure_mode_allowed(self.permission_handler.as_ref(), mode, script, language).await;
        if permission_waits {
            self.emit_permission_event(mode, script, language, PermissionEventStage::Resolved)
                .await;
        }
        permission_result
    }

    async fn emit_permission_event(
        &self,
        mode: TerminalMode,
        script: &str,
        language: ScriptLanguage,
        stage: PermissionEventStage,
    ) {
        let _ = self
            .permission_tx
            .send(PermissionEvent {
                mode,
                script: script.to_string(),
                language,
                stage,
            })
            .await;
    }

    fn spawn_terminal_execution(&self, request: TerminalSpawnRequest) -> SpawnedTerminal {
        let TerminalSpawnRequest {
            target,
            task_id,
            execution_id,
            script,
            language,
            expect,
            resolution,
            max_lines,
            raw,
            background,
            timeout,
            carry,
            call,
        } = request;
        let ExecutionTarget { mode, backend } = target;
        // Every IPC channel this execution opens, local router or container
        // bridge, is served from this one registry, so each command its script
        // runs, a detached job's included, is told the id of this call, and
        // only the commands that answer in its mode are there.
        let registry = self
            .registry()
            .in_mode(mode)
            .for_job(crate::command::JobOutput::new(
                self.job_registry.clone(),
                task_id.clone(),
            ));
        let registry = Arc::new(match call {
            Some(call) => registry.for_call(call),
            None => registry,
        });
        let (result_tx, result_rx) = async_channel::bounded(1);
        let (taken_tx, taken_rx) = async_channel::bounded(1);
        let (startup_tx, startup_rx) = async_channel::bounded(1);
        // Every job gets a real stdin pipe: a foreground command that blocks
        // on it promotes to a background task the model can feed through
        // `terminal_input`, and a blocked episode raises an alert.
        let stdin_alerts = Some(StdinAlerts {
            tx: self.alert_tx.clone(),
            task_id: task_id.to_string(),
            script: script.clone(),
        });
        let timeout_watch = self.spawn_kill_watchdog(&task_id, timeout);
        self.spawn_long_job_alert(&task_id);

        let lifetime = if background {
            JobLifetime::Background
        } else {
            JobLifetime::Foreground {
                alerts: self.alert_tx.clone(),
            }
        };
        let background_startup = BackgroundStartup::new(startup_tx);
        let running_tasks = self.running_tasks.clone();
        let completed_tx = self.completed_tx.clone();
        let outages = self.outages.clone();
        outages.begin(&task_id);

        running_tasks.fetch_add(1, Ordering::AcqRel);
        self.executor
            .spawn(execute_terminal_task(SpawnedTerminalTask {
                working_dir: self.working_dir.clone(),
                writable_paths: self.grants.snapshot().writable.clone(),
                readable_paths: self.grants.snapshot().readable.clone(),
                read_denied_paths: self.grants.snapshot().read_denied.clone(),
                git_dir: self.grants.snapshot().git_dir,
                env_source: self.env_source.clone(),
                executor: self.executor.clone(),
                registry,
                permission_handler: self.permission_handler.clone(),
                job_registry: self.job_registry.clone(),
                task_id,
                execution_id,
                background,
                timeout_watch: timeout_watch.clone(),
                carry,
                carried_dir: self.carried_dir.clone(),
                alert_tx: self.alert_tx.clone(),
                script,
                language,
                mode,
                backend,
                stdin_alerts,
                lifetime,
                background_startup,
                expect,
                resolution,
                outputs: self.output_store.clone(),
                max_lines,
                raw,
                result_tx,
                taken: taken_rx,
                completed_tx,
                running_tasks,
                network_audit: self.network_audit.clone(),
                priority: self.priority,
                #[cfg(all(unix, feature = "jobserver"))]
                jobserver: self.jobserver.clone(),
                heel: self.heel.clone(),
                outages,
            }))
            .detach();

        SpawnedTerminal {
            result: result_rx,
            startup: startup_rx,
            timeout_watch,
            taken: taken_tx,
        }
    }
}

impl<P: PermissionHandler + 'static, E: Executor + Clone + 'static> Tool
    for TerminalTool<P, E, Configured>
{
    fn name(&self) -> Cow<'static, str> {
        "terminal".into()
    }

    type Arguments = TerminalArgs;
    type Res = ToolResult;

    async fn call(
        &self,
        arguments: Self::Arguments,
        cx: ToolContext,
    ) -> aither_core::Result<Self::Res> {
        let cap = self.limits.timeout_cap;
        let timeout = Duration::from_secs(arguments.timeout);
        if arguments.timeout == 0 || timeout > cap {
            return Err(anyhow::anyhow!(
                "terminal timeout must be between 1 and {} seconds",
                cap.as_secs()
            ));
        }
        let prepared = self.prepare_execution(&arguments, cx.identity()).await?;
        // A detached job cannot report a directory carry: its final
        // directory is unknowable when the call returns.
        let carry = if arguments.background {
            None
        } else {
            self.cwd_carry(&prepared, &arguments.script, arguments.language)
                .await
        };
        let spawned = self.spawn_terminal_execution(TerminalSpawnRequest {
            target: prepared.target,
            task_id: prepared.task_id.clone(),
            execution_id: prepared.execution_id,
            script: arguments.script,
            language: arguments.language,
            expect: arguments.expect,
            resolution: arguments.resolution,
            max_lines: prepared.max_lines,
            raw: arguments.raw,
            background: arguments.background,
            timeout,
            carry: carry.clone(),
            call: cx.identity().cloned(),
        });
        // Registration precedes `report_ready` on every backend, so once
        // startup returns the job is killable through the registry and the
        // foreground clock only measures the command's own runtime.
        wait_for_background_startup(&spawned.startup).await?;
        if arguments.background {
            return background_terminal_result(
                &self.job_registry,
                &prepared.outputs,
                &prepared.task_id,
                prepared.max_lines,
                &self.started_tx,
            )
            .await;
        }
        let outcome =
            wait_for_foreground_result(&spawned.result, self.limits.foreground_wait.get()).await;
        // A result that raced in at the window's edge counts as a
        // foreground finish.
        let outcome = outcome.or_else(|| spawned.result.try_recv().ok());
        match outcome {
            Some(Ok(result)) => {
                let killed = self
                    .job_registry
                    .get_by_task_id(&prepared.task_id)
                    .await
                    .is_some_and(|job| matches!(job.status, JobStatus::Killed { .. }));
                let command = if killed {
                    CommandResult {
                        stdout: result.stdout,
                        stderr: result.stderr,
                        interruptions: result.interruptions,
                        outcome: CommandOutcome::Killed {
                            task_id: prepared.task_id.to_string(),
                            notice: self.kill_notice(spawned.timeout_watch.kill().as_ref()),
                        },
                    }
                } else {
                    CommandResult::from(result)
                };
                spawned.took_result().await;
                command.into_tool_result()
            }
            Some(Err(err)) => {
                spawned.took_result().await;
                Err(anyhow::anyhow!(err))
            }
            // The command outlived its foreground window: promote it to a
            // background task.
            None => {
                background_terminal_result(
                    &self.job_registry,
                    &prepared.outputs,
                    &prepared.task_id,
                    prepared.max_lines,
                    &self.started_tx,
                )
                .await
            }
        }
    }
}

impl<P: PermissionHandler + 'static, E: Executor + Clone + 'static> TerminalTool<P, E, Configured> {
    /// The directory report of a foreground command on the main agent's
    /// terminal; `None` for a subagent, for an ssh command and for a container
    /// whose workspace mount is not declared.
    async fn cwd_carry(
        &self,
        prepared: &ExecutionPreparation,
        script: &str,
        language: ScriptLanguage,
    ) -> Option<CwdCarry> {
        let carried = self.carried_dir.as_ref()?;
        let mount = match &prepared.target.backend {
            ExecutionBackend::Local(_) if !cfg!(windows) => None,
            ExecutionBackend::Container { runtime, .. } => Some(runtime.workspace_mount()?.clone()),
            _ => return None,
        };
        let start = carried.get();
        // A directory removed since it was recorded no longer carries.
        let start = match start {
            Some(dir)
                if async_fs::metadata(&dir)
                    .await
                    .is_ok_and(|meta| meta.is_dir()) =>
            {
                Some(dir)
            }
            Some(_) => {
                carried.set(None);
                let dir = if mount.is_some() {
                    PathBuf::from(CONTAINER_EXEC_WORKING_DIR)
                } else {
                    self.own_dir().await
                };
                let _ = self
                    .alert_tx
                    .send(JobAlert::DirectoryReset(DirectoryReset {
                        dir,
                        reason: DirectoryResetReason::Removed,
                    }))
                    .await;
                None
            }
            None => None,
        };
        let report = self.working_dir.join(format!(".cwd-{}", prepared.task_id));
        let container = match mount {
            None => None,
            Some(mount) => {
                // The report must lie in the mounted workspace for the host
                // to read it back.
                let container_report = mount.container_path(&report).ok()?;
                let container_start = start
                    .as_ref()
                    .and_then(|start| mount.container_path(start).ok())
                    .unwrap_or_else(|| {
                        ContainerPath::new(CONTAINER_EXEC_WORKING_DIR)
                            .expect("the exec directory is absolute")
                    });
                Some(ContainerCarry {
                    mount,
                    report: Some(container_report),
                    start: container_start,
                })
            }
        };
        // A Python script runs from a shell wrapper, so its report is written
        // like a shell script's.
        let shell =
            container.is_some() || language == ScriptLanguage::Python || runs_in_shell(script);
        Some(CwdCarry {
            start,
            report: Some(report),
            container,
            shell,
        })
    }

    /// Makes the directory a finished foreground command ended in the start
    /// of the next one, with the missing-report alert a task end does not
    /// raise for a killed job. In production the task consumes the report
    /// (see [`execute_script_standalone`]); tests drive the same logic here.
    #[cfg(test)]
    async fn record_carried_dir(&self, carry: &CwdCarry, succeeded: bool) {
        let ctx = CarryContext {
            carried_dir: self.carried_dir.as_ref(),
            alert_tx: &self.alert_tx,
            working_dir: &self.working_dir,
            grants: self.grants.snapshot(),
        };
        let Some(reported) = take_cwd_report(carry).await else {
            if carry.shell {
                alert_directory_reset(carry, DirectoryResetReason::Unreported, &ctx).await;
            }
            return;
        };
        apply_cwd_report(carry, reported, succeeded, &ctx).await;
    }

    /// The terminal's own directory as a command sees it.
    async fn own_dir(&self) -> PathBuf {
        canonical_path(&self.working_dir)
            .await
            .unwrap_or_else(|_| self.working_dir.clone())
    }
}

/// Shared state needed to settle a finished command's directory report,
/// whether the command finished inside its foreground call or promoted
/// and ended as a background task.
struct CarryContext<'a> {
    carried_dir: Option<&'a CarriedDir>,
    alert_tx: &'a Sender<JobAlert>,
    working_dir: &'a Path,
    grants: std::sync::Arc<GrantSet>,
}

/// Reads and removes a command's directory report, returning the directory
/// the shell ended in when it reported one. The file is consumed either
/// way so a promoted command never leaves it behind.
async fn take_cwd_report(carry: &CwdCarry) -> Option<String> {
    let report = carry.report.as_ref()?;
    let reported = async_fs::read_to_string(report).await;
    let _ = async_fs::remove_file(report).await;
    // A direct command writes no report; a shell that ended through
    // `exit` or a signal writes none either.
    reported
        .ok()
        .map(|reported| reported.trim_end_matches('\n').to_owned())
        .filter(|reported| !reported.is_empty())
}

/// Makes the directory a finished command ended in the start of the next
/// one, when the command succeeded and the directory lies inside the paths
/// this terminal may read. When the next command does not start where the
/// shell ended the model is alerted once.
async fn apply_cwd_report(
    carry: &CwdCarry,
    reported: String,
    succeeded: bool,
    ctx: &CarryContext<'_>,
) {
    let Some(carried) = ctx.carried_dir else {
        return;
    };
    if !succeeded {
        if !left_in_start(carry, &reported, ctx.working_dir).await {
            alert_directory_reset(carry, DirectoryResetReason::Failed, ctx).await;
        }
        return;
    }
    if let Some(container) = &carry.container {
        // A container is an unconfined main agent: what bounds its
        // directory is the workspace mount.
        match ContainerPath::new(reported.as_str())
            .map_err(drop)
            .and_then(|dir| container.mount.host_path(&dir).map_err(drop))
        {
            Ok(dir) => carried.set(Some(dir)),
            Err(()) => {
                alert_directory_reset(carry, DirectoryResetReason::OutsideWorkspace, ctx).await;
            }
        }
        return;
    }
    let Ok(dir) = canonical_path(Path::new(&reported)).await else {
        alert_directory_reset(carry, DirectoryResetReason::Removed, ctx).await;
        return;
    };
    for grant in std::iter::once(ctx.working_dir)
        .chain(ctx.grants.writable.iter().map(PathBuf::as_path))
        .chain(ctx.grants.readable.iter().map(PathBuf::as_path))
    {
        if canonical_path(grant)
            .await
            .is_ok_and(|grant| dir.starts_with(grant))
        {
            carried.set(Some(dir));
            return;
        }
    }
    alert_directory_reset(carry, DirectoryResetReason::OutsideReadable, ctx).await;
}

/// Whether the shell ended in the directory the command started in.
async fn left_in_start(carry: &CwdCarry, reported: &str, working_dir: &Path) -> bool {
    if let Some(container) = &carry.container {
        return reported == container.start.as_str();
    }
    let start = carry.start.as_deref().unwrap_or(working_dir);
    match (
        canonical_path(Path::new(reported)).await,
        canonical_path(start).await,
    ) {
        (Ok(reported), Ok(start)) => reported == start,
        _ => false,
    }
}

/// Alerts the model that the next command starts where `carry` started,
/// not where the shell ended.
async fn alert_directory_reset(
    carry: &CwdCarry,
    reason: DirectoryResetReason,
    ctx: &CarryContext<'_>,
) {
    let dir = match &carry.container {
        Some(container) => PathBuf::from(container.start.as_str()),
        None => match &carry.start {
            Some(start) => start.clone(),
            None => canonical_path(ctx.working_dir)
                .await
                .unwrap_or_else(|_| ctx.working_dir.to_path_buf()),
        },
    };
    let _ = ctx
        .alert_tx
        .send(JobAlert::DirectoryReset(DirectoryReset { dir, reason }))
        .await;
}

impl<P: PermissionHandler + 'static, E: Executor + Clone + 'static> TerminalTool<P, E, Configured> {
    /// Runs `script` as a detached background job bounded by `timeout`, for
    /// embedders that drive the terminal directly rather than through the
    /// `terminal` tool schema. Shares [`Self::call`]'s `background: true`
    /// path.
    ///
    /// # Errors
    ///
    /// Fails the way a `terminal` call does: an invalid `timeout`, a
    /// refused permission, a blocked command or a spawn failure.
    pub async fn run_background(&self, arguments: TerminalArgs) -> aither_core::Result<ToolResult> {
        self.call(
            TerminalArgs {
                background: true,
                ..arguments
            },
            ToolContext::new(),
        )
        .await
    }
}

impl<P, E, S> TerminalTool<P, E, S>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
    S: RegistryState,
{
    /// What renders this terminal's refusals and notices: its registry's.
    pub(crate) fn notices(&self) -> &crate::AnySandboxNotices {
        self.registry.registry().notices()
    }

    /// Why a foreground command that was killed was killed, as the model
    /// reads it in the command's result.
    fn kill_notice(&self, kill: Option<&TimeoutKill>) -> String {
        let killed = kill.map_or(crate::CommandKilled::BeforeTimeout, |kill| {
            crate::CommandKilled::TimedOut(kill)
        });
        self.notices().command_killed(&killed)
    }

    /// Shared front half of every `terminal` call: argument validation, then
    /// [`Self::admit_command`].
    async fn prepare_execution(
        &self,
        arguments: &TerminalArgs,
        call: Option<&CallIdentity>,
    ) -> anyhow::Result<ExecutionPreparation> {
        if arguments.description.trim().is_empty() {
            return Err(anyhow::anyhow!("terminal description must not be empty"));
        }
        let origin = if arguments.background {
            ScriptOrigin::Background
        } else {
            ScriptOrigin::Foreground
        };
        self.admit_command(Admission {
            script: &arguments.script,
            language: arguments.language,
            mode: arguments.mode,
            ssh_server_id: arguments.ssh_server_id.as_deref(),
            max_lines: arguments.max_lines,
            origin,
            call,
        })
        .await
        .map_err(|error| match error {
            // Kept unwrapped, so the agent loop recognises the refusal.
            TerminalRunError::Refused(refusal) => anyhow::Error::from(refusal),
            other => anyhow::Error::from(other),
        })
    }

    /// The terminal's policy for a command, whoever runs it — the one entry
    /// every foreground, background, subagent and run command on every
    /// backend passes through: the command policies, the command gate,
    /// target resolution, the read-only tools check and permission; then
    /// the spawned job's ids.
    ///
    /// Every script the policies were asked about is reported to them once
    /// it ends; one admission fails is reported here, unrun.
    async fn admit_command(
        &self,
        admission: Admission<'_>,
    ) -> Result<ExecutionPreparation, TerminalRunError> {
        // Leased for as long as the command can be addressed: the registry
        // keeps a clone once the job is registered.
        let task_id = self.ids.lease()?;
        let policies = self.registry.registry().policies();
        self.check_policies(&task_id, &admission)
            .await
            .map_err(TerminalRunError::Refused)?;
        let admitted = self.admit_checked(&admission).await;
        if admitted.is_err() {
            policies.ended(&task_id, ScriptOutcome::NotRun).await;
        }
        let (target, max_lines) = admitted?;
        Ok(ExecutionPreparation {
            target,
            execution_id: format!("exec-{task_id}"),
            task_id,
            outputs: self.output_store.clone(),
            max_lines,
        })
    }

    /// Puts the script to the registry's command policies, the shell parsed
    /// once for all of them. A refused script is reported to them, unrun.
    async fn check_policies(
        &self,
        task_id: &str,
        admission: &Admission<'_>,
    ) -> Result<(), PolicyRefusal> {
        let policies = self.registry.registry().policies();
        if policies.is_empty() {
            return Ok(());
        }
        let shell = (admission.language == ScriptLanguage::Shell)
            .then(|| crate::ShellScript::parse(admission.script));
        let check = crate::ScriptCheck {
            task_id,
            script: admission.script,
            language: admission.language,
            shell: shell.as_ref().map(Result::as_ref),
            origin: admission.origin,
            role: self.registry.registry().role(),
            working_dir: &self.working_dir,
            call: admission.call,
        };
        let checked = policies.check(&check).await;
        if checked.is_err() {
            policies.ended(task_id, ScriptOutcome::NotRun).await;
        }
        checked
    }

    /// The rest of admission once the policies allowed the script.
    async fn admit_checked(
        &self,
        admission: &Admission<'_>,
    ) -> Result<(ExecutionTarget, usize), TerminalRunError> {
        // Ahead of target resolution and permission, so a blocked command
        // never asks the user for anything. The decision carries no grant.
        // The gate reads shell syntax, so Python source skips it.
        if admission.language == ScriptLanguage::Shell
            && let Some(gate) = self.registry.registry().gate()
            && let GateDecision::Block { reason } = gate.check(admission.script).await
        {
            return Err(TerminalRunError::Blocked(crate::Refused::rendered(
                CommandBlocked { reason },
                |blocked| self.notices().command_blocked(blocked),
            )));
        }
        let target = self.resolve_execution_target(admission.mode, admission.ssh_server_id)?;
        if let ExecutionBackend::Local(tools) = &target.backend {
            tools
                .ensure_readonly(
                    std::iter::once(&self.working_dir)
                        .chain(self.grants.snapshot().writable.iter()),
                )
                .await
                .map_err(TerminalError::from)?;
        }
        self.ensure_permission_allowed(target.mode, admission.script, admission.language)
            .await?;
        Ok((target, admission.max_lines.min(MAX_LINES_CEILING) as usize))
    }

    /// Runs `run` to its end on this terminal; see [`TerminalRunner::run`].
    async fn run_to_end(&self, run: TerminalScript) -> Result<CommandResult, TerminalRunError> {
        let cap = self.limits.timeout_cap;
        if run.timeout.is_zero() || run.timeout > cap {
            return Err(TerminalRunError::Timeout { cap });
        }
        // A run starts in a host directory, so it resolves the terminal's
        // home backend, never an SSH server.
        let mode = match run.mode {
            TerminalMode::Sandboxed => TerminalExecutionMode::Sandboxed,
            TerminalMode::Unsafe => TerminalExecutionMode::Unsafe,
        };
        let prepared = self
            .admit_command(Admission {
                script: &run.script,
                language: ScriptLanguage::Shell,
                mode,
                ssh_server_id: None,
                max_lines: default_max_lines(),
                origin: ScriptOrigin::Run,
                call: None,
            })
            .await?;
        let start = match run_start(&prepared.target, run.working_dir) {
            Ok(start) => start,
            Err(error) => {
                self.registry
                    .registry()
                    .policies()
                    .ended(&prepared.task_id, ScriptOutcome::NotRun)
                    .await;
                return Err(error);
            }
        };
        let spawned = self.spawn_terminal_execution(TerminalSpawnRequest {
            target: prepared.target,
            task_id: prepared.task_id.clone(),
            execution_id: prepared.execution_id,
            script: run.script,
            language: ScriptLanguage::Shell,
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            max_lines: prepared.max_lines,
            raw: false,
            background: false,
            timeout: run.timeout,
            carry: Some(start),
            call: None,
        });
        match spawned.startup.recv().await {
            Ok(Ok(())) => {}
            Ok(Err(error)) => return Err(TerminalError::Execution(error).into()),
            Err(_) => {
                return Err(TerminalError::Execution(
                    "the run ended before it was registered".to_string(),
                )
                .into());
            }
        }
        // The run is never announced as a background task, so its end is
        // told to the caller alone, however long it takes.
        let result =
            spawned.result.recv().await.map_err(|_| {
                TerminalError::Execution("the run ended without a result".to_string())
            });
        let killed = self
            .job_registry
            .get_by_task_id_settled(&prepared.task_id)
            .await
            .is_some_and(|job| matches!(job.status, JobStatus::Killed { .. }));
        let timeout_kill = spawned.timeout_watch.kill();
        spawned.took_result().await;
        let result = result?.map_err(TerminalError::Execution)?;
        if !killed {
            return Ok(CommandResult::from(result));
        }
        Ok(CommandResult {
            stdout: result.stdout,
            stderr: result.stderr,
            interruptions: result.interruptions,
            outcome: CommandOutcome::Killed {
                notice: self.kill_notice(timeout_kill.as_ref()),
                task_id: prepared.task_id.to_string(),
            },
        })
    }

    /// Kills the job through the registry once its timeout passes.
    ///
    /// The returned watch holds the job's start time and, once the watchdog
    /// issues the kill, the time it did.
    fn spawn_kill_watchdog(&self, task_id: &IdLease, timeout: Duration) -> Arc<TimeoutWatch> {
        let watch = Arc::new(TimeoutWatch::new(timeout));
        let job_registry = self.job_registry.clone();
        // Weak, so a job that ended gives its word back before the timer
        // fires; a word that went back may name another job by then.
        let task_id = task_id.downgrade();
        let recorded = watch.clone();
        self.executor
            .spawn(async move {
                async_io::Timer::after(timeout).await;
                let Some(task_id) = task_id.upgrade() else {
                    return;
                };
                if let Some(job) = job_registry.get_by_task_id(&task_id).await
                    && matches!(job.status, JobStatus::Running)
                {
                    // Recorded before the kill, so a result that races the
                    // kill's return already finds it.
                    let _ = recorded.killed.set(jiff::Timestamp::now());
                    job_registry.kill(job.pid).await;
                }
            })
            .detach();
        watch
    }

    /// Emits one [`LongRunningJob`] when the job crosses the configured
    /// long-running threshold.
    fn spawn_long_job_alert(&self, task_id: &IdLease) {
        let job_registry = self.job_registry.clone();
        let alert_tx = self.alert_tx.clone();
        // Weak for the same reason as the watchdog's.
        let task_id = task_id.downgrade();
        let alert_after = self.limits.long_job_alert;
        self.executor
            .spawn(async move {
                async_io::Timer::after(alert_after).await;
                let Some(task_id) = task_id.upgrade() else {
                    return;
                };
                if let Some(job) = job_registry.get_by_task_id(&task_id).await
                    && matches!(job.status, JobStatus::Running)
                {
                    let _ = alert_tx
                        .send(JobAlert::LongRunning(LongRunningJob {
                            task_id: task_id.to_string(),
                            script: job.script,
                            elapsed: job.started_at.elapsed(),
                        }))
                        .await;
                }
            })
            .detach();
    }
}

/// What [`TerminalTool::admit_command`] admits: a script and how it came.
struct Admission<'a> {
    script: &'a str,
    language: ScriptLanguage,
    mode: TerminalExecutionMode,
    ssh_server_id: Option<&'a str>,
    max_lines: u32,
    origin: ScriptOrigin,
    call: Option<&'a CallIdentity>,
}

struct ExecutionPreparation {
    target: ExecutionTarget,
    task_id: IdLease,
    execution_id: String,
    outputs: OutputStore,
    max_lines: usize,
}

/// Where a run starts: `dir` on the host, mapped through the workspace
/// mount for a container command. A run carries no directory, so it writes
/// no report.
fn run_start(target: &ExecutionTarget, dir: PathBuf) -> Result<CwdCarry, TerminalRunError> {
    let container = match &target.backend {
        ExecutionBackend::Local(_) => None,
        ExecutionBackend::Container { runtime, .. } => {
            let mount = runtime
                .workspace_mount()
                .cloned()
                .ok_or(TerminalRunError::NoWorkspaceMount)?;
            let start = mount.container_path(&dir)?;
            Some(ContainerCarry {
                mount,
                report: None,
                start,
            })
        }
        ExecutionBackend::Ssh { .. } => unreachable!("a run resolves the home backend"),
    };
    Ok(CwdCarry {
        start: Some(dir),
        report: None,
        container,
        shell: false,
    })
}

async fn wait_for_background_startup(
    startup_rx: &Receiver<Result<(), String>>,
) -> anyhow::Result<()> {
    match startup_rx.recv().await {
        Ok(Ok(())) => Ok(()),
        Ok(Err(err)) => Err(anyhow::anyhow!(err)),
        Err(_) => Err(anyhow::anyhow!(
            "background startup channel dropped before registration"
        )),
    }
}

/// Races the result channel against the foreground limit.
///
/// Returns `None` when the limit expired (or the channel was dropped, which
/// the caller treats the same way — the job is finished or killed).
async fn wait_for_foreground_result(
    result_rx: &Receiver<Result<CompletedCommand, String>>,
    limit: Duration,
) -> Option<Result<CompletedCommand, String>> {
    futures_lite::future::or(async { result_rx.recv().await.ok() }, async {
        async_io::Timer::after(limit).await;
        result_rx.try_recv().ok()
    })
    .await
}

async fn background_terminal_result(
    job_registry: &JobRegistry,
    outputs: &OutputStore,
    task_id: &str,
    max_lines: usize,
    started_tx: &Sender<StartedBackgroundTask>,
) -> aither_core::Result<ToolResult> {
    let redirect =
        start_background_output_redirect(job_registry, outputs, task_id, max_lines).await?;
    let _ = started_tx
        .send(StartedBackgroundTask {
            task_id: task_id.to_string(),
            output_preview: redirect.preview.clone(),
            output_file: redirect.file.clone(),
        })
        .await;
    let stdout = if redirect.truncated {
        CommandStream::Stored {
            file: redirect.file.clone(),
            preview: redirect.preview,
            truncated: true,
        }
    } else {
        CommandStream::Inline {
            text: redirect.preview,
        }
    };
    CommandResult {
        stdout,
        stderr: None,
        interruptions: Vec::new(),
        outcome: CommandOutcome::Running {
            task_id: task_id.to_string(),
            output: redirect.file,
        },
    }
    .into_tool_result()
}

/// Output file a background job was redirected to, with what it holds so far.
struct BackgroundRedirect {
    file: StoredFile,
    /// First lines already written; empty when nothing was.
    preview: String,
    truncated: bool,
}

async fn start_background_output_redirect(
    job_registry: &JobRegistry,
    outputs: &OutputStore,
    task_id: &str,
    max_lines: usize,
) -> Result<BackgroundRedirect, anyhow::Error> {
    let (url, output_path) = outputs.save_raw(&[]).await?;
    let file = StoredFile {
        url,
        path: output_path.display().to_string(),
    };
    let snapshot = job_registry
        .start_output_redirect(task_id, output_path)
        .await
        .map_err(anyhow::Error::msg)?;
    let (preview, truncated) = preview_first_lines(&snapshot, max_lines);
    Ok(BackgroundRedirect {
        file,
        preview: background_preview(&preview),
        truncated,
    })
}

/// The preview of what a background job has written so far: empty when it
/// wrote only whitespace, otherwise the text with its trailing whitespace cut
/// and the first line's indentation kept.
fn background_preview(preview: &str) -> String {
    if preview.trim().is_empty() {
        String::new()
    } else {
        preview.trim_end().to_string()
    }
}

struct StandaloneExecution<P, E> {
    working_dir: PathBuf,
    writable_paths: Vec<PathBuf>,
    readable_paths: Vec<PathBuf>,
    read_denied_paths: Vec<PathBuf>,
    git_dir: GitDirAccess,
    env_source: Option<Arc<dyn TerminalEnvSource>>,
    executor: E,
    registry: Arc<ToolRegistry>,
    permission_handler: Arc<P>,
    job_registry: JobRegistry,
    task_id: IdLease,
    execution_id: String,
    background: bool,
    carry: Option<CwdCarry>,
    carried_dir: Option<CarriedDir>,
    alert_tx: Sender<JobAlert>,
    script: String,
    language: ScriptLanguage,
    mode: TerminalMode,
    backend: ExecutionBackend,
    stdin_alerts: Option<StdinAlerts>,
    lifetime: JobLifetime,
    background_startup: BackgroundStartup,
    network_audit: Option<NetworkAuditLog>,
    priority: ProcessPriority,
    #[cfg(all(unix, feature = "jobserver"))]
    jobserver: Option<JobBroker>,
    heel: SharedHeelBinary,
    expect: OutputFormat,
    resolution: MediaResolution,
    outputs: OutputStore,
    max_lines: usize,
    raw: bool,
}

struct StandaloneStart<'a, P, E> {
    working_dir: &'a Path,
    writable_paths: &'a [PathBuf],
    readable_paths: &'a [PathBuf],
    read_denied_paths: &'a [PathBuf],
    git_dir: GitDirAccess,
    env_source: &'a Option<Arc<dyn TerminalEnvSource>>,
    executor: E,
    registry: &'a Arc<ToolRegistry>,
    permission_handler: Arc<P>,
    job_registry: &'a JobRegistry,
    task_id: &'a IdLease,
    execution_id: &'a str,
    carry: Option<&'a CwdCarry>,
    script: &'a str,
    language: ScriptLanguage,
    mode: TerminalMode,
    backend: &'a ExecutionBackend,
    stdin_alerts: Option<StdinAlerts>,
    lifetime: JobLifetime,
    background_startup: &'a BackgroundStartup,
    network_audit: Option<NetworkAuditLog>,
    priority: ProcessPriority,
    #[cfg(all(unix, feature = "jobserver"))]
    jobserver: &'a Option<JobBroker>,
    heel: &'a SharedHeelBinary,
}

struct LocalBackgroundExecution<'a, E> {
    prepared_tools: &'a PreparedTools<PathBuf>,
    working_dir: &'a Path,
    writable_paths: &'a [PathBuf],
    readable_paths: &'a [PathBuf],
    read_denied_paths: &'a [PathBuf],
    git_dir: GitDirAccess,
    env_source: &'a Option<Arc<dyn TerminalEnvSource>>,
    executor: E,
    registry: &'a Arc<ToolRegistry>,
    task_id: &'a IdLease,
    execution_id: &'a str,
    carry: Option<&'a CwdCarry>,
    script: &'a str,
    language: ScriptLanguage,
    mode: TerminalMode,
    job_registry: &'a JobRegistry,
    stdin_alerts: Option<StdinAlerts>,
    lifetime: JobLifetime,
    background_startup: &'a BackgroundStartup,
    priority: ProcessPriority,
    #[cfg(all(unix, feature = "jobserver"))]
    job_fifo: Option<crate::jobserver::CommandFifo>,
    heel: &'a SharedHeelBinary,
}

struct ContainerBackgroundExecution<'a, E> {
    executor: E,
    env_source: &'a Option<Arc<dyn TerminalEnvSource>>,
    registry: &'a Arc<ToolRegistry>,
    task_id: &'a IdLease,
    execution_id: &'a str,
    script: &'a str,
    language: ScriptLanguage,
    mode: TerminalMode,
    container_runtime: &'a ContainerShellRuntime,
    prepared_tools: &'a PreparedTools<ContainerPath>,
    confinement: Option<&'a ContainerConfinement>,
    carry: Option<&'a ContainerCarry>,
    ipc_commands: &'a [String],
    job_registry: &'a JobRegistry,
    stdin_alerts: Option<StdinAlerts>,
    lifetime: JobLifetime,
    background_startup: &'a BackgroundStartup,
    priority: ProcessPriority,
    /// The command's jobserver fifo inside the container, held until its
    /// exec has ended.
    #[cfg(all(unix, feature = "jobserver"))]
    job_fifo: Option<crate::container_jobserver::ContainerJobFifo>,
}

struct SshBackgroundExecution<'a> {
    prepared_tools: &'a PreparedTools<PathBuf>,
    task_id: &'a IdLease,
    execution_id: &'a str,
    script: &'a str,
    language: ScriptLanguage,
    mode: TerminalMode,
    ssh_target: &'a str,
    ssh_runtime: &'a SshRuntimeProfile,
    job_registry: &'a JobRegistry,
    background_startup: &'a BackgroundStartup,
}

struct CompletedProcessOutput<'a> {
    job_registry: &'a JobRegistry,
    pid: u32,
    output: std::process::Output,
    background_output: bool,
    outputs: &'a OutputStore,
    expect: OutputFormat,
    resolution: MediaResolution,
    max_lines: usize,
    raw: bool,
}

/// Where a command runs, with the tools prepared for exactly that environment.
enum ExecutionBackend {
    /// The local sandbox, whose tools live at a host path.
    Local(PreparedTools<PathBuf>),
    /// A container, whose tools are mounted at a container path.
    Container {
        runtime: ContainerShellRuntime,
        tools: PreparedTools<ContainerPath>,
        /// The sandbox a subagent's command runs in inside the container; the
        /// main agent's commands run unconfined.
        confinement: Option<ContainerConfinement>,
    },
    /// A remote host over SSH.
    Ssh {
        target: String,
        runtime: SshRuntimeProfile,
        tools: PreparedTools<PathBuf>,
    },
}

struct ExecutionTarget {
    mode: TerminalMode,
    backend: ExecutionBackend,
}

struct TerminalSpawnRequest {
    target: ExecutionTarget,
    task_id: IdLease,
    execution_id: String,
    script: String,
    language: ScriptLanguage,
    expect: OutputFormat,
    resolution: MediaResolution,
    max_lines: usize,
    raw: bool,
    background: bool,
    timeout: Duration,
    carry: Option<CwdCarry>,
    /// The `terminal` call this execution belongs to.
    call: Option<CallIdentity>,
}

struct SpawnedTerminal {
    result: Receiver<Result<CompletedCommand, String>>,
    startup: Receiver<Result<(), String>>,
    timeout_watch: Arc<TimeoutWatch>,
    /// Tells the job's flow the call returned its result itself; dropped
    /// unsent, the job is a background task whose completion the agent takes.
    taken: Sender<Sender<()>>,
}

impl SpawnedTerminal {
    /// The call returns the job's result itself: nothing addresses the job
    /// once it does, so its flow takes the completion on the agent's behalf.
    /// Returns once the flow ended and the registry forgot the job, so the
    /// task id is back with the allocator when the call returns.
    async fn took_result(self) {
        let (done_tx, done_rx) = async_channel::bounded(1);
        // A flow that ended without a result no longer listens.
        if self.taken.send(done_tx).await.is_ok() {
            let _ = done_rx.recv().await;
        }
    }
}

struct SpawnedTerminalTask<P, E> {
    working_dir: PathBuf,
    writable_paths: Vec<PathBuf>,
    readable_paths: Vec<PathBuf>,
    read_denied_paths: Vec<PathBuf>,
    git_dir: GitDirAccess,
    executor: E,
    registry: Arc<ToolRegistry>,
    permission_handler: Arc<P>,
    job_registry: JobRegistry,
    task_id: IdLease,
    execution_id: String,
    background: bool,
    timeout_watch: Arc<TimeoutWatch>,
    carry: Option<CwdCarry>,
    carried_dir: Option<CarriedDir>,
    alert_tx: Sender<JobAlert>,
    script: String,
    language: ScriptLanguage,
    mode: TerminalMode,
    backend: ExecutionBackend,
    stdin_alerts: Option<StdinAlerts>,
    lifetime: JobLifetime,
    background_startup: BackgroundStartup,
    expect: OutputFormat,
    resolution: MediaResolution,
    outputs: OutputStore,
    max_lines: usize,
    raw: bool,
    result_tx: Sender<Result<CompletedCommand, String>>,
    /// Whether the call took the result: see [`SpawnedTerminal::took_result`].
    taken: Receiver<Sender<()>>,
    completed_tx: Sender<CompletedTask>,
    running_tasks: Arc<AtomicUsize>,
    env_source: Option<Arc<dyn TerminalEnvSource>>,
    network_audit: Option<NetworkAuditLog>,
    priority: ProcessPriority,
    #[cfg(all(unix, feature = "jobserver"))]
    jobserver: Option<JobBroker>,
    heel: SharedHeelBinary,
    outages: Outages,
}

#[allow(clippy::too_many_lines)]
async fn execute_terminal_task<P, E>(task: SpawnedTerminalTask<P, E>)
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    let SpawnedTerminalTask {
        working_dir,
        writable_paths,
        readable_paths,
        read_denied_paths,
        git_dir,
        env_source,
        executor,
        registry,
        permission_handler,
        job_registry,
        task_id,
        execution_id,
        background,
        timeout_watch,
        carry,
        carried_dir,
        alert_tx,
        script,
        language,
        mode,
        backend,
        stdin_alerts,
        lifetime,
        background_startup,
        expect,
        resolution,
        outputs,
        max_lines,
        raw,
        result_tx,
        taken,
        completed_tx,
        running_tasks,
        network_audit,
        priority,
        #[cfg(all(unix, feature = "jobserver"))]
        jobserver,
        heel,
        outages,
    } = task;
    let status_registry = job_registry.clone();
    let policies = registry.policies().clone();
    let result = execute_script_standalone(StandaloneExecution {
        working_dir,
        writable_paths,
        readable_paths,
        read_denied_paths,
        git_dir,
        env_source,
        executor,
        registry,
        permission_handler,
        job_registry,
        task_id: task_id.clone(),
        execution_id,
        background,
        carry,
        carried_dir,
        alert_tx,
        script: script.clone(),
        language,
        mode,
        backend,
        stdin_alerts,
        lifetime,
        background_startup,
        network_audit,
        priority,
        #[cfg(all(unix, feature = "jobserver"))]
        jobserver,
        heel,
        expect,
        resolution,
        outputs,
        max_lines,
        raw,
    })
    .await;
    let interruptions = outages.end(&task_id).await;
    let result = result.map(|command| CompletedCommand {
        interruptions,
        ..command
    });
    // Ahead of the result, so what a policy records of this end holds for
    // the agent's next call.
    let outcome = result
        .as_ref()
        .map_or(ScriptOutcome::Failed, |command| ScriptOutcome::Exited {
            code: command.exit_code,
        });
    policies.ended(&task_id, outcome).await;

    let quick_result = match &result {
        Ok(ok) => Ok(ok.clone()),
        Err(err) => Err(err.to_string()),
    };
    let _ = result_tx.send(quick_result).await;
    // The call answers at once, taking the result or leaving it to a
    // background task.
    let foreground = taken.recv().await.ok();
    // A kill's signal can end the process before the kill records its
    // outcome, so the registry settles the ending once no kill is in flight.
    let ending = match &result {
        Ok(command) => Ok(command.exit_code),
        Err(error) => Err(error.to_string()),
    };
    let owed = status_registry.owe_completion(&task_id, ending).await;
    let kill = owed.as_ref().and_then(|owed| owed.kill);
    let mut pending = owed.map(|owed| owed.pending);
    // A result the call returned leaves nothing for the agent to take: the
    // completion is taken here, so the registry forgets the job.
    if foreground.is_some()
        && let Some(pending) = pending.take()
    {
        pending.take().await;
    }
    // Every job reports completion; the agent reinjects the result only for
    // tasks it saw promoted or detached (`take_started`), so a plain
    // foreground result is not delivered twice.
    let _ = completed_tx
        .send(CompletedTask {
            task_id: task_id.to_string(),
            script,
            result,
            kill,
            timeout_kill: timeout_watch.kill().filter(|_| kill.is_some()),
            pending,
        })
        .await;
    running_tasks.fetch_sub(1, Ordering::AcqRel);
    // The flow's own hold on the word ends before the call returns.
    drop(task_id);
    if let Some(done) = foreground {
        let _ = done.send(()).await;
    }
}

/// Standalone script execution that can be spawned in a background task.
#[allow(clippy::too_many_lines)]
async fn execute_script_standalone<P, E>(
    request: StandaloneExecution<P, E>,
) -> Result<CompletedCommand, TerminalError>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    let StandaloneExecution {
        working_dir,
        writable_paths,
        readable_paths,
        read_denied_paths,
        git_dir,
        env_source,
        executor,
        registry,
        permission_handler,
        job_registry,
        task_id,
        execution_id,
        background,
        carry,
        carried_dir,
        alert_tx,
        script,
        language,
        mode,
        backend,
        stdin_alerts,
        lifetime,
        background_startup,
        network_audit,
        priority,
        #[cfg(all(unix, feature = "jobserver"))]
        jobserver,
        heel,
        expect,
        resolution,
        outputs,
        max_lines,
        raw,
    } = request;

    info!(
        script_len = script.len(),
        ?mode,
        "executing background terminal command"
    );
    debug!(script = %script, "script content");
    let start_result = start_standalone_execution(StandaloneStart {
        working_dir: &working_dir,
        writable_paths: &writable_paths,
        readable_paths: &readable_paths,
        read_denied_paths: &read_denied_paths,
        git_dir,
        env_source: &env_source,
        executor,
        registry: &registry,
        permission_handler,
        job_registry: &job_registry,
        task_id: &task_id,
        execution_id: &execution_id,
        carry: carry.as_ref(),
        script: &script,
        language,
        mode,
        backend: &backend,
        stdin_alerts,
        lifetime,
        background_startup: &background_startup,
        network_audit,
        priority,
        #[cfg(all(unix, feature = "jobserver"))]
        jobserver: &jobserver,
        heel: &heel,
    })
    .await;
    let (pid, output) = match start_result {
        Ok(started) => started,
        Err(error) => {
            background_startup.report_failure(&error).await;
            return Err(error);
        }
    };

    let result = save_completed_process_output(CompletedProcessOutput {
        job_registry: &job_registry,
        pid,
        output,
        background_output: background,
        outputs: &outputs,
        expect,
        resolution,
        max_lines,
        raw,
    })
    .await?;
    let exit_code = result.exit_code;

    debug!(exit_code, "background script completed");

    let output_path = stored_path(&result.stdout);
    job_registry.complete(pid, exit_code, output_path).await;

    // The command's directory report arrives with its end, whether the call
    // answered in the foreground window or the command promoted: the task
    // is its sole consumer, so the next command starts where the shell
    // ended and the report file never lingers.
    if let Some(carry) = &carry {
        let ctx = CarryContext {
            carried_dir: carried_dir.as_ref(),
            alert_tx: &alert_tx,
            working_dir: &working_dir,
            grants: std::sync::Arc::new(GrantSet {
                readable: readable_paths.clone(),
                writable: writable_paths.clone(),
                read_denied: read_denied_paths.clone(),
                git_dir,
            }),
        };
        if let Some(reported) = take_cwd_report(carry).await {
            apply_cwd_report(carry, reported, exit_code == 0, &ctx).await;
        } else if ctx.carried_dir.is_some() && carry.shell {
            alert_directory_reset(carry, DirectoryResetReason::Unreported, &ctx).await;
        }
    }

    Ok(result)
}

#[allow(clippy::too_many_lines)]
async fn start_standalone_execution<P, E>(
    request: StandaloneStart<'_, P, E>,
) -> Result<(u32, std::process::Output), TerminalError>
where
    P: PermissionHandler + 'static,
    E: Executor + Clone + 'static,
{
    let prepared_tools = match request.backend {
        ExecutionBackend::Local(tools) => tools,
        ExecutionBackend::Container {
            runtime,
            tools,
            confinement,
        } => {
            // The command's fifo lives in the container's kernel, brokered
            // by a relay run with the image's managed `python3`.
            #[cfg(all(unix, feature = "jobserver"))]
            let job_fifo = match request.jobserver {
                Some(broker) => Some(
                    crate::container_jobserver::open_container_job_fifo(
                        broker,
                        runtime,
                        &tools.bin_dir().join("python3"),
                        request.executor.clone(),
                    )
                    .await?,
                ),
                None => None,
            };
            let ipc_commands = request.registry.registered_tool_names();
            return execute_container_background(ContainerBackgroundExecution {
                executor: request.executor,
                env_source: request.env_source,
                registry: request.registry,
                task_id: request.task_id,
                execution_id: request.execution_id,
                script: request.script,
                language: request.language,
                mode: request.mode,
                container_runtime: runtime,
                prepared_tools: tools,
                confinement: confinement.as_ref(),
                carry: request.carry.and_then(|carry| carry.container.as_ref()),
                ipc_commands: &ipc_commands,
                job_registry: request.job_registry,
                stdin_alerts: request.stdin_alerts,
                lifetime: request.lifetime,
                background_startup: request.background_startup,
                priority: request.priority,
                #[cfg(all(unix, feature = "jobserver"))]
                job_fifo,
            })
            .await;
        }
        ExecutionBackend::Ssh {
            target,
            runtime,
            tools,
        } => {
            // The remote host is outside the pool's reach; running there
            // unbounded would defeat it.
            #[cfg(all(unix, feature = "jobserver"))]
            if request.jobserver.is_some() {
                return Err(TerminalError::Execution(
                    "jobserver token pools are not supported for SSH executions".into(),
                ));
            }
            return execute_ssh_background(SshBackgroundExecution {
                prepared_tools: tools,
                task_id: request.task_id,
                execution_id: request.execution_id,
                script: request.script,
                language: request.language,
                mode: request.mode,
                ssh_target: target,
                ssh_runtime: runtime,
                job_registry: request.job_registry,
                background_startup: request.background_startup,
            })
            .await;
        }
    };
    #[cfg(all(unix, feature = "jobserver"))]
    let job_fifo = match request.jobserver {
        Some(broker) => Some(broker.open_fifo().await?),
        None => None,
    };
    let local = LocalBackgroundExecution {
        prepared_tools,
        working_dir: request.working_dir,
        writable_paths: request.writable_paths,
        readable_paths: request.readable_paths,
        read_denied_paths: request.read_denied_paths,
        git_dir: request.git_dir,
        env_source: request.env_source,
        executor: request.executor,
        registry: request.registry,
        task_id: request.task_id,
        execution_id: request.execution_id,
        carry: request.carry,
        script: request.script,
        language: request.language,
        mode: request.mode,
        job_registry: request.job_registry,
        stdin_alerts: request.stdin_alerts,
        lifetime: request.lifetime,
        background_startup: request.background_startup,
        priority: request.priority,
        #[cfg(all(unix, feature = "jobserver"))]
        job_fifo,
        heel: request.heel,
    };
    match request.mode {
        TerminalMode::Sandboxed => {
            execute_audited_sandboxed_background(
                local,
                PermissionNetworkPolicy {
                    permission_handler: request.permission_handler,
                },
                request.network_audit,
            )
            .await
        }
        TerminalMode::Unsafe => execute_unsafe_background(local).await,
    }
}

/// Runs a sandboxed execution, recording policy verdicts when an audit log is
/// configured. Unsafe mode bypasses the proxy entirely, so it cannot be
/// audited at this layer.
async fn execute_audited_sandboxed_background<E, N>(
    local: LocalBackgroundExecution<'_, E>,
    policy: N,
    audit: Option<NetworkAuditLog>,
) -> Result<(u32, std::process::Output), TerminalError>
where
    E: Executor + Clone + 'static,
    N: NetworkPolicy + 'static,
{
    match audit {
        Some(log) => execute_sandboxed_background(local, Audited::new(policy, log)).await,
        None => execute_sandboxed_background(local, policy).await,
    }
}

async fn save_completed_process_output(
    request: CompletedProcessOutput<'_>,
) -> Result<CompletedCommand, TerminalError> {
    let CompletedProcessOutput {
        job_registry,
        pid,
        output,
        background_output,
        outputs,
        expect,
        resolution,
        max_lines,
        raw,
    } = request;
    let stdout = save_completed_stdout(
        job_registry,
        pid,
        &output.stdout,
        CompletedStdoutFormat {
            background_output,
            outputs,
            expect,
            resolution,
            max_lines,
            raw,
        },
    )
    .await?;
    let stderr = save_completed_stderr(job_registry, pid, outputs, &output.stderr).await?;
    let exit_code = output.status.code().unwrap_or(-1);

    Ok(CompletedCommand {
        stdout,
        stderr,
        exit_code,
        interruptions: Vec::new(),
    })
}

struct CompletedStdoutFormat<'a> {
    background_output: bool,
    outputs: &'a OutputStore,
    expect: OutputFormat,
    resolution: MediaResolution,
    max_lines: usize,
    raw: bool,
}

async fn save_completed_stdout(
    job_registry: &JobRegistry,
    pid: u32,
    stdout: &[u8],
    format: CompletedStdoutFormat<'_>,
) -> Result<CommandStream, TerminalError> {
    let byte_limit = Some(INLINE_OUTPUT_LIMIT);
    let data_to_save = if format.background_output {
        Cow::Borrowed(stdout)
    } else {
        compressed_stdout_data(format.outputs, stdout, format.expect, format.raw).await?
    };

    match format
        .outputs
        .save_text_with_line_limit(
            data_to_save.as_ref(),
            format.expect,
            format.resolution,
            format.max_lines,
            byte_limit,
        )
        .await
    {
        Ok(entry) => Ok(entry),
        Err(err) => {
            job_registry.fail(pid, &err.to_string(), None).await;
            Err(TerminalError::Io(err))
        }
    }
}

/// Runs the output cleaning pipeline over a completed command's stdout.
///
/// `raw: true` bypasses it entirely, as do non-text formats and output that
/// is not valid UTF-8, so the model sees exactly the bytes the command wrote.
async fn compressed_stdout_data<'a>(
    outputs: &OutputStore,
    stdout: &'a [u8],
    expect: OutputFormat,
    raw: bool,
) -> Result<Cow<'a, [u8]>, TerminalError> {
    let is_text = matches!(expect, OutputFormat::Text | OutputFormat::Auto);
    if raw || !is_text || stdout.is_empty() {
        return Ok(Cow::Borrowed(stdout));
    }
    let Ok(text) = std::str::from_utf8(stdout) else {
        return Ok(Cow::Borrowed(stdout));
    };

    let cleaned = crate::output_compress::compress_text(outputs, text)
        .await
        .map_err(TerminalError::Io)?;
    Ok(cleaned.map_or(Cow::Borrowed(stdout), |cleaned| {
        Cow::Owned(cleaned.into_bytes())
    }))
}

async fn save_completed_stderr(
    job_registry: &JobRegistry,
    pid: u32,
    outputs: &OutputStore,
    stderr: &[u8],
) -> Result<Option<CommandStream>, TerminalError> {
    if stderr.is_empty() {
        return Ok(None);
    }
    match outputs
        .save_with_limit(
            stderr,
            OutputFormat::Text,
            MediaResolution::Auto,
            Some(INLINE_OUTPUT_LIMIT),
        )
        .await
    {
        Ok(entry) => Ok(Some(entry)),
        Err(err) => {
            job_registry.fail(pid, &err.to_string(), None).await;
            Err(TerminalError::Io(err))
        }
    }
}

/// The `git` shim every sandboxed command's PATH resolves first: a git
/// run in a committing worktree reads the worktree's host-owned entry
/// instead of whatever `.git` its subagent wrote.
#[cfg(unix)]
const GIT_SHIM: &str = include_str!("../templates/git_shim");

/// Writes the `git` shim into the prepared tools directory once: the
/// commands' PATH sees it ahead of the system's `git`.
#[cfg(unix)]
async fn write_git_shim(tools: &PreparedTools<PathBuf>) -> Result<(), TerminalError> {
    use std::os::unix::fs::PermissionsExt as _;
    let shim = tools.bin_dir().join("git");
    match async_fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&shim)
        .await
    {
        Ok(mut file) => {
            file.write_all(GIT_SHIM.as_bytes()).await.map_err(|error| {
                TerminalError::Execution(format!("writing {}: {error}", shim.display()))
            })?;
            file.flush().await.map_err(|error| {
                TerminalError::Execution(format!("writing {}: {error}", shim.display()))
            })?;
            async_fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
                .await
                .map_err(|error| {
                    TerminalError::Execution(format!("writing {}: {error}", shim.display()))
                })
        }
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
        Err(error) => Err(TerminalError::Execution(format!(
            "writing {}: {error}",
            shim.display()
        ))),
    }
}

/// Windows commands run no `sh`: no shim, and the worktrees' git map is
/// never handed out either.
#[cfg(not(unix))]
async fn write_git_shim(_tools: &PreparedTools<PathBuf>) -> Result<(), TerminalError> {
    Ok(())
}

/// The script a container's command runs ahead of its own: the `git`
/// shim written into a writable directory it puts first on `PATH`, and
/// the worktree map as exports. Empty without a map — subagent
/// containers never see it.
#[cfg(unix)]
fn container_git_preamble(
    registry: &ToolRegistry,
    mount: Option<&MountRoot>,
) -> Result<String, TerminalError> {
    use std::fmt::Write as _;
    let mut environment = Vec::new();
    // The shim inside the container compares its working directory against
    // the map: every path it holds must be spelled the way the container's
    // workspace mount resolves it, or the worktree goes unprotected.
    let spell = |path: &Path| -> Result<String, TerminalError> {
        let mount = mount.ok_or_else(|| {
            TerminalError::SandboxSetup(format!(
                "a committing worktree {} has no workspace mount to map through",
                path.display()
            ))
        })?;
        let host_root =
            std::fs::canonicalize(&mount.host_root).unwrap_or_else(|_| mount.host_root.clone());
        MountRoot::new(host_root, mount.container_root.clone())
            .container_path(path)
            .map(|path| path.to_string())
            .map_err(|source| {
                TerminalError::SandboxSetup(format!(
                    "{} is outside the container workspace mount: {source}",
                    path.display()
                ))
            })
    };
    committed_git_environment(registry, &mut environment, spell)?;
    if environment.is_empty() {
        return Ok(String::new());
    }
    let mut preamble =
        "aither_shim=${TMPDIR:-/tmp}/aither-shim-$$\nmkdir -p \"$aither_shim\"\n".to_string();
    preamble.push_str("cat > \"$aither_shim/git\" <<'AITHER_GIT_SHIM'\n");
    preamble.push_str(GIT_SHIM);
    preamble.push_str(
        "AITHER_GIT_SHIM\nchmod +x \"$aither_shim/git\"\nPATH=\"$aither_shim:$PATH\"\nexport PATH\n",
    );
    for (name, value) in &environment {
        writeln!(preamble, "export {name}={}", shell_words::quote(value))
            .expect("a string cannot fail a write");
    }
    Ok(preamble)
}

#[cfg(not(unix))]
fn container_git_preamble(
    _registry: &ToolRegistry,
    _mount: Option<&MountRoot>,
) -> Result<String, TerminalError> {
    Ok(String::new())
}

/// Hands the git shim of a main terminal's commands the worktree map,
/// each path spelled the way `spell` resolves it for the command's
/// context — a host path locally, a container path inside a container.
///
/// A command's `git` in a committing worktree resolves the worktree's
/// host-owned repository entry through `GIT_DIR`, so nothing a subagent
/// wrote — a `.git` file, the repository's configuration, hooks,
/// fsmonitor or filter programs — decides what program git runs. The
/// map only describes paths the host resolved when the grant was made.
/// Subagent terminals keep their own repositories' view.
fn committed_git_environment(
    registry: &ToolRegistry,
    environment: &mut Vec<(String, String)>,
    spell: impl Fn(&Path) -> Result<String, TerminalError>,
) -> Result<(), TerminalError> {
    if registry.role() != crate::command::CommandRole::Main {
        return Ok(());
    }
    let committed = registry.committed_worktrees();
    if committed.is_empty() {
        return Ok(());
    }
    environment.push((
        "AITHER_GIT_WORKTREES_COUNT".to_string(),
        committed.len().to_string(),
    ));
    for (index, worktree) in committed.iter().enumerate() {
        environment.push((
            format!("AITHER_GIT_WORKTREE_PATH_{index}"),
            spell(worktree.worktree())?,
        ));
        environment.push((
            format!("AITHER_GIT_WORKTREE_GITDIR_{index}"),
            spell(worktree.git_dir())?,
        ));
    }
    Ok(())
}

/// The object a spelled path names, in the spelling a resolved grant
/// checks: canonicalized, without the verbatim prefix Windows adds — an
/// 8.3 alias or a symlinked component does not name the same object.
fn resolved(path: &Path) -> heel::Result<ResolvedPath> {
    ResolvedPath::new(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()))
}

/// The grant a command's jobserver fifo needs: it writes tokens back to it.
#[cfg(all(unix, feature = "jobserver"))]
pub fn job_fifo_grant(path: &Path) -> heel::Result<Grant> {
    Ok(Grant::new(resolved(path)?, Access::WRITE))
}

/// The grants a session sandbox gives every command; see
/// [`crate::SessionSandboxPolicy`], the public way to build them.
pub fn local_path_grants(
    writable: &[PathBuf],
    readable: &[PathBuf],
    tools: &PreparedTools<PathBuf>,
) -> heel::Result<Vec<Grant>> {
    writable
        .iter()
        // A writable directory also executes: a sandboxed process can already
        // run anything it writes through an interpreter, and builds must
        // execute their own outputs.
        .map(|path| Ok(Grant::new(resolved(path)?, Access::WRITE | Access::EXEC)))
        .chain(
            readable
                .iter()
                .map(|path| Ok(Grant::new(resolved(path)?, Access::READ))),
        )
        .chain(std::iter::once(Ok(Grant::new(
            resolved(tools.bin_dir())?,
            Access::EXEC,
        ))))
        // The shared `uv` cache and project Python installs, which `uv`
        // writes and the interpreters it installs execute.
        .chain(
            tools
                .uv_dir()
                .map(|path| Ok(Grant::new(resolved(path)?, Access::WRITE | Access::EXEC))),
        )
        .chain(toolchain_grants(resolved))
        .collect()
}

/// The grants that let git work in a granted linked worktree: its common git
/// directory, with the access `git_dir` gives a writable worktree's (the
/// worktree's own for a session's terminal, read for a subagent's). The directory is the
/// repository's, outside the worktree, and a strict sandbox reads only what
/// is granted. Only a pointer git's back-links confirm
/// ([`crate::subagent::confirmed_common_dir`]) grants anything, because the
/// `.git` file sits in a directory the session can write.
pub async fn linked_worktree_grants(
    writable: &[PathBuf],
    readable: &[PathBuf],
    git_dir: GitDirAccess,
) -> heel::Result<Vec<Grant>> {
    let mut grants = Vec::new();
    for (path, access) in writable
        .iter()
        .map(|path| (path, git_dir.writable_worktree_access()))
        .chain(readable.iter().map(|path| (path, Access::READ)))
    {
        if let Some(common) = crate::subagent::confirmed_common_dir(path).await {
            grants.push(Grant::new(resolved(&common)?, access));
        }
    }
    Ok(grants)
}

/// Host toolchain homes a local sandbox reaches: (env var, resolved
/// existing dir). `CARGO_HOME` and `RUSTUP_HOME` fall back to their
/// `~/.cargo` / `~/.rustup` defaults; only directories that exist yield, so
/// a toolchain absent from the host is never granted.
fn host_toolchain_homes() -> impl Iterator<Item = (&'static str, PathBuf)> {
    let home = std::env::home_dir;
    [
        std::env::var_os("CARGO_HOME")
            .map(PathBuf::from)
            .or_else(|| home().map(|home| home.join(".cargo")))
            .map(|path| ("CARGO_HOME", path)),
        std::env::var_os("RUSTUP_HOME")
            .map(PathBuf::from)
            .or_else(|| home().map(|home| home.join(".rustup")))
            .map(|path| ("RUSTUP_HOME", path)),
    ]
    .into_iter()
    .flatten()
    .filter(|(_, path)| path.is_dir())
}

/// The grants that let a command run what the session's `PATH` lists: each
/// existing absolute directory of the `PATH` in `environment`, read and
/// execute, never write. They come from the `PATH` itself, so a tool in any
/// directory the user put there runs without a list of known toolchains.
pub fn path_directory_grants(environment: &[(String, String)]) -> heel::Result<Vec<Grant>> {
    let Some((_, path)) = environment.iter().find(|(name, _)| name == "PATH") else {
        return Ok(Vec::new());
    };
    let mut seen = std::collections::HashSet::new();
    let mut grants = Vec::new();
    for directory in std::env::split_paths(path) {
        if !directory.is_absolute() || !directory.is_dir() {
            continue;
        }
        let resolved = resolved(&directory)?;
        if seen.insert(resolved.as_path().to_path_buf()) {
            grants.push(Grant::new(resolved, Access::READ | Access::EXEC));
        }
    }
    Ok(grants)
}

/// The paths a session sandbox must not write: heel's persistence table
/// (git hooks and config, shell startup files, `PATH` directories and the
/// rest), where a write runs as code outside the sandbox later.
///
/// Three places are exempt, because the table forbids creating a `.git` at all
/// and the commands that need to would otherwise be impossible: cargo's git
/// cache, `$CARGO_HOME/git`, where cargo clones git dependencies and keeps
/// their `.git/hooks`, which it creates and removes itself and no user runs;
/// the session directory `working_dir`, where `git clone` and `git init`
/// make the session's own repositories; and the prepared runtime's `uv`
/// cache (`UV_CACHE_DIR`), whose buckets `uv` marks with a `.git` entry and
/// where no user runs git. Nothing else of a toolchain home is exempt.
pub fn session_write_denylist(
    working_dir: &Path,
    tools: &PreparedTools<PathBuf>,
) -> heel::WriteDenylist {
    let resolved = |path: &Path| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let denylist = heel::WriteDenylist::persistence().except(resolved(working_dir));
    let denylist = match host_toolchain_homes().find(|(name, _)| *name == "CARGO_HOME") {
        Some((_, cargo_home)) => denylist.except(resolved(&cargo_home).join("git")),
        None => denylist,
    };
    match tools.uv_environment() {
        Some(uv) => denylist.except(resolved(&uv.cache)),
        None => denylist,
    }
}

/// The paths a local sandbox must not read: heel's credential table plus the
/// embedder's `denied` absolute paths. Everything else stays readable.
#[cfg(not(windows))]
fn session_read_denylist(denied: &[PathBuf]) -> heel::ReadDenylist {
    denied
        .iter()
        .fold(heel::ReadDenylist::credentials(), |denylist, path| {
            denylist.deny(path)
        })
}

/// The toolchain directories a sandboxed build needs: package-manager
/// installs, compilers, and their caches, each rwx since builds both run
/// the binaries and write the caches. Credential files inside them stay
/// denied by the security tables, which emit after grants.
fn toolchain_grants(
    resolved: impl Fn(&Path) -> heel::Result<ResolvedPath>,
) -> impl Iterator<Item = heel::Result<Grant>> {
    host_toolchain_homes()
        .map(move |(_, path)| Ok(Grant::new(resolved(&path)?, Access::WRITE | Access::EXEC)))
}

async fn execute_sandboxed_background<E, N>(
    context: LocalBackgroundExecution<'_, E>,
    policy: N,
) -> Result<(u32, std::process::Output), TerminalError>
where
    E: Executor + Clone + 'static,
    N: NetworkPolicy + 'static,
{
    let (grants, mut runtime_environment, write_denylist) = local_launch_policy(&context).await?;
    let marker = JobMarker::new();
    runtime_environment.push(marker.entry());
    let heel_binary = context
        .heel
        .get()
        .await
        .map_err(|e| TerminalError::SandboxSetup(e.to_string()))?;
    let config_builder = SandboxConfig::builder().network(policy);
    // The Windows backend refuses a write denylist rather than run weaker.
    // The same holds for the read denylist: reads are open everywhere except
    // the credential table and the embedder's additions.
    #[cfg(not(windows))]
    let config_builder = config_builder
        .write_denylist(write_denylist)
        .filesystem_strict(false)
        .read_denylist(session_read_denylist(context.read_denied_paths));
    #[cfg(windows)]
    drop(write_denylist);
    let config_builder = config_builder
        .working_dir(
            // A symlink in the working directory's spelling fails the
            // sandbox's own resolution — it does not follow a link a
            // sandboxed process could have planted.
            std::fs::canonicalize(context.working_dir)
                .unwrap_or_else(|_| context.working_dir.to_path_buf()),
        )
        .grants(grants)
        .heel_binary(heel_binary)
        .security(SecurityConfig::interactive())
        // The session's own commands run their build outputs — anything
        // written here could already run through an interpreter.
        .executable_working_dir(true)
        .priority(context.priority);
    #[cfg(target_os = "linux")]
    let config_builder = config_builder.supervised_spawn(true);
    // `ipc` changes the builder's type, so both arms build where they are.
    let config = match create_ipc_router(context.registry) {
        Some(router) => config_builder.ipc(router).build(),
        None => config_builder.build(),
    };

    let sandbox = Sandbox::with_config_and_executor(config, context.executor.clone())
        .await
        .map_err(|e| TerminalError::SandboxSetup(e.to_string()))?;

    let launch_script = launch_script(context.language, context.script, context.task_id)?;
    let launch = build_terminal_launch(
        &context.prepared_tools.shell()?,
        &launch_script,
        context.carry.and_then(|carry| carry.report.as_deref()),
    )?;
    let (program, args) = match &launch {
        TerminalLaunch::Direct { program, args } | TerminalLaunch::Shell { program, args } => {
            (program, args)
        }
    };

    let mut command = sandbox.command(program);
    if let Some(start) = context.carry.and_then(|carry| carry.start.as_deref()) {
        command = command.current_dir(start);
    }
    let (child, tree) = spawn_local_command(
        command,
        args,
        runtime_environment,
        context.stdin_alerts.as_ref(),
        &context.lifetime,
        context.job_registry,
        &context.executor,
        &marker,
    )
    .await?;

    let pid = child.id();
    context
        .job_registry
        .register_with_tree(
            pid,
            context.task_id,
            context.execution_id,
            context.script,
            context.language,
            context.mode,
            None,
            Some(tree.clone()),
            crate::JobPlace::Host,
        )
        .await;
    context.background_startup.report_ready().await;

    let output = collect_local_process_output(
        child,
        context.executor,
        context.job_registry,
        pid,
        LocalJob {
            tree,
            lifetime: context.lifetime,
            stdin_alerts: context.stdin_alerts,
        },
        "missing stdout pipe for sandbox process",
        "missing stderr pipe for sandbox process",
    )
    .await?;

    Ok((pid, output))
}

async fn execute_unsafe_background<E: Executor + Clone + 'static>(
    context: LocalBackgroundExecution<'_, E>,
) -> Result<(u32, std::process::Output), TerminalError> {
    let (_, mut runtime_environment, _) = local_launch_policy(&context).await?;
    let marker = JobMarker::new();
    runtime_environment.push(marker.entry());
    let heel_binary = context
        .heel
        .get()
        .await
        .map_err(|e| TerminalError::SandboxSetup(e.to_string()))?;
    let config_builder = SandboxConfig::builder()
        .working_dir(
            std::fs::canonicalize(context.working_dir)
                .unwrap_or_else(|_| context.working_dir.to_path_buf()),
        )
        // Unsafe is approved host execution — the user runs the script
        // themselves in every respect except IPC plumbing, so no
        // credential or filesystem protection may apply.
        .host_access()
        .heel_binary(heel_binary)
        .executable_working_dir(true)
        .priority(context.priority);
    #[cfg(target_os = "linux")]
    let config_builder = config_builder.supervised_spawn(true);
    // `ipc` changes the builder's type, so both arms build where they are.
    let config = match create_ipc_gateway_router(context.registry) {
        Some(router) => config_builder.ipc(router).build(),
        None => config_builder.build(),
    };

    let sandbox = Sandbox::with_config_and_executor(config, context.executor.clone())
        .await
        .map_err(|e| TerminalError::SandboxSetup(e.to_string()))?;

    let launch_script = launch_script(context.language, context.script, context.task_id)?;
    let launch = build_terminal_launch(
        &context.prepared_tools.shell()?,
        &launch_script,
        context.carry.and_then(|carry| carry.report.as_deref()),
    )?;
    let (program, args) = match &launch {
        TerminalLaunch::Direct { program, args } | TerminalLaunch::Shell { program, args } => {
            (program, args)
        }
    };

    let mut command = sandbox.command(program);
    if let Some(start) = context.carry.and_then(|carry| carry.start.as_deref()) {
        command = command.current_dir(start);
    }
    let (child, tree) = spawn_local_command(
        command,
        args,
        runtime_environment,
        context.stdin_alerts.as_ref(),
        &context.lifetime,
        context.job_registry,
        &context.executor,
        &marker,
    )
    .await?;

    let pid = child.id();
    context
        .job_registry
        .register_with_tree(
            pid,
            context.task_id,
            context.execution_id,
            context.script,
            context.language,
            context.mode,
            None,
            Some(tree.clone()),
            crate::JobPlace::Host,
        )
        .await;
    context.background_startup.report_ready().await;

    let output = collect_local_process_output(
        child,
        context.executor,
        context.job_registry,
        pid,
        LocalJob {
            tree,
            lifetime: context.lifetime,
            stdin_alerts: context.stdin_alerts,
        },
        "missing stdout pipe for unsafe process",
        "missing stderr pipe for unsafe process",
    )
    .await?;

    Ok((pid, output))
}

/// How long a command's descendants may outlive its top-level shell.
#[derive(Clone)]
enum JobLifetime {
    /// None: the survivors are killed and reported on `alerts`.
    Foreground { alerts: Sender<JobAlert> },
    /// All of them: the job runs until its whole tree has exited.
    Background,
}

/// Where a background job's stdin alerts go.
///
/// Its presence is what makes a command a background job: a command without
/// one reads EOF from a null stdin.
struct StdinAlerts {
    tx: Sender<JobAlert>,
    task_id: String,
    script: String,
}

impl StdinAlerts {
    async fn raise(&self) {
        debug!(task_id = %self.task_id, "background job is blocked on stdin");
        let _ = self
            .tx
            .send(JobAlert::StdinBlocked(StdinBlockedJob {
                task_id: self.task_id.clone(),
                script: self.script.clone(),
            }))
            .await;
    }

    /// Tells the agent this job's stdin watch died: no blocked-on-stdin
    /// alert can come for it anymore.
    async fn raise_failure(&self, error: String) {
        warn!(task_id = %self.task_id, error = %error, "stdin watch failed");
        let _ = self
            .tx
            .send(JobAlert::StdinProbeFailed(StdinProbeFailedJob {
                task_id: self.task_id.clone(),
                script: self.script.clone(),
                error,
            }))
            .await;
    }
}

const fn local_stdin_config(alerts: Option<&StdinAlerts>) -> StdioConfig {
    if alerts.is_some() {
        StdioConfig::Piped
    } else {
        StdioConfig::Null
    }
}

/// Watches one local background job's stdin pipe for a waiting reader.
struct LocalStdinWatch {
    probe: LocalStdinProbe,
    feed: FeedCounter,
    detector: EpisodeDetector,
    alerts: StdinAlerts,
}

impl LocalStdinWatch {
    /// Probes the pipe every [`STDIN_WATCH_INTERVAL`] and raises one alert per
    /// blocking episode, for as long as the future is polled.
    async fn run(mut self) -> std::convert::Infallible {
        loop {
            async_io::Timer::after(STDIN_WATCH_INTERVAL).await;
            let Self {
                probe,
                feed,
                mut detector,
                alerts,
            } = self;
            let fed = feed.count();
            let (probe, observed) = blocking::unblock(move || {
                let observed = probe.probe();
                (probe, observed)
            })
            .await;
            match observed {
                Ok(observed) => {
                    if detector.observe(fed, observed) {
                        alerts.raise().await;
                    }
                }
                Err(error) => {
                    // Detection cannot run: surface it once, then park — the
                    // job's exit still ends the race in
                    // `wait_for_local_process_exit`.
                    alerts.raise_failure(error.to_string()).await;
                    std::future::pending::<()>().await;
                }
            }
            self = Self {
                probe,
                feed,
                detector,
                alerts,
            };
        }
    }
}

async fn collect_local_process_output<E: Executor + Clone + 'static>(
    mut child: LocalChild,
    executor: E,
    job_registry: &JobRegistry,
    pid: u32,
    job: LocalJob,
    missing_stdout_message: &'static str,
    missing_stderr_message: &'static str,
) -> Result<std::process::Output, TerminalError> {
    let LocalJob {
        tree,
        lifetime,
        stdin_alerts,
    } = job;
    let mut stdin_watch = None;
    if let Some(stdin) = child.take_stdin() {
        let feed = FeedCounter::default();
        if let Some(alerts) = stdin_alerts {
            let probe = LocalStdinProbe::new(pid, &stdin)
                .map_err(|error| TerminalError::Execution(format!("stdin probe: {error}")))?;
            stdin_watch = Some(LocalStdinWatch {
                probe,
                feed: feed.clone(),
                detector: EpisodeDetector::default(),
                alerts,
            });
        }
        let input_tx = spawn_terminal_stdin_writer(stdin, feed);
        job_registry.attach_terminal_input(pid, input_tx).await;
    }

    let stdout = child
        .take_stdout()
        .ok_or_else(|| TerminalError::Execution(missing_stdout_message.into()))?;
    let stderr = child
        .take_stderr()
        .ok_or_else(|| TerminalError::Execution(missing_stderr_message.into()))?;

    let (chunk_tx, chunk_rx) = async_channel::unbounded();
    spawn_terminal_reader(stdout, chunk_tx.clone(), false);
    spawn_terminal_reader(stderr, chunk_tx.clone(), true);
    drop(chunk_tx);
    executor
        .spawn(drain_terminal_chunks(job_registry.clone(), pid, chunk_rx))
        .detach();

    // The root stays unreaped until its tree is gone, so its pid and process
    // group stay reserved while the job's descendants are tracked by them.
    let exited = match wait_for_local_process_exit(&mut child, stdin_watch).await {
        Ok(exited) => exited,
        Err(error) => {
            tree.finish().await;
            job_registry.close_stdout(pid).await;
            job_registry.close_stderr(pid).await;
            return Err(error);
        }
    };
    let descendants = end_descendants(&tree, &lifetime).await;
    // The task ends first: afterwards the root's pid may belong to anyone.
    tree.finish().await;
    let (status, report) = match exited {
        Some(status) => (Ok(status), None),
        None => match child.wait_reported().await {
            Ok((status, report)) => (Ok(status), report),
            Err(error) => (Err(TerminalError::Execution(error.to_string())), None),
        },
    };
    let _ = &report;
    #[cfg(target_os = "linux")]
    if let Some(report) = report {
        let killed: Vec<JobProcess> = report
            .killed
            .into_iter()
            .map(|process| JobProcess {
                pid: process.pid,
                name: process.name,
            })
            .collect();
        if !killed.is_empty() {
            info!(
                killed = killed.len(),
                "the supervisor killed the finished command's descendants"
            );
            if let JobLifetime::Foreground { alerts } = &lifetime {
                let _ = alerts
                    .send(JobAlert::DescendantsKilled(DescendantsKilled::new(killed)))
                    .await;
            }
        }
    }
    let status = match (descendants, status) {
        (Ok(()), Ok(status)) => status,
        (Err(error), _) | (Ok(()), Err(error)) => {
            job_registry.close_stdout(pid).await;
            job_registry.close_stderr(pid).await;
            job_registry.fail(pid, &error.to_string(), None).await;
            return Err(error);
        }
    };
    wait_for_terminal_stream_close(job_registry, pid).await;
    let (stdout, stderr) = job_registry.terminal_output(pid).await.ok_or_else(|| {
        TerminalError::Execution(format!("missing terminal output for pid {pid}"))
    })?;
    let output = std::process::Output {
        status,
        stdout,
        stderr,
    };

    Ok(output)
}

/// A local job's process tree and how long its descendants may live.
struct LocalJob {
    tree: JobTree,
    lifetime: JobLifetime,
    stdin_alerts: Option<StdinAlerts>,
}

/// The teardown budget a job's supervisor gives its kills: the time to
/// freeze the tree, deliver `SIGKILL` and see every killed process exit.
/// Generous relative to the few milliseconds a `SIGKILL` exit takes, since a
/// too-short budget reports survivors that are merely still exiting.
#[cfg(target_os = "linux")]
const SUPERVISED_REAP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

/// A spawned local job: the plain `heel` child on platforms without a
/// supervisor, or a `heel supervise`-supervised one on Linux, where the
/// supervisor is the command's parent and owns its whole tree.
enum LocalChild {
    /// Everywhere but Linux: the sandboxed process itself.
    #[cfg_attr(target_os = "linux", allow(dead_code))]
    Plain(heel::Child),
    /// Linux, foreground lifetime: `wait` yields the command's status and
    /// the teardown's report of what it killed.
    #[cfg(target_os = "linux")]
    Foreground(heel::supervisor::SupervisedChild<heel::supervisor::Foreground>),
    /// Linux, background lifetime: `wait` ends only once the last descendant
    /// of the command has exited.
    #[cfg(target_os = "linux")]
    Background(heel::supervisor::SupervisedChild<heel::supervisor::Background>),
}

impl LocalChild {
    /// The spawned process's id: the supervisor's on Linux.
    fn id(&self) -> u32 {
        match self {
            Self::Plain(child) => child.id(),
            #[cfg(target_os = "linux")]
            Self::Foreground(child) => child.id(),
            #[cfg(target_os = "linux")]
            Self::Background(child) => child.id(),
        }
    }

    fn take_stdin(&mut self) -> Option<std::fs::File> {
        match self {
            Self::Plain(child) => child.take_stdin(),
            #[cfg(target_os = "linux")]
            Self::Foreground(child) => child.take_stdin(),
            #[cfg(target_os = "linux")]
            Self::Background(child) => child.take_stdin(),
        }
    }

    fn take_stdout(&mut self) -> Option<std::fs::File> {
        match self {
            Self::Plain(child) => child.take_stdout(),
            #[cfg(target_os = "linux")]
            Self::Foreground(child) => child.take_stdout(),
            #[cfg(target_os = "linux")]
            Self::Background(child) => child.take_stdout(),
        }
    }

    fn take_stderr(&mut self) -> Option<std::fs::File> {
        match self {
            Self::Plain(child) => child.take_stderr(),
            #[cfg(target_os = "linux")]
            Self::Foreground(child) => child.take_stderr(),
            #[cfg(target_os = "linux")]
            Self::Background(child) => child.take_stderr(),
        }
    }

    /// A handle to the supervisor owning the job's tree.
    #[cfg(target_os = "linux")]
    fn tree_control(&self) -> TreeControl {
        match self {
            Self::Foreground(child) => child.tree_control(),
            #[cfg(target_os = "linux")]
            Self::Background(child) => child.tree_control(),
            Self::Plain(_) => unreachable!("a supervised spawn returns no plain child"),
        }
    }

    /// Waits the job out, yielding the command's status and, for a
    /// supervised foreground job, the supervisor's teardown report: what it
    /// found still running under the command and killed.
    async fn wait_reported(
        &mut self,
    ) -> Result<(std::process::ExitStatus, Option<TreeReport>), heel::Error> {
        match self {
            Self::Plain(child) => Ok((child.wait().await?, None)),
            #[cfg(target_os = "linux")]
            Self::Foreground(child) => {
                let exit = child.wait().await?;
                Ok((exit.status, Some(exit.report)))
            }
            #[cfg(target_os = "linux")]
            Self::Background(child) => Ok((child.wait().await?, None)),
        }
    }
}

/// Spawns a local job's command and hands its tree to whoever owns it.
///
/// On Linux the sandbox was built with `supervised_spawn(true)`, so the
/// command runs under `heel supervise`: a child subreaper inside the sandbox
/// that owns the whole tree however its members change session, group or
/// environment. Everywhere else the root's process group is watched through
/// the process table, keyed by the job's marker.
#[allow(clippy::too_many_arguments)]
async fn spawn_local_command<E: Executor + Clone + 'static>(
    command: heel::Command<'_>,
    args: &[String],
    environment: Vec<(String, String)>,
    stdin_alerts: Option<&StdinAlerts>,
    lifetime: &JobLifetime,
    job_registry: &JobRegistry,
    executor: &E,
    marker: &JobMarker,
) -> Result<(LocalChild, JobTree), TerminalError> {
    let command = command
        .args(args)
        .envs(environment)
        .stdin(local_stdin_config(stdin_alerts))
        .stdout(StdioConfig::Piped)
        .stderr(StdioConfig::Piped);

    #[cfg(target_os = "linux")]
    {
        let _ = (job_registry, executor, marker);
        let child = match lifetime {
            JobLifetime::Foreground { .. } => LocalChild::Foreground(
                command
                    .spawn_supervised(heel::supervisor::Foreground {
                        reap_timeout: SUPERVISED_REAP_TIMEOUT,
                    })
                    .await
                    .map_err(|error| TerminalError::Execution(error.to_string()))?,
            ),
            JobLifetime::Background => LocalChild::Background(
                command
                    .spawn_supervised(heel::supervisor::Background {
                        reap_timeout: SUPERVISED_REAP_TIMEOUT,
                    })
                    .await
                    .map_err(|error| TerminalError::Execution(error.to_string()))?,
            ),
        };
        let tree = JobTree::supervised(child.tree_control());
        Ok((child, tree))
    }

    #[cfg(not(target_os = "linux"))]
    {
        let _ = lifetime;
        let child = command
            .spawn()
            .await
            .map_err(|error| TerminalError::Execution(error.to_string()))?;
        let pid = child.id();
        let tree = job_registry.start_process_tree(executor, pid, marker);
        Ok((LocalChild::Plain(child), tree))
    }
}

/// Applies the rule that a job's descendants live exactly as long as the job,
/// after its top-level shell exited.
///
/// A foreground command's surviving descendants are killed and reported in one
/// [`JobAlert::DescendantsKilled`]; a background job stays running until every
/// descendant has exited, which its timeout, `terminal_kill` and the registry's
/// kills end by killing the tree.
async fn end_descendants(tree: &JobTree, lifetime: &JobLifetime) -> Result<(), TerminalError> {
    match lifetime {
        JobLifetime::Foreground { alerts } => {
            let killed = tree
                .kill_descendants()
                .await
                .map_err(|error| TerminalError::Execution(error.to_string()))?;
            if !killed.is_empty() {
                info!(
                    killed = killed.len(),
                    "killed descendants of a finished foreground command"
                );
                let _ = alerts
                    .send(JobAlert::DescendantsKilled(DescendantsKilled::new(killed)))
                    .await;
            }
            Ok(())
        }
        JobLifetime::Background => tree
            .wait_descendants_exit()
            .await
            .map_err(|error| TerminalError::Execution(error.to_string())),
    }
}

/// Waits for the child to exit, raising stdin alerts meanwhile.
///
/// On Unix the child is only observed to have exited and stays unreaped (the
/// answer is `None`); the caller waits for it once its tree is gone. Windows
/// has no such state and answers the exit status.
#[cfg_attr(unix, allow(clippy::needless_pass_by_ref_mut))]
async fn wait_for_local_process_exit(
    child: &mut LocalChild,
    stdin_watch: Option<LocalStdinWatch>,
) -> Result<Option<std::process::ExitStatus>, TerminalError> {
    #[cfg(unix)]
    let exit = async {
        crate::process_tree::wait_for_exit(child.id())
            .await
            .map(|()| None)
            .map_err(|error| TerminalError::Execution(error.to_string()))
    };
    #[cfg(not(unix))]
    let exit = async {
        child
            .wait_reported()
            .await
            .map(|(status, _)| Some(status))
            .map_err(|error| TerminalError::Execution(error.to_string()))
    };
    let Some(stdin_watch) = stdin_watch else {
        return exit.await;
    };
    futures_lite::future::or(exit, async { match stdin_watch.run().await {} }).await
}

/// A container command's full script. A main terminal's git shim and
/// worktree map travel inside it: the container's tools mount is
/// read-only, so the command writes the shim where its own `PATH` can
/// put it first.
fn container_exec_script(
    registry: &ToolRegistry,
    container_runtime: &ContainerShellRuntime,
    prepared_tools: &PreparedTools<ContainerPath>,
    carry: Option<&ContainerCarry>,
    script: &str,
) -> Result<String, TerminalError> {
    let preamble = container_git_preamble(registry, container_runtime.workspace_mount())?;
    let script = if preamble.is_empty() {
        script.to_string()
    } else {
        format!("{preamble}{script}")
    };
    let script = prepared_tools.wrap_script(&script)?;
    let script = match carry.and_then(|carry| carry.report.as_ref()) {
        Some(report) => carry_cwd_script(&script, report.as_str())?,
        None => script,
    };
    Ok(prepared_tools.shell_command(&script)?)
}

#[allow(clippy::too_many_lines)]
async fn execute_container_background<E: Executor + Clone + 'static>(
    context: ContainerBackgroundExecution<'_, E>,
) -> Result<(u32, std::process::Output), TerminalError> {
    let container_runtime = context.container_runtime;
    let exec = container_runtime.exec();

    // Use lower 32 bits of a UUID as a synthetic PID for job tracking.
    let pid = u32::from_le_bytes(
        uuid::Uuid::new_v4().as_u128().to_le_bytes()[..4]
            .try_into()
            .expect("uuid byte slice has four bytes"),
    );
    let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
    let (input_tx, input_rx) = async_channel::unbounded::<Vec<u8>>();
    context
        .job_registry
        .register_at(
            crate::JobPlace::Container,
            pid,
            context.task_id,
            context.execution_id,
            context.script,
            context.language,
            context.mode,
        )
        .await;
    let script = container_exec_script(
        context.registry,
        context.container_runtime,
        context.prepared_tools,
        context.carry,
        &launch_script(context.language, context.script, context.task_id)?,
    )?;
    let script = inject_env_exports(script, context.env_source.as_ref())?;
    // Exported ahead of the embedder's variables, which win as they do for
    // a local command.
    #[cfg(all(unix, feature = "jobserver"))]
    let script = match &context.job_fifo {
        Some(fifo) => {
            let environment: Arc<dyn TerminalEnvSource> = Arc::new(fifo.environment());
            inject_env_exports(script, Some(&environment))?
        }
        None => script,
    };
    #[cfg(all(unix, feature = "jobserver"))]
    let confinement = job_confinement(
        context.confinement,
        context
            .job_fifo
            .as_ref()
            .map(crate::container_jobserver::ContainerJobFifo::path),
    );
    #[cfg(not(all(unix, feature = "jobserver")))]
    let confinement = context.confinement.cloned();
    let script = mark_container_job(script, context.task_id)?;
    // A foreground command gets no input channel: the dropped sender is the
    // EOF its stdin reads. StdinAlerts may ride along either way; they are
    // the background job's blocked-reader wiring.
    let exec_lifetime = if let JobLifetime::Foreground { .. } = context.lifetime {
        drop(input_tx);
        ExecLifetime::Foreground
    } else {
        context
            .job_registry
            .attach_terminal_input(pid, input_tx)
            .await;
        let (signal_tx, signal_rx) = async_channel::unbounded::<StdinWatchSignal>();
        if let Some(alerts) = context.stdin_alerts {
            context
                .executor
                .clone()
                .spawn(async move {
                    while let Ok(signal) = signal_rx.recv().await {
                        match signal {
                            StdinWatchSignal::Blocked => alerts.raise().await,
                            StdinWatchSignal::Failed(error) => {
                                alerts.raise_failure(error).await;
                            }
                        }
                    }
                })
                .detach();
        }
        ExecLifetime::Background {
            stdin_blocked: signal_tx,
        }
    };
    context.job_registry.attach_kill_switch(pid, kill_tx).await;
    context.background_startup.report_ready().await;

    let ipc_bridge = if context.ipc_commands.is_empty() {
        None
    } else {
        Some(start_container_ipc_bridge(
            context.executor,
            Arc::clone(context.registry),
            container_runtime.workspace_mount().cloned(),
            container_runtime.ipc_route().bind(),
        )?)
    };
    let working_dir = context
        .carry
        .map_or(CONTAINER_EXEC_WORKING_DIR, |carry| carry.start.as_str());
    let wrapped_script = wrap_container_script(
        &script,
        context.ipc_commands,
        ipc_bridge.as_ref().map(|bridge| ContainerIpcEndpoint {
            host: container_runtime.ipc_route().host(),
            port: bridge.port(),
        }),
        context.priority,
        context.prepared_tools.bin_dir(),
        working_dir,
        confinement.as_ref(),
    )?;

    let execution = exec
        .exec_boxed(
            container_runtime.container_id(),
            &wrapped_script,
            working_dir,
            kill_rx,
            input_rx,
            exec_lifetime,
        )
        .await;

    if let Some(bridge) = ipc_bridge {
        bridge.stop().await;
    }
    // The exec has ended, killed or not: the relay stops feeding the fifo and
    // returns its tokens once the job's last process holding it is gone.
    #[cfg(all(unix, feature = "jobserver"))]
    drop(context.job_fifo);

    record_container_exec_outcome(context.job_registry, pid, &context.lifetime, execution).await
}

/// Records a finished container exec in the job's streams and folds it into
/// the call's result.
async fn record_container_exec_outcome(
    job_registry: &JobRegistry,
    pid: u32,
    lifetime: &JobLifetime,
    execution: Result<ContainerExecOutcome, String>,
) -> Result<(u32, std::process::Output), TerminalError> {
    match execution {
        Ok(ContainerExecOutcome::Completed { output, killed }) => {
            if let JobLifetime::Foreground { alerts } = lifetime
                && !killed.is_empty()
            {
                info!(
                    killed = killed.len(),
                    "killed processes of a finished foreground container command"
                );
                let _ = alerts
                    .send(JobAlert::DescendantsKilled(DescendantsKilled::new(killed)))
                    .await;
            }
            if !output.stdout.is_empty() {
                job_registry.append_stdout(pid, output.stdout.clone()).await;
            }
            if !output.stderr.is_empty() {
                job_registry.append_stderr(pid, output.stderr.clone()).await;
            }
            job_registry.close_stdout(pid).await;
            job_registry.close_stderr(pid).await;
            Ok((pid, output))
        }
        Ok(ContainerExecOutcome::Killed) => {
            job_registry.close_stdout(pid).await;
            job_registry.close_stderr(pid).await;
            Err(TerminalError::Execution("container job killed".to_string()))
        }
        Err(err) => {
            job_registry.fail(pid, &err, None).await;
            job_registry.close_stdout(pid).await;
            job_registry.close_stderr(pid).await;
            Err(TerminalError::Execution(err))
        }
    }
}

#[derive(Template)]
#[template(path = "ssh_tool_execution.sh", escape = "none")]
struct SshToolExecutionTemplate<'a> {
    binary: Cow<'a, str>,
    tools_dir: Cow<'a, str>,
    /// Read, write and execute access to the shared `uv` directory, quoted.
    uv_grant: Option<String>,
    program: Cow<'a, str>,
    arguments: String,
}

async fn execute_ssh_background(
    context: SshBackgroundExecution<'_>,
) -> Result<(u32, std::process::Output), TerminalError> {
    let target = context.ssh_target;
    let remote_cmd = match (context.ssh_runtime, context.mode) {
        (SshRuntimeProfile::Heel { binary }, TerminalMode::Sandboxed) => {
            let script = context.prepared_tools.wrap_script(&launch_script(
                context.language,
                context.script,
                context.task_id,
            )?)?;
            let (program, args) = shell_launch(&context.prepared_tools.shell()?, &script);
            let directory = context.prepared_tools.script_bin_dir()?;
            let uv_grant = context
                .prepared_tools
                .uv_dir()
                .map(|dir| {
                    let dir = dir
                        .to_str()
                        .ok_or_else(|| ToolRuntimeError::InvalidCache(dir.clone()))?;
                    Ok::<_, ToolRuntimeError>(
                        shell_words::quote(&format!("{dir}=rwx")).into_owned(),
                    )
                })
                .transpose()?;
            SshToolExecutionTemplate {
                binary: shell_words::quote(binary),
                tools_dir: shell_words::quote(directory),
                uv_grant,
                program: shell_words::quote(&program),
                arguments: shell_words::join(&args),
            }
            .render()
            .map_err(ToolRuntimeError::from)?
        }
        (SshRuntimeProfile::Heel { .. }, TerminalMode::Unsafe) => {
            return Err(TerminalError::InvalidTarget(
                "unsafe mode is not supported for ssh backend".into(),
            ));
        }
    };

    let mut command = std::process::Command::new("ssh");
    command
        .arg("-o")
        .arg("BatchMode=yes")
        .arg("-o")
        .arg("ConnectTimeout=10")
        .arg(target)
        .arg(remote_cmd)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(unix)]
    std::os::unix::process::CommandExt::process_group(&mut command, 0);

    let child = async_process::Command::from(command)
        .spawn()
        .map_err(|e| TerminalError::Execution(e.to_string()))?;

    let pid = child.id();
    // The local `ssh` process stands for a job that runs on the remote host,
    // whose memory is never judged.
    context
        .job_registry
        .register_at(
            crate::JobPlace::Remote,
            pid,
            context.task_id,
            context.execution_id,
            context.script,
            context.language,
            context.mode,
        )
        .await;
    context.background_startup.report_ready().await;

    match child.output().await {
        Ok(output) => {
            if !output.stdout.is_empty() {
                context
                    .job_registry
                    .append_stdout(pid, output.stdout.clone())
                    .await;
            }
            if !output.stderr.is_empty() {
                context
                    .job_registry
                    .append_stderr(pid, output.stderr.clone())
                    .await;
            }
            context.job_registry.close_stdout(pid).await;
            context.job_registry.close_stderr(pid).await;
            Ok((pid, output))
        }
        Err(err) => {
            context.job_registry.fail(pid, &err.to_string(), None).await;
            context.job_registry.close_stdout(pid).await;
            context.job_registry.close_stderr(pid).await;
            Err(TerminalError::Execution(err.to_string()))
        }
    }
}

/// Prepends a source's env pairs to `script` as `export` statements, for
/// backends (container exec) whose channel accepts only a script — never an
/// env channel. Names are validated so a provider can't inject shell syntax.
fn inject_env_exports(
    script: String,
    env_source: Option<&Arc<dyn TerminalEnvSource>>,
) -> Result<String, TerminalError> {
    let Some(source) = env_source else {
        return Ok(script);
    };
    let mut rendered = String::new();
    for (name, value) in source.env() {
        if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
            || name.chars().next().is_some_and(|c| c.is_ascii_digit())
        {
            return Err(TerminalError::Execution(format!(
                "invalid environment variable name for container exec: {name}"
            )));
        }
        rendered.push_str("export ");
        rendered.push_str(&name);
        rendered.push('=');
        rendered.push_str(&shell_escape(&value));
        rendered.push('\n');
    }
    rendered.push_str(&script);
    Ok(rendered)
}

/// Marks every process of a container job with its task ID, the marker the
/// container's memory reader finds the job's processes by: each process the
/// job starts inherits it.
fn mark_container_job(script: String, task_id: &str) -> Result<String, TerminalError> {
    let marker: Arc<dyn TerminalEnvSource> = Arc::new(vec![(
        crate::memory::JOB_MARKER_ENV.to_string(),
        task_id.to_string(),
    )]);
    inject_env_exports(script, Some(&marker))
}

fn shell_escape(value: &str) -> String {
    let escaped = value.replace('\'', "'\"'\"'");
    let mut output = String::with_capacity(escaped.len() + 2);
    output.push('\'');
    output.push_str(&escaped);
    output.push('\'');
    output
}

/// Builds a local command's grants and environment: the session policy
/// (the one [`crate::SessionSandboxPolicy`] exposes to hosts, with the
/// command's jobserver fifo), the git shim, committed grant vars, then the
/// embedder's extra envs (which override).
async fn local_launch_policy<E: Executor>(
    context: &LocalBackgroundExecution<'_, E>,
) -> Result<(Vec<Grant>, Vec<(String, String)>, heel::WriteDenylist), TerminalError> {
    write_git_shim(context.prepared_tools).await?;
    let policy = crate::SessionSandboxPolicy::new(
        context.working_dir,
        context.writable_paths,
        context.readable_paths,
        context.git_dir,
        context.prepared_tools,
    )
    .await?;
    #[cfg(all(unix, feature = "jobserver"))]
    let policy = match &context.job_fifo {
        Some(fifo) => policy.with_job_fifo(fifo)?,
        None => policy,
    };
    let write_denylist = policy.write_denylist().clone();
    let (grants, mut env) = policy.into_parts();
    committed_git_environment(context.registry, &mut env, |path| {
        Ok(path.display().to_string())
    })?;
    env.extend(context.env_source.iter().flat_map(|s| s.env()));
    Ok((grants, env, write_denylist))
}

pub async fn prepare_session_runtime_environment(
    working_dir: &Path,
    tools: &PreparedTools<PathBuf>,
) -> Result<Vec<(String, String)>, TerminalError> {
    let session_tmp = working_dir.join("tmp");
    let session_cache = working_dir.join(".cache");
    let bun_cache = session_cache.join("bun");
    let session_config = working_dir.join(".config");
    let playwright_cache = session_cache.join("ms-playwright");
    let python_path = working_dir.join("skills").join("python");

    for directory in [
        &session_tmp,
        &session_cache,
        &bun_cache,
        &session_config,
        &playwright_cache,
    ] {
        async_fs::create_dir_all(directory).await?;
    }

    let tmp = path_environment_value("TMPDIR", &session_tmp)?;
    let cache = path_environment_value("XDG_CACHE_HOME", &session_cache)?;
    let bun = path_environment_value("BUN_INSTALL_CACHE_DIR", &bun_cache)?;
    let config = path_environment_value("XDG_CONFIG_HOME", &session_config)?;
    let playwright = path_environment_value("PLAYWRIGHT_BROWSERS_PATH", &playwright_cache)?;
    let home = path_environment_value("HOME", working_dir)?;
    let python = std::env::var_os("PYTHONPATH").map_or_else(
        || Ok::<_, TerminalError>(python_path.clone().into_os_string()),
        |existing| {
            std::env::join_paths(
                std::iter::once(python_path.clone()).chain(std::env::split_paths(&existing)),
            )
            .map_err(|error| {
                TerminalError::Execution(format!("failed to construct session PYTHONPATH: {error}"))
            })
        },
    )?;
    let python = python.into_string().map_err(|value| {
        TerminalError::Execution(format!(
            "session PYTHONPATH is not valid UTF-8: {}",
            value.to_string_lossy()
        ))
    })?;

    // The managed tools directory leads; the host PATH follows so host
    // toolchains (cargo, rustup, anything else) stay reachable. The heel
    // sandbox path is only a fallback for a host without a PATH.
    let host_path = std::env::var_os("PATH")
        .filter(|path| !path.is_empty())
        .unwrap_or_else(|| heel::default_sandbox_path().into());
    let path = tools
        .prepend_path(Some(host_path.as_os_str()))?
        .into_string()
        .map_err(|_| ToolRuntimeError::InvalidCache(tools.bin_dir().clone()))?;
    // Point cargo and rustup at the same host homes the grants cover, so
    // the remapped HOME does not strand them under the working dir.
    let mut env = vec![
        ("PATH".to_string(), path),
        ("TMPDIR".to_string(), tmp.clone()),
        ("TMP".to_string(), tmp.clone()),
        ("TEMP".to_string(), tmp),
        ("HOME".to_string(), home),
        ("XDG_CACHE_HOME".to_string(), cache),
        ("XDG_CONFIG_HOME".to_string(), config),
        ("BUN_INSTALL_CACHE_DIR".to_string(), bun),
        ("PLAYWRIGHT_BROWSERS_PATH".to_string(), playwright),
        ("PYTHONPATH".to_string(), python),
    ];
    // `uv` keeps its cache and the Pythons it installs for projects in one
    // directory shared by every session, not under the remapped HOME.
    if let Some(uv) = tools.uv_environment() {
        env.push((
            "UV_CACHE_DIR".to_string(),
            path_environment_value("UV_CACHE_DIR", &uv.cache)?,
        ));
        env.push((
            "UV_PYTHON_INSTALL_DIR".to_string(),
            path_environment_value("UV_PYTHON_INSTALL_DIR", &uv.python_installs)?,
        ));
        env.push((
            "UV_PYTHON_PREFERENCE".to_string(),
            crate::tool_runtime::UV_PYTHON_PREFERENCE.to_string(),
        ));
    }
    for (name, home) in host_toolchain_homes() {
        env.push((name.to_string(), path_environment_value(name, &home)?));
    }
    Ok(env)
}

fn path_environment_value(name: &str, path: &Path) -> Result<String, TerminalError> {
    path.to_str().map(str::to_string).ok_or_else(|| {
        TerminalError::Execution(format!(
            "session environment path for {name} is not valid UTF-8: {}",
            path.display()
        ))
    })
}

#[derive(Template)]
#[template(path = "container_ipc_wrapper.sh", escape = "none")]
struct ContainerIpcWrapperTemplate<'a> {
    escaped_commands: &'a str,
    ipc_host: &'a str,
    ipc_port: u16,
    script: &'a str,
}

#[derive(Clone, Copy)]
struct ContainerIpcEndpoint<'a> {
    host: &'a str,
    port: u16,
}

/// Working directory container executions run their scripts in.
pub const CONTAINER_EXEC_WORKING_DIR: &str = "/workspace";

/// The sandbox a subagent's command runs in inside a container, as container
/// paths: the main agent's commands run unconfined because the container is its
/// boundary, but a subagent's keep the per-command sandbox they have on the
/// host — write access to its own space and its granted paths only.
#[derive(Clone, Debug, PartialEq, Eq)]
struct ContainerConfinement {
    working_dir: ContainerPath,
    writable: Vec<ContainerPath>,
}

/// A container command's sandbox: a subagent's confinement plus write access
/// to the command's jobserver fifo, which its build tools write tokens back
/// to. An unconfined command already reaches the fifo.
#[cfg(all(unix, feature = "jobserver"))]
fn job_confinement(
    confinement: Option<&ContainerConfinement>,
    job_fifo: Option<&ContainerPath>,
) -> Option<ContainerConfinement> {
    let mut confinement = confinement?.clone();
    confinement.writable.extend(job_fifo.cloned());
    Some(confinement)
}

/// Where a container command runs: the mounted tools, the exec's working
/// directory and, for a subagent, its sandbox.
#[derive(Clone, Copy)]
struct ContainerRunScope<'a> {
    tools_dir: &'a ContainerPath,
    working_dir: &'a str,
    confinement: Option<&'a ContainerConfinement>,
}

#[derive(Template)]
#[template(path = "container_heel_run.sh", escape = "none")]
struct ContainerHeelRunTemplate<'a> {
    heel_bin: &'a str,
    resolve_heel: bool,
    escaped_working_dir: &'a str,
    escaped_tools_dir: &'a str,
    /// Set for a subagent: the isolation level and grants replacing the
    /// container-wide permissive one.
    escaped_grants: Option<Vec<String>>,
    escaped_ipc_endpoint: Option<String>,
    nice: Option<u8>,
    io_priority: Option<&'static str>,
    escaped_script: &'a str,
}

/// Renders the command that runs `script` inside the container at the
/// configured scheduling priority.
///
/// The priority goes through heel's own sandbox configuration: the container
/// image's `heel` binary runs the script under `heel run`, so the settings are
/// the same flags the CLI takes everywhere — `nice`/`ionice` are never
/// reimplemented here. `heel_bin` is the shell expression that resolves the
/// image's `heel` (`$MAY_IPC_BIN` once the IPC wrapper has resolved it, or
/// `$MAY_HEEL_BIN` the template resolves itself when `resolve_heel` is set)
/// and `working_dir` is the exact directory the execution runs in, matching
/// the directory the container exec applies.
///
/// The container is already the isolation boundary, so the invocation asks for
/// `permissive` isolation: the script keeps the filesystem permissions it had
/// as the container caller. The ruleset still exec-denies everything outside
/// the system directories, so `--executable` grants the mounted tools
/// directory read-execute — without it every prepared tool fails with
/// Permission denied. `PATH` and `HOME` are forwarded so the generated
/// `heel ipc` shims still resolve and the script sees its usual environment.
/// Networking keeps heel's deny-all default, and no rule is bent to pass the
/// IPC transport: `--ipc-endpoint` has heel relay the sandbox's local IPC
/// socket to the bridge endpoint from outside the sandbox, so the sandboxed
/// `heel ipc` never needs TCP access of its own.
fn heel_run_container_command(
    script: &str,
    priority: ProcessPriority,
    heel_bin: &str,
    resolve_heel: bool,
    ipc_endpoint: Option<ContainerIpcEndpoint<'_>>,
    scope: ContainerRunScope<'_>,
) -> Result<String, TerminalError> {
    let ContainerRunScope {
        tools_dir,
        working_dir,
        confinement,
    } = scope;
    let nice = match priority.cpu() {
        CpuPriority::Nice(level) => Some(level.get()),
        CpuPriority::Normal => None,
    };
    let io_priority = match priority.io() {
        IoPriority::Utility => Some("utility"),
        IoPriority::Background => Some("background"),
        IoPriority::Normal => None,
    };
    // A subagent runs in its own space with heel's default isolation (that space
    // writable, the rest readable) plus its granted paths.
    let working_dir =
        confinement.map_or(working_dir, |confinement| confinement.working_dir.as_str());
    let escaped_grants = confinement.map(|confinement| {
        confinement
            .writable
            .iter()
            .map(|path| shell_escape(&format!("{path}=rw")))
            .collect()
    });
    let escaped_working_dir = shell_escape(working_dir);
    let escaped_tools_dir = shell_escape(tools_dir.as_str());
    let escaped_ipc_endpoint = ipc_endpoint
        .map(|endpoint| format!("tcp://{}:{}", endpoint.host, endpoint.port))
        .map(|endpoint| shell_escape(&endpoint));
    let escaped_script = shell_escape(script);
    ContainerHeelRunTemplate {
        heel_bin,
        resolve_heel,
        escaped_working_dir: &escaped_working_dir,
        escaped_tools_dir: &escaped_tools_dir,
        escaped_grants,
        escaped_ipc_endpoint,
        nice,
        io_priority,
        escaped_script: &escaped_script,
    }
    .render()
    .map_err(|error| {
        TerminalError::Execution(format!("failed to render container heel command: {error}"))
    })
}

fn prioritized_container_script(
    script: &str,
    priority: ProcessPriority,
    tools_dir: &ContainerPath,
    working_dir: &str,
    confinement: Option<&ContainerConfinement>,
) -> Result<String, TerminalError> {
    if priority.is_normal() && confinement.is_none() {
        return Ok(script.to_string());
    }
    // Outside the IPC wrapper no `heel` binary has been resolved yet; the
    // template resolves it the same way the wrapper does and fails when the
    // image lacks one.
    heel_run_container_command(
        script,
        priority,
        "\"$MAY_HEEL_BIN\"",
        true,
        None,
        ContainerRunScope {
            tools_dir,
            working_dir,
            confinement,
        },
    )
}

fn wrap_container_script(
    script: &str,
    ipc_commands: &[String],
    ipc_endpoint: Option<ContainerIpcEndpoint<'_>>,
    priority: ProcessPriority,
    tools_dir: &ContainerPath,
    working_dir: &str,
    confinement: Option<&ContainerConfinement>,
) -> Result<String, TerminalError> {
    if ipc_commands.is_empty() {
        return prioritized_container_script(script, priority, tools_dir, working_dir, confinement);
    }

    let endpoint = ipc_endpoint.ok_or_else(|| {
        TerminalError::Execution(
            "missing container IPC endpoint for wrapped script execution".to_string(),
        )
    })?;

    for name in ipc_commands {
        if !name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
        {
            return Err(TerminalError::Execution(format!(
                "invalid ipc command name for container wrapper: {name}"
            )));
        }
    }

    let escaped_commands = ipc_commands
        .iter()
        .map(|name| shell_escape(name))
        .collect::<Vec<_>>()
        .join(" ");
    let script = if priority.is_normal() && confinement.is_none() {
        script.to_string()
    } else {
        // The generated shims are written under the shared temp directory,
        // which stays execute-denied even at `permissive` isolation: the
        // render below grants them read-and-execute so the sandboxed `PATH`
        // resolves them — the wrapper writes them before `heel run`, so the
        // sandbox itself never writes the directory.
        heel_run_container_command(
            script,
            priority,
            "\"$MAY_IPC_BIN\"",
            false,
            Some(endpoint),
            ContainerRunScope {
                tools_dir,
                working_dir,
                confinement,
            },
        )?
    };
    ContainerIpcWrapperTemplate {
        escaped_commands: &escaped_commands,
        ipc_host: endpoint.host,
        ipc_port: endpoint.port,
        script: &script,
    }
    .render()
    .map_err(|error| {
        TerminalError::Execution(format!("failed to render container IPC wrapper: {error}"))
    })
}

struct ContainerIpcBridge {
    shutdown_tx: Sender<()>,
    port: u16,
}

impl ContainerIpcBridge {
    const fn port(&self) -> u16 {
        self.port
    }

    async fn stop(self) {
        tracing::debug!("stopping container IPC bridge");
        let _ = self.shutdown_tx.send(()).await;
    }
}

fn start_container_ipc_bridge<E: Executor + Clone + 'static>(
    executor: E,
    registry: Arc<ToolRegistry>,
    workspace: Option<MountRoot>,
    bind: BridgeAddress,
) -> Result<ContainerIpcBridge, TerminalError> {
    // The bridge executes host IPC commands for whoever connects, so it binds
    // only the address the container route names — never a wildcard.
    let listener = StdTcpListener::bind(SocketAddr::new(bind.ip(), 0)).map_err(|e| {
        TerminalError::Execution(format!("failed to bind container IPC tcp port: {e}"))
    })?;
    let local_addr = listener.local_addr().map_err(|e| {
        TerminalError::Execution(format!("failed to resolve container IPC tcp endpoint: {e}"))
    })?;
    tracing::debug!(
        bind = %local_addr,
        "starting container IPC bridge"
    );
    listener.set_nonblocking(true).map_err(|e| {
        TerminalError::Execution(format!(
            "failed to set IPC tcp listener nonblocking mode: {e}"
        ))
    })?;
    let listener = Async::new(listener).map_err(|e| {
        TerminalError::Execution(format!(
            "failed to register IPC tcp listener with async reactor: {e}"
        ))
    })?;

    let (shutdown_tx, shutdown_rx) = async_channel::bounded::<()>(1);
    let bridge_executor = executor.clone();
    executor
        .spawn(async move {
            tracing::debug!(bind = %local_addr, "container IPC bridge listening");
            if let Err(error) = run_container_ipc_bridge(
                listener,
                registry,
                workspace,
                shutdown_rx,
                bridge_executor,
            )
            .await
            {
                tracing::debug!(error = %error, "container IPC bridge stopped with error");
            }
            tracing::debug!(bind = %local_addr, "container IPC bridge stopped");
        })
        .detach();

    Ok(ContainerIpcBridge {
        shutdown_tx,
        port: local_addr.port(),
    })
}

enum ContainerIpcBridgeEvent {
    Accept(std::io::Result<(Async<StdTcpStream>, std::net::SocketAddr)>),
    Shutdown,
}

async fn run_container_ipc_bridge<E: Executor + Clone + 'static>(
    listener: Async<StdTcpListener>,
    registry: Arc<ToolRegistry>,
    workspace: Option<MountRoot>,
    shutdown_rx: Receiver<()>,
    executor: E,
) -> Result<(), String> {
    loop {
        let event = futures_lite::future::or(
            async { ContainerIpcBridgeEvent::Accept(listener.accept().await) },
            async {
                let _ = shutdown_rx.recv().await;
                ContainerIpcBridgeEvent::Shutdown
            },
        )
        .await;

        match event {
            ContainerIpcBridgeEvent::Shutdown => break,
            ContainerIpcBridgeEvent::Accept(Ok((stream, _addr))) => {
                tracing::debug!("container IPC bridge accepted connection");
                let registry = registry.clone();
                let workspace = workspace.clone();
                executor
                    .spawn(async move {
                        if let Err(error) =
                            handle_container_ipc_connection(stream, registry, workspace).await
                        {
                            tracing::debug!(error = %error, "container IPC connection failed");
                        }
                    })
                    .detach();
            }
            ContainerIpcBridgeEvent::Accept(Err(error))
                if error.kind() == std::io::ErrorKind::Interrupted => {}
            ContainerIpcBridgeEvent::Accept(Err(error)) => {
                return Err(format!("container IPC accept failed: {error}"));
            }
        }
    }
    Ok(())
}

async fn handle_container_ipc_connection(
    mut stream: Async<StdTcpStream>,
    registry: Arc<ToolRegistry>,
    workspace: Option<MountRoot>,
) -> Result<(), String> {
    loop {
        let mut length_bytes = [0_u8; 4];
        match stream.read_exact(&mut length_bytes).await {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(()),
            Err(error) => return Err(format!("failed to read IPC request length: {error}")),
        }
        let body_length = u32::from_be_bytes(length_bytes) as usize;
        if body_length == 0 || body_length > 16 * 1024 * 1024 {
            return Err(format!("invalid IPC request length: {body_length}"));
        }

        let mut body = vec![0_u8; body_length];
        stream
            .read_exact(&mut body)
            .await
            .map_err(|e| format!("failed to read IPC request body: {e}"))?;

        let request = match heel::ipc::IpcRequest::decode(&body) {
            Ok(request) if !request.method.is_empty() => request,
            Ok(_) => {
                write_container_ipc_error(&mut stream, "empty IPC method name").await?;
                continue;
            }
            Err(error) => {
                write_container_ipc_error(&mut stream, &error.to_string()).await?;
                continue;
            }
        };
        let cli_args = decode_container_ipc_args(&request.params)?;
        // The caller reports its directory as the container sees it; the
        // host resolves relative paths in the directory that is mounted at.
        // A directory outside the workspace mount has no host spelling.
        let working_dir = workspace.as_ref().and_then(|workspace| {
            let container_dir = ContainerPath::new(request.working_dir.to_str()?).ok()?;
            workspace.host_path(&container_dir).ok()
        });
        let envelope = registry
            .query_tool_handler_from(&request.method, &cli_args, working_dir.as_deref())
            .await;
        match crate::command::envelope_to_cli(envelope) {
            Ok(rendered) => write_container_ipc_success(&mut stream, &rendered).await?,
            Err(error) => {
                write_container_ipc_error(&mut stream, &error.to_string()).await?;
            }
        }
    }
}

fn decode_container_ipc_args(params: &[u8]) -> Result<Vec<String>, String> {
    let parsed: serde_json::Value =
        rmp_serde::from_slice(params).map_err(|e| format!("invalid IPC params: {e}"))?;
    let args = parsed
        .as_object()
        .ok_or_else(|| "container IPC params must be a map".to_string())?;
    let args = args
        .iter()
        .map(|(key, value)| (key.clone(), value.clone()))
        .collect::<std::collections::HashMap<_, _>>();
    Ok(crate::command::flatten_args_to_cli(&args))
}

async fn write_container_ipc_success(
    stream: &mut Async<StdTcpStream>,
    rendered: &str,
) -> Result<(), String> {
    let payload = rmp_serde::to_vec_named(rendered)
        .map_err(|e| format!("failed to encode IPC success payload: {e}"))?;
    write_container_ipc_response(stream, true, &payload).await
}

async fn write_container_ipc_error(
    stream: &mut Async<StdTcpStream>,
    message: &str,
) -> Result<(), String> {
    let payload = rmp_serde::to_vec_named(&message.to_string())
        .map_err(|e| format!("failed to encode IPC error payload: {e}"))?;
    write_container_ipc_response(stream, false, &payload).await
}

async fn write_container_ipc_response(
    stream: &mut Async<StdTcpStream>,
    success: bool,
    payload: &[u8],
) -> Result<(), String> {
    let body_length = 1usize
        .checked_add(payload.len())
        .ok_or_else(|| "IPC response payload length overflow".to_string())?;
    let response_length = u32::try_from(body_length)
        .map_err(|_| format!("IPC response body too large: {body_length} bytes"))?;

    stream
        .write_all(&response_length.to_be_bytes())
        .await
        .map_err(|e| format!("failed to write IPC response length: {e}"))?;
    stream
        .write_all(&[u8::from(success)])
        .await
        .map_err(|e| format!("failed to write IPC success flag: {e}"))?;
    stream
        .write_all(payload)
        .await
        .map_err(|e| format!("failed to write IPC payload: {e}"))?;
    stream
        .flush()
        .await
        .map_err(|e| format!("failed to flush IPC payload: {e}"))
}

fn preview_first_lines(data: &[u8], max_lines: usize) -> (String, bool) {
    if data.is_empty() || max_lines == 0 {
        return (String::new(), !data.is_empty() && max_lines == 0);
    }

    let text = String::from_utf8_lossy(data);
    let mut preview = String::new();
    let mut total_lines = 0usize;

    for line in text.lines() {
        total_lines += 1;
        if total_lines <= max_lines {
            if !preview.is_empty() {
                preview.push('\n');
            }
            preview.push_str(line);
        }
    }

    let truncated = total_lines > max_lines;
    (preview, truncated)
}

enum TerminalChunk {
    Stdout(Vec<u8>),
    Stderr(Vec<u8>),
    StdoutClosed,
    StderrClosed,
}

fn spawn_terminal_reader<R>(
    mut reader: R,
    tx: async_channel::Sender<TerminalChunk>,
    is_stderr: bool,
) where
    R: Read + Send + 'static,
{
    std::thread::spawn(move || {
        let mut buffer = vec![0_u8; 8192];
        loop {
            match reader.read(&mut buffer) {
                Ok(0) => {
                    let _ = tx.send_blocking(if is_stderr {
                        TerminalChunk::StderrClosed
                    } else {
                        TerminalChunk::StdoutClosed
                    });
                    break;
                }
                Ok(count) => {
                    let chunk = buffer[..count].to_vec();
                    let _ = tx.send_blocking(if is_stderr {
                        TerminalChunk::Stderr(chunk)
                    } else {
                        TerminalChunk::Stdout(chunk)
                    });
                }
                Err(error) => {
                    warn!(error = %error, is_stderr, "terminal reader failed");
                    let _ = tx.send_blocking(if is_stderr {
                        TerminalChunk::StderrClosed
                    } else {
                        TerminalChunk::StdoutClosed
                    });
                    break;
                }
            }
        }
    });
}

fn spawn_terminal_stdin_writer<W>(
    mut writer: W,
    feed: FeedCounter,
) -> async_channel::Sender<Vec<u8>>
where
    W: Write + Send + 'static,
{
    let (tx, rx) = async_channel::unbounded::<Vec<u8>>();
    std::thread::spawn(move || {
        while let Ok(bytes) = rx.recv_blocking() {
            if bytes.is_empty() {
                continue;
            }
            feed.record();
            if let Err(error) = writer.write_all(&bytes) {
                warn!(error = %error, "terminal stdin write failed");
                break;
            }
            if let Err(error) = writer.flush() {
                warn!(error = %error, "terminal stdin flush failed");
                break;
            }
        }
    });
    tx
}

async fn drain_terminal_chunks(
    job_registry: JobRegistry,
    pid: u32,
    rx: async_channel::Receiver<TerminalChunk>,
) {
    while let Ok(chunk) = rx.recv().await {
        match chunk {
            TerminalChunk::Stdout(bytes) => job_registry.append_stdout(pid, bytes).await,
            TerminalChunk::Stderr(bytes) => job_registry.append_stderr(pid, bytes).await,
            TerminalChunk::StdoutClosed => job_registry.close_stdout(pid).await,
            TerminalChunk::StderrClosed => job_registry.close_stderr(pid).await,
        }
    }
}

async fn wait_for_terminal_stream_close(job_registry: &JobRegistry, pid: u32) {
    while !job_registry.terminal_streams_closed(pid).await {
        async_io::Timer::after(Duration::from_millis(10)).await;
    }
}

/// Creates a sandboxed execution's IPC router: the built-in commands and
/// every command `registry` has in the execution's mode.
fn create_ipc_router(registry: &Arc<ToolRegistry>) -> Option<IpcRouter> {
    let mut router = builtin_router();

    let tool_names = registry.registered_tool_names();
    tracing::info!(tools = ?tool_names, "Creating IPC router with registered tools");
    for name in tool_names {
        router = crate::register_tool_command(router, Arc::clone(registry), &name);
    }

    let has_methods = router.methods().next().is_some();
    has_methods.then_some(router)
}

/// Creates an unsafe execution's IPC router: the `ipc` gateway and every
/// command `registry` has in unsafe mode. A command registered for
/// sandboxed modes alone gets no shim, so the name resolves on the host's
/// `PATH`.
fn create_ipc_gateway_router(registry: &Arc<ToolRegistry>) -> Option<IpcRouter> {
    let mut router = crate::register_ipc_gateway_command(IpcRouter::new(), Arc::clone(registry));

    for name in registry.registered_tool_names() {
        router = crate::register_tool_command(router, Arc::clone(registry), &name);
    }

    let has_methods = router.methods().next().is_some();
    has_methods.then_some(router)
}

/// Errors that can occur during terminal execution.
#[derive(Debug, thiserror::Error)]
pub enum TerminalError {
    /// Execution environment or mode is not configured.
    #[error("invalid terminal execution target: {0}")]
    InvalidTarget(String),
    /// Required tool runtime is unavailable or unsafe to expose.
    #[error(transparent)]
    Tools(#[from] ToolRuntimeError),
    /// Permission denied for the requested mode.
    #[error(
        "sandbox blocked {mode} execution; approval is required to escalate this terminal command",
        mode = .0.description()
    )]
    PermissionDenied(TerminalMode),

    /// Permission check failed.
    #[error("permission error: {0}")]
    Permission(#[from] PermissionError),

    /// Sandbox setup failed.
    #[error("sandbox setup failed: {0}")]
    SandboxSetup(String),

    /// Script execution failed.
    #[error("execution failed: {0}")]
    Execution(String),

    /// IO error.
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    /// Jobserver pool or broker error.
    #[cfg(all(unix, feature = "jobserver"))]
    #[error(transparent)]
    Jobserver(#[from] crate::jobserver::JobserverError),
}

impl<P, E, State> std::fmt::Debug for TerminalTool<P, E, State> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TerminalTool")
            .field("working_dir", &self.working_dir)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
    use std::time::Duration;

    use super::*;
    #[cfg(unix)]
    use crate::builtin::{InputTerminalArgs, InputTerminalTool};
    use crate::output::empty_stream;
    use crate::{SandboxNotices, ToolRegistryBuilder};
    #[cfg(unix)]
    use heel::DenyAll;
    use heel::NiceLevel;

    #[cfg(all(unix, feature = "connectivity"))]
    mod outage;

    #[cfg(unix)]
    mod progress;

    /// An output store in `dir`, which exists, leasing from the default
    /// allocator.
    fn test_outputs(dir: impl Into<PathBuf>) -> OutputStore {
        OutputStore::at(dir.into(), AnyIdAllocator::default())
    }

    /// A stdin whose drop reports that the writer thread holding it ended.
    struct DropSignal(async_channel::Sender<()>);

    impl Write for DropSignal {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            Ok(bytes.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl Drop for DropSignal {
        fn drop(&mut self) {
            let _ = self.0.send_blocking(());
        }
    }

    /// A finished job's stdin writer thread exits instead of blocking on its
    /// channel forever.
    #[tokio::test]
    async fn finished_job_ends_its_stdin_writer_thread() {
        use executor_core::{Executor as _, Task as _};
        let (registry, service) = crate::job_registry::job_registry_channel();
        executor_core::tokio::TokioGlobal
            .spawn(async move { service.serve().await })
            .detach();
        registry
            .register(
                9001,
                &crate::test_ids::lease("writer"),
                "exec-writer",
                "cat",
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        let (ended_tx, ended_rx) = async_channel::bounded::<()>(1);
        let input_tx = spawn_terminal_stdin_writer(DropSignal(ended_tx), FeedCounter::default());
        registry.attach_terminal_input(9001, input_tx).await;
        registry
            .terminal_input("writer", b"hi\n".to_vec())
            .await
            .expect("a running job takes input");
        assert!(ended_rx.is_empty(), "the writer lives while the job runs");

        registry.complete(9001, 0, None).await;

        tokio::time::timeout(Duration::from_secs(10), ended_rx.recv())
            .await
            .expect("the writer thread must end once the job finishes")
            .expect("the writer reports its end");
    }

    /// Toolchain directories named by `*_HOME` variables become rwx grants;
    /// ones that do not exist are skipped.
    #[test]
    fn toolchain_grants_cover_existing_dirs_rwx() {
        let cargo = tempfile::tempdir().unwrap();
        let rustup = tempfile::tempdir().unwrap();
        unsafe {
            std::env::set_var("CARGO_HOME", cargo.path());
            std::env::set_var("RUSTUP_HOME", rustup.path().join("missing"));
        }
        let grants: Vec<Grant> = toolchain_grants(|path| {
            ResolvedPath::new(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()))
        })
        .map(|grant| grant.expect("grant"))
        .collect();
        assert_eq!(grants.len(), 1, "only the existing dir is granted");
        let access = grants[0].access();
        assert!(access.can_write());
        assert!(access.can_execute());
        unsafe {
            std::env::remove_var("CARGO_HOME");
            std::env::remove_var("RUSTUP_HOME");
        }
    }

    async fn prepared_test_registry() -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        ShellSessionRegistry,
    ) {
        let cache = crate::tool_runtime::tests::unlocking_tempdir();
        let tools = crate::tool_runtime::tests::bundle()
            .prepare_local(cache.path())
            .await
            .unwrap();
        let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
            local: true,
            container: false,
            ssh: false,
        })
        .with_test_tools(tools);
        (cache, registry)
    }

    /// Counts the consent prompts an SSH authorizer receives and denies each.
    #[derive(Default)]
    struct CountingSshAuthorizer {
        connects: AtomicUsize,
        installs: AtomicUsize,
    }

    impl crate::SshSessionAuthorizer for CountingSshAuthorizer {
        fn authorize_connect(
            &self,
            _target: &str,
        ) -> impl std::future::Future<Output = Result<bool, crate::SshAuthorizationError>> + Send
        {
            self.connects.fetch_add(1, AtomicOrdering::SeqCst);
            std::future::ready(Ok(false))
        }

        fn authorize_runtime_install(
            &self,
            _target: &str,
            _details: &str,
        ) -> impl std::future::Future<Output = Result<bool, crate::SshAuthorizationError>> + Send
        {
            self.installs.fetch_add(1, AtomicOrdering::SeqCst);
            std::future::ready(Ok(false))
        }
    }

    /// A container executor for registries whose container is never reached.
    struct UnreachableContainerExec;

    impl crate::ContainerExec for UnreachableContainerExec {
        fn exec(
            &self,
            _container_id: &str,
            _script: &str,
            _working_dir: &str,
            _kill_rx: Receiver<()>,
            _stdin_rx: Receiver<Vec<u8>>,
            _lifetime: ExecLifetime,
        ) -> impl std::future::Future<Output = Result<crate::ContainerExecOutcome, String>> + Send
        {
            std::future::ready(Err("adoption never executes in the container".to_string()))
        }

        fn exec_streamed(
            &self,
            _container_id: &str,
            _script: &str,
            _working_dir: &str,
            _kill_rx: Receiver<()>,
            _stdin_rx: Receiver<Vec<u8>>,
            _stdout: Sender<Vec<u8>>,
        ) -> impl std::future::Future<Output = Result<crate::ContainerExecOutcome, String>> + Send
        {
            std::future::ready(Err("adoption never executes in the container".to_string()))
        }
    }

    fn test_container_runtime(container_id: &str) -> ContainerShellRuntime {
        ContainerShellRuntime::new(
            container_id,
            crate::ContainerIpcRoute::new(
                "host.docker.internal",
                crate::BridgeAddress::try_from(std::net::IpAddr::from([127, 0, 0, 1]))
                    .expect("loopback binds the bridge"),
            ),
            crate::AnyContainerExec::new(Arc::new(UnreachableContainerExec)),
        )
    }

    fn build_server() -> crate::SshServer {
        crate::SshServer {
            name: "build".to_string(),
            target: "builder@build.internal".to_string(),
        }
    }

    /// Local and SSH configuration gated by `authorizer`, not yet prepared.
    fn local_and_ssh_registry(authorizer: &Arc<CountingSshAuthorizer>) -> ShellSessionRegistry {
        ShellSessionRegistry::new(ShellRuntimeAvailability {
            local: true,
            container: false,
            ssh: true,
        })
        .with_ssh_servers(vec![build_server()])
        .expect("ssh server should configure")
        .with_ssh_authorizer(Arc::clone(authorizer))
    }

    async fn fresh_terminal(
        dir: &Path,
    ) -> TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> {
        TerminalTool::new_exact(
            dir,
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
    }

    /// A trusted manifest serving one script, which reports `tool 1.0.0` and
    /// lists the coreutils aliases, for every managed tool at version 1.0.0.
    #[cfg(unix)]
    async fn script_distribution(directory: &Path) -> ToolDistribution {
        // Invoked through a coreutils alias it runs the host's command of
        // that name, so the scripts of these tests still find `pwd` and `cat`.
        let commands = crate::ManagedTool::ALL.map(crate::ManagedTool::command);
        // As `uv`, `python install <request>` installs a copy of the script as
        // the interpreter, which reports the Python version below.
        let script = format!(
            "#!/bin/sh\n\
             case \"${{0##*/}}\" in bash)\n\
               case \"$1\" in --version) printf '%s\\n' 'GNU bash, version 1.0.0(1)-release (fixture)'; exit 0;; esac\n\
               AITHER_FIXTURE_BASH=1.0.0; export AITHER_FIXTURE_BASH; exec /bin/bash \"$@\";; esac\n\
             case \"${{0##*/}}\" in python*) printf '%s\\n' 'Python 3.13.1'; exit 0;; esac\n\
             case \"${{0##*/}}\" in {}) ;; *) PATH=/usr/bin:/bin exec \"${{0##*/}}\" \"$@\";; esac\n\
             case \"$1\" in --list) printf '%s\\n' {}; exit 0;; esac\n\
             case \"$1\" in python) PATH=/usr/bin:/bin; for request; do :; done; \
             dir=\"$UV_PYTHON_INSTALL_DIR/$request\"; mkdir -p \"$dir/bin\"; \
             cp \"$0\" \"$dir/bin/python3.13\"; chmod 755 \"$dir/bin/python3.13\"; \
             ln -s python3.13 \"$dir/bin/python3\"; exit 0;; esac\n\
             printf '%s\\n' 'tool 1.0.0'\n",
            commands.join("|"),
            crate::tool_runtime::COREUTILS_ALIASES.join(" ")
        )
        .into_bytes();
        let script = script.as_slice();
        let path = directory.join("baseline-tool");
        async_fs::write(&path, script).await.unwrap();
        let artifacts = crate::tool_runtime::tests::native_tools()
            .iter()
            .map(|&tool| crate::ToolArtifact {
                tool,
                version: "1.0.0".into(),
                target: crate::ToolTarget::native().unwrap(),
                url: crate::ToolArtifactLocation::Download(
                    url::Url::from_file_path(&path).unwrap(),
                ),
                sha256: hex::encode(crate::tool_runtime::digest(script)),
                size: script.len() as u64,
                encoding: crate::ToolArtifactFormat::Executable,
            })
            .collect::<Vec<_>>();
        let python = crate::tool_runtime::tests::python_pins_for(
            crate::tool_runtime::digest(script),
            "3.13.1",
        );
        ToolDistribution::from_json(
            &serde_json::to_vec(&serde_json::json!({ "artifacts": artifacts, "python": python }))
                .unwrap(),
        )
        .unwrap()
    }

    /// A script runs through the managed bash, not the host's `sh`: the
    /// fixture bash marks its environment with the pinned version, and the
    /// script's shell is a real bash.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn terminal_script_runs_in_the_managed_bash() {
        let authorizer = Arc::new(CountingSshAuthorizer::default());
        let tools_cache = tempfile::tempdir().unwrap();
        let tools = crate::tool_runtime::tests::bundle()
            .prepare_local(tools_cache.path())
            .await
            .unwrap();
        let prepared = local_and_ssh_registry(&authorizer)
            .with_test_tools(tools.clone())
            .with_test_ssh(build_server(), tools);
        let directory = tempfile::tempdir().unwrap();
        let terminal = fresh_terminal(directory.path())
            .await
            .adopt_prepared_tools(prepared)
            .await
            .expect("a prepared registry should be adopted");
        let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.output_store().clone()));
        let terminal = terminal.with_registry(registry);
        let result = terminal
            .call(
                TerminalArgs {
                    description: "report the shell".to_string(),
                    script: "[[ -n $BASH_VERSION ]] && echo \"managed=$AITHER_FIXTURE_BASH bash\""
                        .to_string(),
                    language: ScriptLanguage::Shell,
                    mode: TerminalExecutionMode::Sandboxed,
                    ssh_server_id: None,
                    expect: OutputFormat::Text,
                    resolution: MediaResolution::Auto,
                    max_lines: 50,
                    raw: true,
                    timeout: 30,
                    background: false,
                },
                ToolContext::new(),
            )
            .await
            .expect("the script should run");
        let stdout = render_terminal_result(&result);
        assert!(!stdout.contains("Exit code:"), "{stdout}");
        assert!(stdout.contains("managed=1.0.0 bash"), "{stdout}");
    }

    /// A command run on an SSH server is a remote job: its local `ssh`
    /// process stands for work whose memory is never judged here.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_command_run_over_ssh_is_a_remote_job() {
        let authorizer = Arc::new(CountingSshAuthorizer::default());
        let tools_cache = tempfile::tempdir().unwrap();
        let tools = crate::tool_runtime::tests::bundle()
            .prepare_local(tools_cache.path())
            .await
            .unwrap();
        let prepared = local_and_ssh_registry(&authorizer)
            .with_test_tools(tools.clone())
            .with_test_ssh(build_server(), tools);
        let directory = tempfile::tempdir().unwrap();
        let terminal = fresh_terminal(directory.path())
            .await
            .adopt_prepared_tools(prepared)
            .await
            .expect("a prepared registry should be adopted");
        let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.output_store().clone()));
        let terminal = terminal.with_registry(registry);
        let _ = terminal
            .call(
                TerminalArgs {
                    description: "run remotely".to_string(),
                    script: "echo remote-job".to_string(),
                    language: ScriptLanguage::Shell,
                    mode: TerminalExecutionMode::Ssh,
                    ssh_server_id: None,
                    expect: OutputFormat::Text,
                    resolution: MediaResolution::Auto,
                    max_lines: 50,
                    raw: true,
                    timeout: 30,
                    background: true,
                },
                ToolContext::new(),
            )
            .await;

        let jobs = terminal.job_registry().list().await;
        let job = jobs
            .iter()
            .find(|job| job.script == "echo remote-job")
            .expect("the remote job is registered");
        assert_eq!(job.place, crate::JobPlace::Remote);
        let machine = terminal.job_memory().snapshot().await.unwrap();
        assert_eq!(machine.jobs, []);
        // An SSH server is never a home environment: no container to watch.
        assert!(terminal.container_probe().is_none());
        terminal.job_registry().kill_running().await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn adopted_registry_runs_baseline_tools_without_ssh_consent_or_version_probes() {
        let authorizer = Arc::new(CountingSshAuthorizer::default());

        // Full preparation asks the authorizer before connecting to every
        // server; the denial ends it.
        let artifacts = tempfile::tempdir().unwrap();
        let distribution = script_distribution(artifacts.path()).await;
        let first = tempfile::tempdir().unwrap();
        let cache = crate::tool_runtime::tests::unlocking_tempdir();
        let denied = fresh_terminal(first.path())
            .await
            .with_shell_sessions(local_and_ssh_registry(&authorizer))
            .initialize_tools(&distribution, cache.path())
            .await;
        assert!(
            matches!(denied, Err(ToolRuntimeError::SshBootstrap(_))),
            "a denied connection must fail preparation"
        );
        assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);

        // Tools pinned to a version their commands do not report: the version
        // probe of full preparation rejects them.
        let tools_cache = crate::tool_runtime::tests::unlocking_tempdir();
        let tools = crate::tool_runtime::tests::bundle_pinned("2.0.0")
            .prepare_local(tools_cache.path())
            .await
            .unwrap();
        assert!(matches!(
            tools
                .verify_local_versions(
                    executor_core::tokio::TokioGlobal,
                    heel::HeelBinary::locate().unwrap(),
                )
                .await,
            Err(ToolRuntimeError::VersionMismatch(_))
        ));
        let prepared = local_and_ssh_registry(&authorizer)
            .with_test_tools(tools.clone())
            .with_test_ssh(build_server(), tools);

        let second = tempfile::tempdir().unwrap();
        let terminal = fresh_terminal(second.path())
            .await
            .adopt_prepared_tools(prepared)
            .await
            .expect("a prepared registry should be adopted without probing or consent");
        assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);
        assert_eq!(authorizer.installs.load(AtomicOrdering::SeqCst), 0);

        let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.output_store().clone()));
        let terminal = terminal.with_registry(registry);
        let result = terminal
            .call(
                TerminalArgs {
                    description: "run every baseline command".to_string(),
                    script: "apply_patch --version && rg --version && ast-grep --version && jq --version"
                        .to_string(),
                    language: ScriptLanguage::Shell,
                    mode: TerminalExecutionMode::Sandboxed,
                    ssh_server_id: None,
                    expect: OutputFormat::Text,
                    resolution: MediaResolution::Auto,
                    max_lines: 50,
                    raw: true,
                    timeout: 30,
                    background: false,
                },
                ToolContext::new(),
            )
            .await
            .expect("baseline commands should run");
        let stdout = render_terminal_result(&result);
        assert!(!stdout.contains("Exit code:"), "{stdout}");
        for command in ["apply_patch", "rg", "ast-grep", "jq"] {
            assert!(
                stdout.contains(&format!("{command} 1.0.0")),
                "{command} should run from the adopted tools; stdout: {stdout}"
            );
        }
        assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);
        assert_eq!(authorizer.installs.load(AtomicOrdering::SeqCst), 0);
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_container_home_still_gives_the_host_runnable_tools() {
        let container = ShellSessionRegistry::new(ShellRuntimeAvailability {
            local: false,
            container: true,
            ssh: false,
        })
        .with_container_runtime(test_container_runtime("aither-host-tools"))
        .with_test_container_tools(
            crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools()),
            "aither-host-tools".to_string(),
        );
        assert!(
            matches!(
                container.local_tools(),
                Err(ToolRuntimeError::NotInitialized(_))
            ),
            "the container's own tools are not host-runnable"
        );

        let artifacts = tempfile::tempdir().unwrap();
        let distribution = script_distribution(artifacts.path()).await;
        let cache = crate::tool_runtime::tests::unlocking_tempdir();
        let host = container
            .host_tools(&distribution, cache.path())
            .await
            .expect("the distribution prepares the host target");
        let runtimes = std::fs::canonicalize(cache.path().join("runtimes")).unwrap();
        assert!(host.bin_dir().starts_with(runtimes));
        for command in ["apply_patch", "rg", "ast-grep", "jq"] {
            let output = std::process::Command::new(host.bin_dir().join(command))
                .output()
                .expect("the host runs the prepared tool");
            assert_eq!(
                String::from_utf8_lossy(&output.stdout),
                "tool 1.0.0\n",
                "{command}"
            );
        }
    }

    #[tokio::test]
    async fn adoption_rejects_a_registry_changed_after_preparation() {
        let authorizer = Arc::new(CountingSshAuthorizer::default());
        let tools_cache = crate::tool_runtime::tests::unlocking_tempdir();
        let tools = crate::tool_runtime::tests::bundle()
            .prepare_local(tools_cache.path())
            .await
            .unwrap();
        let prepared = local_and_ssh_registry(&authorizer)
            .with_test_tools(tools.clone())
            .with_test_ssh(build_server(), tools.clone());
        let staging = crate::SshServer {
            name: "staging".to_string(),
            target: "deploy@staging.internal".to_string(),
        };
        let retargeted = crate::SshServer {
            target: "builder@build-2.internal".to_string(),
            ..build_server()
        };
        let container = ShellSessionRegistry::new(ShellRuntimeAvailability {
            local: false,
            container: true,
            ssh: false,
        })
        .with_container_runtime(test_container_runtime("aither-tools-a"))
        .with_test_container_tools(
            crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools()),
            "aither-tools-a".to_string(),
        );

        let dir = tempfile::tempdir().unwrap();
        let adopt = |sessions: ShellSessionRegistry| {
            let dir = dir.path().to_path_buf();
            async move {
                fresh_terminal(&dir)
                    .await
                    .adopt_prepared_tools(sessions)
                    .await
            }
        };

        assert!(adopt(prepared.clone()).await.is_ok());
        assert!(adopt(container.clone()).await.is_ok());
        assert!(matches!(
            adopt(local_and_ssh_registry(&authorizer)).await,
            Err(ToolRuntimeError::NotInitialized(_))
        ));
        for servers in [vec![build_server(), staging], Vec::new(), vec![retargeted]] {
            assert!(matches!(
                adopt(prepared.clone().with_ssh_servers(servers).unwrap()).await,
                Err(ToolRuntimeError::EnvironmentChanged(
                    crate::PreparedEnvironment::SshServers
                ))
            ));
        }
        assert!(matches!(
            adopt(container.with_container_runtime(test_container_runtime("aither-tools-b"))).await,
            Err(ToolRuntimeError::EnvironmentChanged(
                crate::PreparedEnvironment::Container
            ))
        ));
        assert!(matches!(
            adopt(prepared.with_availability(ShellRuntimeAvailability {
                local: true,
                container: true,
                ssh: true,
            }))
            .await,
            Err(ToolRuntimeError::EnvironmentChanged(
                crate::PreparedEnvironment::HomeBackend
            ))
        ));
        assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 0);
    }

    #[tokio::test]
    async fn adoption_rechecks_this_terminals_writable_paths() {
        let (cache, prepared) = prepared_test_registry().await;
        let dir = tempfile::tempdir().unwrap();
        let exposed = fresh_terminal(dir.path())
            .await
            .with_writable_paths([cache.path()])
            .adopt_prepared_tools(prepared)
            .await;
        assert!(matches!(
            exposed,
            Err(ToolRuntimeError::WritableToolDirectory(_))
        ));
    }

    fn render_terminal_result(result: &ToolResult) -> String {
        result.render_for_model()
    }

    fn started_task_id(receiver: &BackgroundTaskReceiver) -> String {
        let started = receiver.take_started();
        assert_eq!(started.len(), 1, "expected one started-task event");
        started[0].task_id.clone()
    }

    #[cfg(unix)]
    #[test]
    fn shell_launch_runs_the_managed_bash_without_startup_files() {
        let script = "printf '%s\\n' hello | cat";
        let (program, args) = shell_launch("/tools/bin/bash", script);

        assert_eq!(program, "/tools/bin/bash");
        assert_eq!(args[..3], ["--noprofile", "--norc", "-c"]);
        assert!(args[3].ends_with(script));
        assert_eq!(args.len(), 4);
    }

    #[test]
    fn host_programs_run_without_a_shell() {
        for name in ["grep", "sed", "awk", "find"] {
            assert_eq!(
                direct_command(&format!("{name} x")).unwrap(),
                Some((name.to_string(), vec!["x".to_string()]))
            );
        }
    }

    #[test]
    fn inject_env_exports_prepends_valid_pairs() {
        let source: Option<Arc<dyn TerminalEnvSource>> = Some(Arc::new(vec![
            ("MY_KEY".to_string(), "it's".to_string()),
            ("OTHER".to_string(), "x".to_string()),
        ]));
        let rendered = inject_env_exports("echo hi".to_string(), source.as_ref())
            .expect("valid env names should render");
        assert_eq!(
            rendered,
            "export MY_KEY='it'\"'\"'s'\nexport OTHER='x'\necho hi"
        );
    }

    #[test]
    fn inject_env_exports_rejects_shell_syntax_names() {
        let source: Option<Arc<dyn TerminalEnvSource>> =
            Some(Arc::new(vec![("BAD;name".to_string(), "x".to_string())]));
        assert!(inject_env_exports("echo hi".to_string(), source.as_ref()).is_err());
        assert_eq!(
            inject_env_exports("echo hi".to_string(), None).expect("no source passes through"),
            "echo hi"
        );
    }

    #[tokio::test]
    async fn session_runtime_environment_is_prepared_without_wrapping_the_script() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let cache = crate::tool_runtime::tests::unlocking_tempdir();
        let ready = crate::tool_runtime::tests::bundle()
            .prepare_local(cache.path())
            .await
            .unwrap();
        let environment = prepare_session_runtime_environment(dir.path(), &ready)
            .await
            .expect("session runtime environment should be prepared");
        let value = |name: &str| {
            environment
                .iter()
                .find_map(|(key, value)| (key == name).then_some(value.as_str()))
                .unwrap_or_else(|| panic!("missing session environment variable {name}"))
        };

        assert_eq!(value("HOME"), dir.path().to_str().expect("UTF-8 temp path"));
        assert_eq!(
            value("TMPDIR"),
            dir.path().join("tmp").to_str().expect("UTF-8 temp path")
        );
        assert_eq!(value("TMP"), value("TMPDIR"));
        assert_eq!(value("TEMP"), value("TMPDIR"));
        assert!(dir.path().join("tmp").is_dir());
        assert!(dir.path().join(".cache/bun").is_dir());
        assert!(dir.path().join(".cache/ms-playwright").is_dir());
        assert!(dir.path().join(".config").is_dir());
        // `uv` keeps its state in the shared directory, not in the session's HOME.
        if let Some(uv) = ready.uv_dir() {
            assert_eq!(
                value("UV_CACHE_DIR"),
                uv.join("cache").to_str().expect("UTF-8 temp path")
            );
            assert_eq!(
                value("UV_PYTHON_INSTALL_DIR"),
                uv.join("python").to_str().expect("UTF-8 temp path")
            );
            assert_eq!(value("UV_PYTHON_PREFERENCE"), "system");
            assert!(!uv.starts_with(dir.path()));
        }
    }

    /// The shared `uv` directory is writable and executable beside the
    /// read-only tools directory, and nothing else of the cache is.
    #[cfg(unix)]
    #[tokio::test]
    async fn the_shared_uv_directory_is_a_writable_grant_apart_from_the_tools() {
        let cache = crate::tool_runtime::tests::unlocking_tempdir();
        let ready = crate::tool_runtime::tests::bundle()
            .prepare_local(cache.path())
            .await
            .unwrap();
        let uv = ready.uv_dir().expect("the test host has a managed uv");
        let grants = local_path_grants(&[], &[], &ready).expect("grants build");
        let access_of = |path: &Path| {
            let path = std::fs::canonicalize(path).unwrap();
            grants
                .iter()
                .find(|grant| grant.resolved_path().as_path() == path)
                .map(heel::Grant::access)
        };
        assert_eq!(access_of(uv), Some(Access::WRITE | Access::EXEC));
        assert_eq!(access_of(ready.bin_dir()), Some(Access::EXEC));
        // Neither grant exposes the other.
        assert!(!ready.bin_dir().starts_with(uv) && !uv.starts_with(ready.bin_dir()));
    }

    #[tokio::test]
    async fn session_runtime_environment_sets_toolchain_homes_and_host_path() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let cache = crate::tool_runtime::tests::unlocking_tempdir();
        let cargo_home = tempfile::tempdir().unwrap();
        let rustup_home = tempfile::tempdir().unwrap();
        unsafe {
            std::env::set_var("CARGO_HOME", cargo_home.path());
            std::env::set_var("RUSTUP_HOME", rustup_home.path());
        }
        let ready = crate::tool_runtime::tests::bundle()
            .prepare_local(cache.path())
            .await
            .unwrap();
        let environment = prepare_session_runtime_environment(dir.path(), &ready)
            .await
            .expect("session runtime environment should be prepared");
        unsafe {
            std::env::remove_var("CARGO_HOME");
            std::env::remove_var("RUSTUP_HOME");
        }
        let value = |name: &str| {
            environment
                .iter()
                .find_map(|(key, value)| (key == name).then_some(value.as_str()))
                .unwrap_or_else(|| panic!("missing session environment variable {name}"))
        };

        assert_eq!(
            value("CARGO_HOME"),
            cargo_home.path().to_str().expect("UTF-8 temp path")
        );
        assert_eq!(
            value("RUSTUP_HOME"),
            rustup_home.path().to_str().expect("UTF-8 temp path")
        );
        let host_path = std::env::var("PATH").expect("host PATH");
        let path = value("PATH");
        assert!(
            path.starts_with(ready.bin_dir().to_str().expect("UTF-8 tools dir")),
            "the managed tools dir leads PATH: {path}"
        );
        assert!(
            path.contains(&host_path),
            "the host PATH follows the tools dir: {path}"
        );
    }

    /// Writable working directories execute what they hold — a build output
    /// or a chmod'd script is runnable.
    #[tokio::test]
    async fn local_path_grants_make_writable_dirs_executable() {
        let workdir = tempfile::tempdir().unwrap();
        let readonly = tempfile::tempdir().unwrap();
        let cache = crate::tool_runtime::tests::unlocking_tempdir();
        let tools = crate::tool_runtime::tests::bundle()
            .prepare_local(cache.path())
            .await
            .unwrap();
        let grants = local_path_grants(
            &[workdir.path().to_path_buf()],
            &[readonly.path().to_path_buf()],
            &tools,
        )
        .expect("grants build");
        let canonical = |dir: &tempfile::TempDir| std::fs::canonicalize(dir.path()).unwrap();
        let access_of = |dir: &tempfile::TempDir| {
            grants
                .iter()
                .find(|grant| grant.resolved_path().as_path() == canonical(dir))
                .map(heel::Grant::access)
        };
        let access = access_of(&workdir).expect("workdir grant");
        assert!(access.can_write());
        assert!(access.can_execute(), "a writable directory also executes");
        let access = access_of(&readonly).expect("readonly grant");
        assert!(!access.can_write());
        assert!(!access.can_execute());
    }

    fn output_text(output: &CommandStream) -> Option<&str> {
        match output {
            CommandStream::Inline { text } => Some(text.as_str()),
            CommandStream::Stored { preview, .. } => Some(preview.as_str()),
            CommandStream::Image { .. } => None,
        }
    }

    async fn wait_for_completed_task(
        receiver: &BackgroundTaskReceiver,
        task_id: &str,
    ) -> CompletedTask {
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                if let Some(task) = receiver
                    .take_completed()
                    .into_iter()
                    .find(|task| task.task_id == task_id)
                {
                    return task;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        })
        .await
        .expect("background task should complete after terminal input")
    }

    #[derive(Default)]
    struct TestPermissionHandler {
        mode_checks: AtomicUsize,
        domain_checks: AtomicUsize,
        allow_domain: bool,
        allow_unsafe: bool,
    }

    impl PermissionHandler for TestPermissionHandler {
        fn check(
            &self,
            mode: TerminalMode,
            _script: &str,
            _language: ScriptLanguage,
        ) -> impl std::future::Future<Output = Result<bool, PermissionError>> + Send {
            self.mode_checks.fetch_add(1, AtomicOrdering::Relaxed);
            std::future::ready(Ok(match mode {
                TerminalMode::Sandboxed => true,
                TerminalMode::Unsafe => self.allow_unsafe,
            }))
        }

        fn check_domain(
            &self,
            _domain: &str,
            _port: u16,
        ) -> impl std::future::Future<Output = bool> + Send {
            self.domain_checks.fetch_add(1, AtomicOrdering::Relaxed);
            std::future::ready(self.allow_domain)
        }
    }

    #[tokio::test]
    async fn test_terminal_args_defaults() {
        let args: TerminalArgs = serde_json::from_str(
            r#"{"description":"print a greeting","script":"echo hello","timeout":30}"#,
        )
        .unwrap();
        assert_eq!(args.expect, OutputFormat::Text);
        assert_eq!(args.resolution, MediaResolution::Auto);
        assert_eq!(args.mode, TerminalExecutionMode::Default);
        assert!(!args.background);
    }

    #[test]
    fn background_preview_keeps_leading_indentation() {
        assert_eq!(
            background_preview("  col a  col b\nrow\n\n"),
            "  col a  col b\nrow"
        );
        assert_eq!(background_preview(" \n\t\n"), "");
    }

    fn inline(text: &str) -> CommandStream {
        CommandStream::Inline {
            text: text.to_string(),
        }
    }

    fn completed(
        stdout: CommandStream,
        stderr: Option<CommandStream>,
        exit_code: i32,
    ) -> CommandResult {
        CompletedCommand {
            stdout,
            stderr,
            exit_code,
            interruptions: Vec::new(),
        }
        .into()
    }

    #[test]
    fn completed_command_exit_zero_is_the_bare_output() {
        let result = completed(inline("done"), None, 0)
            .into_tool_result()
            .unwrap();
        assert_eq!(result.render_for_model(), "done\n");
        assert_eq!(
            result.command().map(|command| &command.outcome),
            Some(&CommandOutcome::Exited { code: 0 })
        );
    }

    #[test]
    fn completed_command_without_any_output_says_so() {
        assert_eq!(
            completed(empty_stream(), None, 0).render_for_model(),
            "(no output)\n"
        );
    }

    #[test]
    fn completed_command_non_zero_exit_with_stderr() {
        let result = completed(inline("partial"), Some(inline("oops")), 2);
        assert_eq!(
            result.render_for_model(),
            "partial\nstderr:\noops\nExit code: 2.\n"
        );
    }

    #[test]
    fn completed_command_stderr_only_has_no_contradicting_placeholder() {
        assert_eq!(
            completed(empty_stream(), Some(inline("oops")), 2).render_for_model(),
            "stderr:\noops\nExit code: 2.\n"
        );
    }

    #[tokio::test]
    async fn test_terminal_args_parsing() {
        let args: TerminalArgs = serde_json::from_str(
            r#"{"description":"sleep in background","script":"sleep 5","timeout":30,"background":true}"#,
        )
        .unwrap();
        assert_eq!(args.timeout, 30);
        assert_eq!(args.script, "sleep 5");
        assert!(args.background);

        let missing_timeout = serde_json::from_str::<TerminalArgs>(
            r#"{"description":"sleep in background","script":"sleep 5"}"#,
        )
        .unwrap_err();
        assert!(missing_timeout.to_string().contains("timeout"));

        let missing_description =
            serde_json::from_str::<TerminalArgs>(r#"{"script":"echo hello","timeout":1}"#)
                .unwrap_err();
        assert!(missing_description.to_string().contains("description"));
    }

    #[test]
    fn terminal_args_schema_lists_required_fields() {
        let schema = serde_json::to_value(schemars::schema_for!(TerminalArgs)).unwrap();
        let properties = schema["properties"].as_object().expect("object schema");
        for field in [
            "description",
            "script",
            "timeout",
            "max_lines",
            "background",
        ] {
            assert!(
                properties.contains_key(field),
                "{field} missing from schema {schema}"
            );
        }
        let required = schema["required"].as_array().expect("required list");
        for field in ["description", "script", "timeout"] {
            assert!(
                required.iter().any(|name| name == field),
                "{field} not required in {schema}"
            );
        }
        assert!(
            !required.iter().any(|name| name == "background"),
            "background must not be required in {schema}"
        );
    }

    /// The tools bin directory a container execution passes to the wrapper.
    fn container_tools_dir() -> ContainerPath {
        crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools())
            .bin_dir()
            .clone()
    }

    #[test]
    fn wrap_container_script_refreshes_command_hash_table() {
        let wrapped = wrap_container_script(
            "websearch \"gold price\"",
            &[String::from("websearch")],
            Some(ContainerIpcEndpoint {
                host: "host.docker.internal",
                port: 9000,
            }),
            ProcessPriority::default(),
            &container_tools_dir(),
            CONTAINER_EXEC_WORKING_DIR,
            None,
        )
        .expect("wrap script");
        assert!(wrapped.contains("hash -r;"));
        assert!(wrapped.contains("MAY_IPC_DIR"));
        assert!(wrapped.contains("HEEL_IPC_ENDPOINT"));
    }

    #[test]
    fn wrap_container_script_preserves_user_script_semantics() {
        let script = "echo '$5,040' && subagent art_direction --prompt-file tmp/prompt.md";
        let wrapped = wrap_container_script(
            script,
            &[String::from("subagent")],
            Some(ContainerIpcEndpoint {
                host: "host.docker.internal",
                port: 9000,
            }),
            ProcessPriority::default(),
            &container_tools_dir(),
            CONTAINER_EXEC_WORKING_DIR,
            None,
        )
        .expect("wrap script");
        assert!(wrapped.contains(script));
        assert!(!wrapped.contains("set -euo pipefail"));
    }

    #[test]
    fn wrap_container_script_rejects_invalid_ipc_command_names() {
        let error = wrap_container_script(
            "echo ok",
            &[String::from("bad name")],
            Some(ContainerIpcEndpoint {
                host: "host.docker.internal",
                port: 9000,
            }),
            ProcessPriority::default(),
            &container_tools_dir(),
            CONTAINER_EXEC_WORKING_DIR,
            None,
        )
        .expect_err("invalid command name must fail");
        assert!(
            error
                .to_string()
                .contains("invalid ipc command name for container wrapper")
        );
    }

    #[test]
    fn wrap_container_script_renders_expected_endpoint() {
        let wrapped = wrap_container_script(
            "environment --query deployment",
            &[String::from("environment"), String::from("session")],
            Some(ContainerIpcEndpoint {
                host: "host.containers.internal",
                port: 43123,
            }),
            ProcessPriority::default(),
            &container_tools_dir(),
            CONTAINER_EXEC_WORKING_DIR,
            None,
        )
        .expect("wrap script");
        assert!(wrapped.contains("tcp://host.containers.internal:43123"));
        assert!(wrapped.contains("for cmd in 'environment' 'session'; do"));
    }

    #[tokio::test]
    async fn ensure_mode_allowed_requires_unsafe_approval() {
        let handler = TestPermissionHandler {
            allow_domain: true,
            ..Default::default()
        };
        let err = ensure_mode_allowed(
            &handler,
            TerminalMode::Unsafe,
            "rm -rf /tmp/demo",
            ScriptLanguage::Shell,
        )
        .await
        .expect_err("unsafe mode should be denied");
        assert!(matches!(
            err,
            TerminalError::PermissionDenied(TerminalMode::Unsafe)
        ));
        assert_eq!(handler.mode_checks.load(AtomicOrdering::Relaxed), 1);
    }

    #[tokio::test]
    async fn permission_network_policy_delegates_domain_checks() {
        let handler = Arc::new(TestPermissionHandler {
            allow_domain: true,
            ..Default::default()
        });
        let policy = PermissionNetworkPolicy {
            permission_handler: handler.clone(),
        };
        let request = DomainRequest::new("example.com", 443);
        assert!(policy.check(&request).await);
        assert_eq!(handler.domain_checks.load(AtomicOrdering::Relaxed), 1);
    }

    /// A handler whose review step answers `review` and whose own route
    /// waits for a person.
    struct ReviewingHandler {
        review: Review,
        waits: AtomicUsize,
        checks: AtomicUsize,
    }

    impl ReviewingHandler {
        fn new(review: Review) -> Self {
            Self {
                review,
                waits: AtomicUsize::new(0),
                checks: AtomicUsize::new(0),
            }
        }
    }

    impl PermissionHandler for ReviewingHandler {
        fn review(
            &self,
            _request: &PermissionRequest<'_>,
        ) -> impl std::future::Future<Output = Review> + Send {
            std::future::ready(self.review.clone())
        }

        fn check(
            &self,
            _mode: TerminalMode,
            _script: &str,
            _language: ScriptLanguage,
        ) -> impl std::future::Future<Output = Result<bool, PermissionError>> + Send {
            self.checks.fetch_add(1, AtomicOrdering::Relaxed);
            std::future::ready(Ok(true))
        }

        fn will_wait_for_approval(
            &self,
            _mode: TerminalMode,
            _script: &str,
            _language: ScriptLanguage,
        ) -> impl std::future::Future<Output = bool> + Send {
            self.waits.fetch_add(1, AtomicOrdering::Relaxed);
            std::future::ready(true)
        }
    }

    async fn permission_stages(
        review: Review,
    ) -> (Result<(), String>, Vec<PermissionEventStage>, [usize; 2]) {
        let dir = tempfile::tempdir().unwrap();
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = TerminalTool::new_exact(
            dir.path(),
            ReviewingHandler::new(review),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted");
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let tool = tool.with_registry(registry);
        let result = tool
            .ensure_permission_allowed(TerminalMode::Unsafe, "make install", ScriptLanguage::Shell)
            .await
            .map_err(|error| error.to_string());
        let stages = tool
            .permission_receiver()
            .take_pending()
            .into_iter()
            .map(|event| event.stage)
            .collect();
        let handler = &tool.permission_handler;
        (
            result,
            stages,
            [
                handler.waits.load(AtomicOrdering::Relaxed),
                handler.checks.load(AtomicOrdering::Relaxed),
            ],
        )
    }

    #[tokio::test]
    async fn a_request_a_reviewer_approves_emits_no_permission_event() {
        let (result, stages, [waits, checks]) = permission_stages(Review::Approved).await;
        result.expect("approved");
        assert_eq!(stages, Vec::<PermissionEventStage>::new());
        assert_eq!([waits, checks], [0, 0], "the route is not asked");
    }

    #[tokio::test]
    async fn a_request_a_reviewer_denies_emits_no_permission_event() {
        let (result, stages, [waits, checks]) =
            permission_stages(Review::Denied("not today".into())).await;
        assert!(result.unwrap_err().contains("not today"));
        assert_eq!(stages, Vec::<PermissionEventStage>::new());
        assert_eq!([waits, checks], [0, 0], "the route is not asked");
    }

    #[tokio::test]
    async fn a_request_every_reviewer_passes_waits_then_resolves() {
        let (result, stages, [waits, checks]) = permission_stages(Review::Passed).await;
        result.expect("the route allows");
        assert_eq!(
            stages,
            [
                PermissionEventStage::Waiting,
                PermissionEventStage::Resolved
            ]
        );
        assert_eq!([waits, checks], [1, 1]);
    }

    #[tokio::test]
    async fn permission_network_policy_reviews_a_domain_before_asking() {
        struct Domains(Review, AtomicUsize);
        impl PermissionHandler for Domains {
            fn check(
                &self,
                _mode: TerminalMode,
                _script: &str,
                _language: ScriptLanguage,
            ) -> impl std::future::Future<Output = Result<bool, PermissionError>> + Send
            {
                std::future::ready(Ok(true))
            }
            fn review(
                &self,
                request: &PermissionRequest<'_>,
            ) -> impl std::future::Future<Output = Review> + Send {
                assert_eq!(
                    *request,
                    PermissionRequest::Domain {
                        domain: "example.com",
                        port: 443
                    }
                );
                std::future::ready(self.0.clone())
            }
            fn domain_needs_approval(
                &self,
                _domain: &str,
                _port: u16,
            ) -> impl std::future::Future<Output = bool> + Send {
                std::future::ready(true)
            }
            fn check_domain(
                &self,
                _domain: &str,
                _port: u16,
            ) -> impl std::future::Future<Output = bool> + Send {
                self.1.fetch_add(1, AtomicOrdering::Relaxed);
                std::future::ready(true)
            }
        }
        let request = DomainRequest::new("example.com", 443);
        for (review, allowed, asked) in [
            (Review::Approved, true, 0),
            (Review::Denied("no".into()), false, 0),
            (Review::Passed, true, 1),
        ] {
            let handler = Arc::new(Domains(review, AtomicUsize::new(0)));
            let policy = PermissionNetworkPolicy {
                permission_handler: handler.clone(),
            };
            assert_eq!(policy.check(&request).await, allowed);
            assert_eq!(handler.1.load(AtomicOrdering::Relaxed), asked);
        }
    }

    #[test]
    fn sandboxed_execution_mode_deserializes() {
        let mode: TerminalExecutionMode =
            serde_json::from_str("\"sandboxed\"").expect("sandboxed mode must deserialize");
        assert_eq!(mode, TerminalExecutionMode::Sandboxed);
    }

    #[tokio::test]
    async fn uninitialized_terminal_rejects_execution_and_catalog() {
        let dir = tempfile::tempdir().unwrap();
        let tool = TerminalTool::new_exact(
            dir.path(),
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .unwrap();
        assert!(matches!(
            tool.prepared_tools_context(),
            Err(ToolRuntimeError::NotInitialized(_))
        ));
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let tool = tool.with_registry(registry);
        assert!(matches!(
            tool.resolve_default_target(),
            Err(TerminalError::Tools(ToolRuntimeError::NotInitialized(_)))
        ));
    }

    #[tokio::test]
    async fn child_terminal_exposes_controls_with_isolated_jobs() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted");
        tool.job_registry()
            .register(
                424_242,
                &crate::test_ids::lease("parent"),
                "parent-execution",
                "sleep 30",
                TerminalMode::Sandboxed,
                None,
            )
            .await;

        let parent_registry =
            Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let parent = tool.with_registry(parent_registry);
        let child = parent
            .subagent_without_grant()
            .await
            .expect("an empty grant is always given");
        assert_eq!(
            parent.prepared_tools_context().unwrap(),
            child.prepared_tools_context().unwrap()
        );
        assert!(child.job_registry().list().await.is_empty());
        for name in ["terminal_kill", "terminal_input", "terminal_read"] {
            assert!(child.registry().is_tool_configured(name));
        }
        let args = vec!["--task-id".to_string(), "parent".to_string()];
        let parent_output = serde_json::to_value(
            parent
                .registry()
                .query_tool_handler("terminal_read", &args)
                .await,
        )
        .unwrap();
        let child_output = serde_json::to_value(
            child
                .registry()
                .query_tool_handler("terminal_read", &args)
                .await,
        )
        .unwrap();
        assert!(parent_output.to_string().contains("running"));
        assert!(!child_output.to_string().contains("running"));
        let names = child
            .to_dyn()
            .into_entries()
            .into_iter()
            .map(|entry| entry.definition.name().to_string())
            .collect::<Vec<_>>();

        assert_eq!(names, vec!["terminal"]);
    }

    /// Picks one of the entries of its terminal's working directory, and
    /// names those entries when a call does not parse.
    struct PickTool {
        dir: PathBuf,
    }

    /// Pick an entry.
    #[derive(serde::Deserialize, schemars::JsonSchema)]
    struct PickArgs {
        /// The entry.
        entry: String,
    }

    impl aither_core::llm::Tool for PickTool {
        fn name(&self) -> std::borrow::Cow<'static, str> {
            "pick".into()
        }
        type Arguments = PickArgs;
        type Res = aither_core::llm::ToolResult;

        fn call(
            &self,
            args: Self::Arguments,
            _cx: aither_core::llm::ToolContext,
        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
            std::future::ready(Ok(aither_core::llm::ToolResult::text(args.entry)))
        }
    }

    impl crate::CommandUsage for PickTool {
        async fn usage(&self) -> String {
            use futures_lite::StreamExt as _;
            let mut entries: Vec<String> = async_fs::read_dir(&self.dir)
                .await
                .unwrap()
                .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
                .filter(|name| name.starts_with("entry-"))
                .collect()
                .await;
            entries.sort();
            format!("entries: {}", entries.join(", "))
        }
    }

    #[tokio::test]
    async fn a_main_exclusive_command_names_its_choices_and_does_not_exist_for_a_subagent() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted");
        let mut builder = ToolRegistryBuilder::new();
        builder.main_exclusive(|main| {
            main.configure_terminal_bound_usage_tool("pick", |binding| PickTool {
                dir: binding.working_dir().to_path_buf(),
            });
        });
        let parent = tool.with_registry(Arc::new(
            builder.build(test_outputs(dir.path().join("outputs"))),
        ));

        // What the usage names is read when the call fails, not when the
        // terminal bound the command.
        std::fs::write(dir.path().join("entry-b"), "").unwrap();
        std::fs::write(dir.path().join("entry-a"), "").unwrap();
        let bare = parent.registry().query_tool_handler("pick", &[]).await;
        assert!(!bare.ok);
        assert_eq!(
            bare.error.as_deref(),
            Some(
                "missing required argument: entry\n\nentries: entry-a, entry-b\n\nRun `pick --help` for usage information."
            )
        );
        let picked = parent
            .registry()
            .query_tool_handler("pick", &["entry-a".to_string()])
            .await;
        assert_eq!(picked.payload.unwrap().render_for_cli(), "entry-a");

        let child = parent
            .subagent_without_grant()
            .await
            .expect("an empty grant is always given");
        let registry = child.registry();
        assert!(!registry.is_tool_configured("pick"));
        assert!(!registry.registered_tool_names().contains(&"pick".into()));
        assert!(registry.tool_help("pick").is_none());
        let refused = registry
            .query_tool_handler("pick", &["entry-a".to_string()])
            .await;
        assert_eq!(
            refused.error.as_deref(),
            Some("unknown command 'pick'. Run 'help' to see available commands.")
        );
        assert!(!child.to_dyn().has_command("pick"));
    }

    async fn query_control(
        registry: &ToolRegistry,
        name: &str,
        args: &[&str],
    ) -> serde_json::Value {
        let args = args.iter().map(ToString::to_string).collect::<Vec<_>>();
        serde_json::to_value(registry.query_tool_handler(name, &args).await)
            .expect("command envelope should serialize")
    }

    /// Background terminal arguments for `script`.
    #[cfg(unix)]
    fn background_args(description: &str, script: &str) -> TerminalArgs {
        TerminalArgs {
            description: description.to_string(),
            script: script.to_string(),
            language: ScriptLanguage::Shell,
            mode: TerminalExecutionMode::Sandboxed,
            ssh_server_id: None,
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            max_lines: 50,
            raw: false,
            timeout: 30,
            background: true,
        }
    }

    /// A parent terminal serving a registry and a child terminal launched from
    /// it without a grant. The directories live as long as the guards.
    #[cfg(unix)]
    async fn parent_and_child_terminals() -> (
        (
            tempfile::TempDir,
            crate::tool_runtime::tests::UnlockingTempDir,
        ),
        ConfiguredTestTool,
        ConfiguredTestTool,
    ) {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
                local: true,
                container: false,
                ssh: false,
            });
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let parent = tool.with_registry(registry);
        let child = parent
            .subagent_without_grant()
            .await
            .expect("an empty grant is always given");
        ((dir, cache), parent, child)
    }

    /// A command's task id, the file its background output goes to and a
    /// subagent's space are each named by a word leased from the terminal's
    /// allocator, which the subagent's terminal shares; the stored output and
    /// the space give their words back once the terminals holding them drop.
    #[cfg(unix)]
    #[tokio::test]
    async fn model_facing_names_are_leased_from_the_terminal_allocator() {
        let ids = crate::test_ids::RecordingIds::default();
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .with_id_allocator(ids.allocator())
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
                local: true,
                container: false,
                ssh: false,
            });
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let terminal = tool.with_registry(registry);

        let receiver = terminal.background_receiver();
        terminal
            .run_background(background_args("print a line", "echo leased"))
            .await
            .expect("terminal call should succeed");
        let [started] = <[_; 1]>::try_from(receiver.take_started()).expect("one started task");
        assert_eq!(ids.leased(), ["alfa", "bravo"]);
        assert_eq!(started.task_id, "alfa");
        assert_eq!(started.output_file.url, "outputs/bravo.txt");
        receiver.recv().await.expect("the job completes");

        let child = terminal
            .subagent_without_grant()
            .await
            .expect("an empty grant is always given");
        assert_eq!(ids.leased(), ["alfa", "bravo", "charlie"]);
        assert_eq!(
            child
                .working_dir()
                .file_name()
                .and_then(|name| name.to_str()),
            Some("charlie")
        );
        // The child's terminal and the commands bound to the parent lease
        // from the same allocator.
        let from_child = child.id_allocator().lease().expect("a free word");
        let from_binding = terminal
            .binding()
            .id_allocator()
            .lease()
            .expect("a free word");
        assert_eq!((&*from_child, &*from_binding), ("delta", "echo"));
        drop((from_child, from_binding));

        drop((child, terminal, receiver));
        for _ in 0..500 {
            let released = ids.released();
            if released.iter().any(|word| word == "bravo")
                && released.iter().any(|word| word == "charlie")
            {
                return;
            }
            async_io::Timer::after(Duration::from_millis(10)).await;
        }
        panic!(
            "the output file and the space keep their words: {:?} released",
            ids.released()
        );
    }

    /// A configured terminal leasing its model-facing names from `ids`.
    #[cfg(unix)]
    async fn terminal_leasing_from(
        dir: &Path,
        ids: AnyIdAllocator,
    ) -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
    ) {
        let (cache, shell_sessions) = prepared_test_registry().await;
        let tool = TerminalTool::new_exact(
            dir,
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .with_id_allocator(ids)
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted")
        .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
            local: true,
            container: false,
            ssh: false,
        });
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        (cache, tool.with_registry(registry))
    }

    /// A foreground command gives its task id back by the time its call
    /// returns, so commands run one after another never exhaust the words.
    #[cfg(unix)]
    #[tokio::test]
    async fn foreground_commands_one_after_another_never_exhaust_the_ids() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let ids = AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
        let (_cache, terminal) = terminal_leasing_from(dir.path(), ids.clone()).await;
        for run in 0..4 {
            let result = terminal
                .call(
                    TerminalArgs {
                        background: false,
                        ..background_args("finish at once", "exit 0")
                    },
                    ToolContext::new(),
                )
                .await
                .unwrap_or_else(|error| panic!("run {run} should get the one word: {error}"));
            assert!(!result.is_error(), "{result:?}");
        }
        assert!(
            terminal.job_registry().list().await.is_empty(),
            "a returned result leaves nothing to address"
        );
        assert_eq!(&*ids.lease().expect("river is free"), "river");
    }

    /// A background job keeps its task id while the agent can still address
    /// it, and gives it back once its completion is delivered; after that,
    /// the id answers as an unknown task and can be leased again.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_finished_background_job_gives_its_id_back_once_its_completion_is_delivered() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let ids = AnyIdAllocator::new(aither_core::WordAllocator::new(["river", "stone"]));
        let (_cache, terminal) = terminal_leasing_from(dir.path(), ids.clone()).await;
        let receiver = terminal.background_receiver();
        let jobs = terminal.job_registry();
        terminal
            .run_background(background_args("print a line", "echo done"))
            .await
            .expect("terminal call should succeed");
        let [started] = <[_; 1]>::try_from(receiver.take_started()).expect("one started task");
        assert_eq!(started.task_id, "river");
        assert_eq!(started.output_file.url, "outputs/stone.txt");

        let completed = tokio::time::timeout(Duration::from_secs(30), receiver.recv())
            .await
            .expect("the job should deliver its completion")
            .expect("the completion channel stays open");
        let pending = jobs
            .get_by_task_id("river")
            .await
            .expect("an undelivered completion keeps the job");
        assert!(pending.status.completion_pending(), "{pending:?}");
        assert!(
            ids.lease().is_err(),
            "the job and its output hold both words"
        );

        drop(completed);
        assert!(jobs.list().await.is_empty(), "a delivered job is forgotten");
        assert!(matches!(
            jobs.terminal_read("river", 0, 1024).await,
            Err(crate::TerminalReadError::Failed(_))
        ));
        assert!(!jobs.kill_by_task_id("river").await);
        // The job's flow lets go of the word as it ends.
        for _ in 0..500 {
            if let Ok(again) = ids.lease() {
                assert_eq!(&*again, "river");
                return;
            }
            async_io::Timer::after(Duration::from_millis(10)).await;
        }
        panic!("a delivered job keeps its word");
    }

    /// A child terminal's `terminal_input` and `terminal_read` reach its own
    /// job.
    #[cfg(unix)]
    #[tokio::test]
    async fn configured_child_terminal_input_and_read_address_child_jobs() {
        let (_dirs, _parent, child) = parent_and_child_terminals().await;

        // The echo job exits once its stdin line arrives, so its completion
        // event is the signal that its output exists; the read after it is the
        // first read of that task and cannot be refused as unchanged.
        let receiver = child.background_receiver();
        let result = child
            .run_background(background_args(
                "echo one stdin line",
                "read line; printf 'got %s\\n' \"$line\"",
            ))
            .await
            .expect("terminal call should succeed");
        let rendered = render_terminal_result(&result);
        assert!(
            rendered.contains("Started in background as task '"),
            "{rendered}"
        );
        let echo_id = started_task_id(&receiver);

        let input = query_control(
            child.registry(),
            "terminal_input",
            &["--task-id", &echo_id, "--input", "ping"],
        )
        .await;
        assert_eq!(input["ok"], true, "child terminal_input failed: {input}");

        // Held, so the job is still addressable while it is read.
        let _completed = wait_for_completed_task(&receiver, &echo_id).await;
        let echoed =
            query_control(child.registry(), "terminal_read", &["--task-id", &echo_id]).await;
        assert_eq!(echoed["ok"], true, "child terminal_read failed: {echoed}");
        assert!(echoed.to_string().contains("got ping"), "{echoed}");
    }

    /// A child terminal's job is invisible to the parent's controls and
    /// stopped by the child's own `terminal_kill`.
    #[cfg(unix)]
    #[tokio::test]
    async fn configured_child_terminal_kill_addresses_child_jobs() {
        let (_dirs, parent, child) = parent_and_child_terminals().await;
        let result = child
            .run_background(background_args("sleep", "sleep 30"))
            .await
            .expect("terminal call should succeed");
        let rendered = render_terminal_result(&result);
        assert!(
            rendered.contains("Started in background as task '"),
            "{rendered}"
        );
        let task_id = started_task_id(&child.background_receiver());
        let running =
            query_control(child.registry(), "terminal_read", &["--task-id", &task_id]).await;
        assert_eq!(running["ok"], true, "child terminal_read failed: {running}");
        assert!(running.to_string().contains("running"), "{running}");

        let parent_read =
            query_control(parent.registry(), "terminal_read", &["--task-id", &task_id]).await;
        assert_eq!(parent_read["ok"], false, "{parent_read}");
        assert!(
            parent_read["error"]
                .as_str()
                .is_some_and(|error| error.contains("unknown task_id")),
            "parent terminal_read must not see the child's task: {parent_read}"
        );
        let parent_kill =
            query_control(parent.registry(), "terminal_kill", &["--task-id", &task_id]).await;
        assert!(
            parent_kill
                .to_string()
                .contains("No running background task"),
            "parent terminal_kill must not reach the child's task: {parent_kill}"
        );

        let kill = query_control(child.registry(), "terminal_kill", &["--task-id", &task_id]).await;
        assert!(
            kill.to_string().contains("terminated"),
            "child terminal_kill should stop its task: {kill}"
        );
        let stopped =
            query_control(child.registry(), "terminal_read", &["--task-id", &task_id]).await;
        assert!(
            stopped.to_string().contains("was killed"),
            "child task should be reported killed: {stopped}"
        );
    }

    /// Under strict isolation a command in a `PATH` directory runs, the
    /// directory is not writable, and a directory off `PATH` stays unreadable.
    #[cfg(unix)]
    #[tokio::test]
    async fn path_directories_are_readable_and_executable_but_not_writable() {
        use std::os::unix::fs::PermissionsExt as _;
        let base = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(base.path()).unwrap();
        let on_path = root.join("on-path");
        let off_path = root.join("off-path");
        let missing = root.join("missing");
        for dir in [&on_path, &off_path] {
            std::fs::create_dir(dir).unwrap();
        }
        let tool = on_path.join("hello-tool");
        std::fs::write(&tool, "#!/bin/sh\necho hello-from-path\n").unwrap();
        std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::write(off_path.join("secret"), "secret\n").unwrap();

        let path = std::env::join_paths([&on_path, &missing, Path::new("relative")]).unwrap();
        let environment = vec![("PATH".to_string(), path.into_string().unwrap())];
        let grants = path_directory_grants(&environment).unwrap();
        assert_eq!(grants.len(), 1, "only the existing absolute directory");
        assert_eq!(grants[0].access(), Access::READ | Access::EXEC);

        let session = tempfile::tempdir().unwrap();
        let config = SandboxConfig::builder()
            .network(DenyAll)
            .working_dir(std::fs::canonicalize(session.path()).unwrap())
            .grants(grants)
            .security(SecurityConfig::interactive())
            .build();
        let sandbox = Sandbox::with_config_and_executor(config, executor_core::tokio::TokioGlobal)
            .await
            .expect("sandbox should initialize");
        let script = format!(
            "{tool}; echo x > {on}/planted 2>/dev/null && echo planted; cat {off}/secret 2>/dev/null; true",
            tool = tool.display(),
            on = on_path.display(),
            off = off_path.display(),
        );
        let output = sandbox
            .command("/bin/sh")
            .arg("-c")
            .arg(script)
            .output()
            .await
            .expect("the sandboxed script runs");
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), "hello-from-path", "{stdout}");
        assert!(!on_path.join("planted").exists());
    }

    // These four drive a real sandbox running `/bin/pwd`. `heel` reports
    // `UnsupportedPlatform` off Unix, and the binary they run does not exist
    // there either, so there is nothing for them to exercise on Windows.
    #[cfg(unix)]
    #[tokio::test]
    async fn sandboxed_command_output_executes_pwd() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let config = SandboxConfig::builder()
            .network(DenyAll)
            .working_dir(
                std::fs::canonicalize(dir.path()).unwrap_or_else(|_| dir.path().to_path_buf()),
            )
            .security(SecurityConfig::interactive())
            .build();
        let sandbox = Sandbox::with_config_and_executor(config, executor_core::tokio::TokioGlobal)
            .await
            .expect("sandbox should initialize");

        let output = sandbox
            .command("/bin/pwd")
            .output()
            .await
            .expect("sandbox command output should succeed");
        eprintln!("PWD OUTPUT STATUS: {:?}", output.status);
        eprintln!(
            "PWD OUTPUT STDOUT: {:?}",
            String::from_utf8_lossy(&output.stdout)
        );
        assert_eq!(output.status.code(), Some(0));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn sandboxed_terminal_executes_pwd() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted");
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let job_registry = tool.job_registry();
        let (startup_tx, _startup_rx) = async_channel::bounded(1);
        let result = execute_script_standalone(StandaloneExecution {
            working_dir: tool.working_dir().clone(),
            writable_paths: Vec::new(),
            readable_paths: Vec::new(),
            read_denied_paths: Vec::new(),
            git_dir: GitDirAccess::ReadWrite,
            env_source: None,
            executor: executor_core::tokio::TokioGlobal,
            registry,
            permission_handler: Arc::new(TestPermissionHandler::default()),
            job_registry,
            task_id: crate::test_ids::lease("probe"),
            execution_id: "exec-test".to_string(),
            background: false,
            carry: None,
            carried_dir: None,
            alert_tx: async_channel::unbounded().0,
            script: "/bin/pwd".to_string(),
            language: ScriptLanguage::Shell,
            mode: TerminalMode::Sandboxed,
            backend: ExecutionBackend::Local(tool.shell_sessions.local_tools().unwrap().clone()),
            stdin_alerts: None,
            lifetime: JobLifetime::Foreground {
                alerts: async_channel::unbounded().0,
            },
            background_startup: BackgroundStartup::new(startup_tx),
            network_audit: None,
            priority: ProcessPriority::default(),
            #[cfg(all(unix, feature = "jobserver"))]
            jobserver: None,
            heel: SharedHeelBinary::default(),
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            outputs: tool.output_store().clone(),
            max_lines: 50,
            raw: false,
        })
        .await;
        match result {
            Ok(ok) => {
                eprintln!("PWD RESULT: {ok:?}");
                assert_eq!(ok.exit_code, 0, "unexpected terminal result: {ok:?}");
            }
            Err(error) => panic!("sandboxed pwd should succeed, got error: {error}"),
        }
    }

    /// The policy a host gets from `SessionSandboxPolicy` is the one the
    /// terminal runs a command under: the grants name the writable and
    /// readable sets, the tools and the `uv` directory with the access the
    /// terminal gives them, and a sandboxed terminal command sees exactly
    /// the environment the policy lists and is confined by the same grants.
    #[cfg(unix)]
    #[tokio::test]
    #[allow(clippy::too_many_lines)]
    async fn session_policy_is_the_policy_the_terminal_runs_commands_under() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let writable = tempfile::tempdir().unwrap();
        let readable = tempfile::tempdir().unwrap();
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tools = shell_sessions.local_tools().unwrap().clone();
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted");
        let working_dir = tool.working_dir().clone();
        let writable_paths = vec![writable.path().to_path_buf()];
        let readable_paths = vec![readable.path().to_path_buf()];

        let policy = crate::SessionSandboxPolicy::new(
            &working_dir,
            &writable_paths,
            &readable_paths,
            GitDirAccess::ReadWrite,
            &tools,
        )
        .await
        .expect("policy builds");
        let access_of = |path: &Path| {
            let path = std::fs::canonicalize(path).unwrap();
            policy
                .grants()
                .iter()
                .find(|grant| grant.resolved_path().as_path() == path)
                .map(heel::Grant::access)
        };
        assert_eq!(
            access_of(writable.path()),
            Some(Access::WRITE | Access::EXEC)
        );
        assert_eq!(access_of(readable.path()), Some(Access::READ));
        assert_eq!(access_of(tools.bin_dir()), Some(Access::EXEC));
        if let Some(uv) = tools.uv_dir() {
            assert_eq!(access_of(uv), Some(Access::WRITE | Access::EXEC));
        }

        let names = ["HOME", "TMPDIR", "XDG_CACHE_HOME", "PATH", "PYTHONPATH"];
        let written = writable.path().join("written");
        let refused = readable.path().join("refused");
        let prints = names
            .iter()
            .map(|name| format!("echo \"${name}\""))
            .collect::<Vec<_>>()
            .join("; ");
        let script = format!(
            "{prints}; touch {} && echo write-ok; touch {} && echo read-write-ok; true",
            written.display(),
            refused.display(),
        );
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let job_registry = tool.job_registry();
        let (startup_tx, _startup_rx) = async_channel::bounded(1);
        let result = execute_script_standalone(StandaloneExecution {
            working_dir,
            writable_paths,
            readable_paths,
            read_denied_paths: Vec::new(),
            git_dir: GitDirAccess::ReadWrite,
            env_source: None,
            executor: executor_core::tokio::TokioGlobal,
            registry,
            permission_handler: Arc::new(TestPermissionHandler::default()),
            job_registry,
            task_id: crate::test_ids::lease("policy"),
            execution_id: "exec-policy".to_string(),
            background: false,
            carry: None,
            carried_dir: None,
            alert_tx: async_channel::unbounded().0,
            script,
            language: ScriptLanguage::Shell,
            mode: TerminalMode::Sandboxed,
            backend: ExecutionBackend::Local(tools),
            stdin_alerts: None,
            lifetime: JobLifetime::Foreground {
                alerts: async_channel::unbounded().0,
            },
            background_startup: BackgroundStartup::new(startup_tx),
            network_audit: None,
            priority: ProcessPriority::default(),
            #[cfg(all(unix, feature = "jobserver"))]
            jobserver: None,
            heel: SharedHeelBinary::default(),
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            outputs: tool.output_store().clone(),
            max_lines: 50,
            raw: false,
        })
        .await
        .expect("the sandboxed script runs");
        let stdout = output_text(&result.stdout).expect("inline stdout");
        let mut lines = stdout.lines();
        for name in names {
            let expected = policy
                .environment()
                .iter()
                .rev()
                .find_map(|(key, value)| (key == name).then_some(value.as_str()))
                .unwrap_or_else(|| panic!("the policy lists {name}"));
            assert_eq!(lines.next(), Some(expected), "{name} in the command");
        }
        assert_eq!(lines.next(), Some("write-ok"));
        assert_eq!(lines.next(), None, "a readable-only path stays read-only");
        assert!(written.exists() && !refused.exists());
    }

    /// Runs `script` in a sandboxed session with the given grants and returns
    /// its standard output. Needs a real `HEEL_BIN`.
    #[cfg(unix)]
    async fn sandboxed_stdout(
        writable_paths: Vec<PathBuf>,
        readable_paths: Vec<PathBuf>,
        script: String,
    ) -> String {
        sandboxed_stdout_with(
            GitDirAccess::ReadWrite,
            writable_paths,
            readable_paths,
            Vec::new(),
            script,
        )
        .await
    }

    /// [`sandboxed_stdout`] for a terminal whose grants give a writable
    /// worktree's git directory `git_dir` access.
    #[cfg(unix)]
    async fn sandboxed_stdout_with(
        git_dir: GitDirAccess,
        writable_paths: Vec<PathBuf>,
        readable_paths: Vec<PathBuf>,
        read_denied_paths: Vec<PathBuf>,
        script: String,
    ) -> String {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tools = shell_sessions.local_tools().unwrap().clone();
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted");
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let (startup_tx, _startup_rx) = async_channel::bounded(1);
        let result = execute_script_standalone(StandaloneExecution {
            working_dir: tool.working_dir().clone(),
            writable_paths,
            readable_paths,
            read_denied_paths,
            git_dir,
            env_source: None,
            executor: executor_core::tokio::TokioGlobal,
            registry,
            permission_handler: Arc::new(TestPermissionHandler::default()),
            job_registry: tool.job_registry(),
            task_id: crate::test_ids::lease("grants"),
            execution_id: "exec-grants".to_string(),
            background: false,
            carry: None,
            carried_dir: None,
            alert_tx: async_channel::unbounded().0,
            script,
            language: ScriptLanguage::Shell,
            mode: TerminalMode::Sandboxed,
            backend: ExecutionBackend::Local(tools),
            stdin_alerts: None,
            lifetime: JobLifetime::Foreground {
                alerts: async_channel::unbounded().0,
            },
            background_startup: BackgroundStartup::new(startup_tx),
            network_audit: None,
            priority: ProcessPriority::default(),
            #[cfg(all(unix, feature = "jobserver"))]
            jobserver: None,
            heel: SharedHeelBinary::default(),
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            outputs: tool.output_store().clone(),
            max_lines: 200,
            raw: false,
        })
        .await
        .expect("the sandboxed script runs");
        output_text(&result.stdout)
            .expect("inline stdout")
            .to_string()
    }

    /// A sandboxed command reads an ordinary file outside every granted path.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn sandboxed_commands_read_outside_the_granted_paths() {
        let outside = tempfile::tempdir().unwrap();
        let file = std::fs::canonicalize(outside.path())
            .unwrap()
            .join("ordinary.txt");
        std::fs::write(&file, "ordinary-content").unwrap();
        let stdout = sandboxed_stdout(
            Vec::new(),
            Vec::new(),
            format!("cat {} 2>&1; true", file.display()),
        )
        .await;
        assert!(stdout.contains("ordinary-content"), "{stdout}");
    }

    /// The credential table applies by absolute path although the sandbox
    /// sets `HOME` to the session directory. Checks the credential stores
    /// that exist in the real home.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn sandboxed_commands_cannot_read_home_credentials() {
        let home = PathBuf::from(std::env::var_os("HOME").expect("HOME is set"));
        let stores: Vec<PathBuf> = [".ssh", ".config/gh"]
            .into_iter()
            .map(|store| home.join(store))
            .filter(|store| store.is_dir())
            .collect();
        if stores.is_empty() {
            eprintln!("no ~/.ssh or ~/.config/gh in this home; nothing to deny");
            return;
        }
        for store in stores {
            assert!(
                std::fs::read_dir(&store).is_ok(),
                "the host reads {}",
                store.display()
            );
            let stdout = sandboxed_stdout(
                Vec::new(),
                Vec::new(),
                format!("ls {} 2>&1; echo rc=$?", store.display()),
            )
            .await;
            assert!(
                stdout.contains("rc=1") || stdout.contains("rc=2"),
                "{} must be unreadable: {stdout}",
                store.display()
            );
            assert!(
                stdout.to_lowercase().contains("not permitted")
                    || stdout.to_lowercase().contains("denied"),
                "{} must be refused by the sandbox: {stdout}",
                store.display()
            );
        }
    }

    /// A path the embedder adds is denied, while a sibling stays readable.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn sandboxed_commands_cannot_read_embedder_denied_paths() {
        let fake_home = tempfile::tempdir().unwrap();
        let fake_home = std::fs::canonicalize(fake_home.path()).unwrap();
        let secret = fake_home.join("vault");
        std::fs::create_dir(&secret).unwrap();
        std::fs::write(secret.join("key"), "vault-secret").unwrap();
        std::fs::write(fake_home.join("notes"), "plain-notes").unwrap();
        let stdout = sandboxed_stdout_with(
            GitDirAccess::ReadWrite,
            Vec::new(),
            Vec::new(),
            vec![secret.clone()],
            format!(
                "cat {}/key 2>&1; echo rc=$?; cat {}/notes 2>&1",
                secret.display(),
                fake_home.display()
            ),
        )
        .await;
        assert!(!stdout.contains("vault-secret"), "{stdout}");
        assert!(!stdout.contains("rc=0"), "{stdout}");
        assert!(stdout.contains("plain-notes"), "{stdout}");
    }

    /// Runs the host's `git` in `dir`; the caller's environment keeps the
    /// user's configuration out.
    #[cfg(unix)]
    fn host_git(dir: &Path, args: &[&str]) {
        let status = std::process::Command::new("git")
            .current_dir(dir)
            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
            .args(args)
            .status()
            .expect("git runs");
        assert!(status.success(), "git {args:?} in {}", dir.display());
    }

    /// A repository `main` with a linked worktree `linked`, under a fresh
    /// canonical temporary directory.
    #[cfg(unix)]
    fn repository_with_linked_worktree() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let base = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(base.path()).unwrap();
        let main = root.join("main");
        let linked = root.join("linked");
        std::fs::create_dir(&main).unwrap();
        host_git(&main, &["init", "-q", "-b", "main"]);
        host_git(&main, &["commit", "-q", "--allow-empty", "-m", "root"]);
        host_git(&main, &["worktree", "add", "-q", "../linked"]);
        (base, main, linked)
    }

    /// Under strict isolation git works in a granted linked worktree: its
    /// repository is outside the worktree, and the session grants it after
    /// git's back-links confirm the pointer.
    #[cfg(unix)]
    #[tokio::test]
    async fn git_commits_in_a_granted_linked_worktree() {
        let (_base, main, linked) = repository_with_linked_worktree();
        let script = format!(
            "cd {linked} && git status --short 2>&1 && echo changed > file && git add file 2>&1 \
             && git -c user.name=t -c user.email=t@t commit -q -m inside 2>&1 && echo committed; true",
            linked = linked.display(),
        );
        let stdout = sandboxed_stdout(vec![linked.clone()], Vec::new(), script).await;
        assert_eq!(stdout.lines().last(), Some("committed"), "{stdout}");
        let subject = std::process::Command::new("git")
            .current_dir(&main)
            .args(["log", "-1", "--format=%s", "linked"])
            .output()
            .unwrap();
        assert_eq!(String::from_utf8_lossy(&subject.stdout).trim(), "inside");
    }

    /// A subagent's terminal holding a plain worktree grant reads the main
    /// repository's git data and cannot write it: `git commit` fails and the
    /// branch stays where it was. The session's own terminal commits (above).
    #[cfg(unix)]
    #[tokio::test]
    async fn a_derived_terminal_reads_but_cannot_commit_in_a_plain_worktree_grant() {
        let (_base, main, linked) = repository_with_linked_worktree();
        let tip = |branch: &str| {
            let output = std::process::Command::new("git")
                .current_dir(&main)
                .args(["rev-parse", branch])
                .output()
                .unwrap();
            String::from_utf8_lossy(&output.stdout).trim().to_string()
        };
        let before = tip("linked");
        let script = format!(
            "cd {linked} && git status --short >/dev/null 2>&1 && echo status-ok; \
             git log -1 --format=%s 2>&1 | head -n 1; \
             echo changed > file; git add file 2>&1; \
             git -c user.name=t -c user.email=t@t commit -q -m inside 2>&1 && echo committed; true",
            linked = linked.display(),
        );
        let stdout = sandboxed_stdout_with(
            GitDirAccess::ReadOnly,
            vec![linked.clone()],
            Vec::new(),
            Vec::new(),
            script,
        )
        .await;
        assert!(stdout.lines().any(|line| line == "status-ok"), "{stdout}");
        assert!(stdout.lines().any(|line| line == "root"), "{stdout}");
        assert!(!stdout.contains("committed"), "{stdout}");
        assert_eq!(tip("linked"), before, "{stdout}");
    }

    /// The grants a subagent's terminal derives give worktree git data read
    /// access; the session's own give it write access.
    #[test]
    fn only_derived_grants_read_worktree_git_data() {
        let parent = TerminalGrants::new();
        assert_eq!(parent.snapshot().git_dir, GitDirAccess::ReadWrite);
        let derived = TerminalGrants::derived(&parent, Vec::new(), vec![PathBuf::from("/w")]);
        assert_eq!(derived.snapshot().git_dir, GitDirAccess::ReadOnly);
    }

    /// In a read-write repository the persistence paths stay unwritable, in a
    /// linked worktree's common git directory too, while git still commits.
    #[cfg(unix)]
    #[tokio::test]
    async fn git_persistence_paths_are_unwritable_in_granted_repositories() {
        let (_base, main, linked) = repository_with_linked_worktree();
        let attempt = |repository: &Path, work: &Path| {
            format!(
                "cd {work} && echo '#!/bin/sh' > {hook} 2>/dev/null && echo hook-written; \
                 echo '[alias]' >> {config} 2>/dev/null && echo config-written; \
                 echo changed > file && git add file 2>&1 \
                 && git -c user.name=t -c user.email=t@t commit -q -m inside 2>&1 && echo committed; true",
                work = work.display(),
                hook = repository.join(".git/hooks/pre-commit").display(),
                config = repository.join(".git/config").display(),
            )
        };
        for (repository, work, writable) in [
            (&main, &main, vec![main.clone()]),
            (&main, &linked, vec![linked.clone()]),
        ] {
            let stdout = sandboxed_stdout(writable, Vec::new(), attempt(repository, work)).await;
            assert_eq!(stdout.lines().last(), Some("committed"), "{stdout}");
            assert!(!stdout.contains("written"), "{stdout}");
            assert!(!main.join(".git/hooks/pre-commit").exists());
        }
    }

    /// `uv` marks its cache buckets with a `.git` entry: the prepared
    /// runtime's cache takes that, while a granted repository still refuses
    /// git's config. Judged by outcome, since platforms differ on whether the
    /// bare `.git` directory itself is refused.
    #[cfg(unix)]
    #[tokio::test]
    async fn uv_cache_may_hold_git_entries_and_a_granted_repository_may_not() {
        let base = tempfile::tempdir().unwrap();
        let granted = std::fs::canonicalize(base.path()).unwrap().join("repo");
        std::fs::create_dir(&granted).unwrap();
        let script = format!(
            "mkdir -p \"$UV_CACHE_DIR/x\" && mkdir \"$UV_CACHE_DIR/x/.git\" 2>&1 && echo cache-written; \
             mkdir -p {repo}/.git 2>/dev/null; touch {repo}/.git/config 2>/dev/null && echo repo-written; true",
            repo = granted.display(),
        );
        let stdout = sandboxed_stdout(vec![granted.clone()], Vec::new(), script).await;
        assert!(
            stdout.lines().any(|line| line == "cache-written"),
            "{stdout}"
        );
        assert!(!stdout.contains("repo-written"), "{stdout}");
        assert!(!granted.join(".git/config").exists(), "{stdout}");
    }

    /// Cargo's git cache keeps the `.git/hooks` rule off, and nothing else of
    /// a toolchain home is exempt.
    #[cfg(unix)]
    #[tokio::test]
    async fn cargo_git_cache_is_the_only_toolchain_home_denylist_exception() {
        let (_base, main, _linked) = repository_with_linked_worktree();
        let session = tempfile::tempdir().unwrap();
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tools = shell_sessions.local_tools().unwrap().clone();
        let denylist = session_write_denylist(session.path(), &tools);
        // The cache directory appears with the first `uv` run; its parent
        // is canonical from preparation.
        let uv_cache = tools.uv_environment().unwrap().cache;
        let cargo_git = host_toolchain_homes()
            .find(|(name, _)| *name == "CARGO_HOME")
            .map(|(_, home)| std::fs::canonicalize(home).unwrap().join("git"))
            .expect("the test host has a cargo home");
        assert_eq!(
            denylist.exempt(),
            [
                std::fs::canonicalize(session.path()).unwrap(),
                cargo_git.clone(),
                uv_cache
            ]
        );

        let checkout = cargo_git.join(format!(
            "checkouts/aither-denylist-test-{}/rev",
            std::process::id()
        ));
        std::fs::create_dir_all(&checkout).unwrap();
        host_git(&checkout, &["init", "-q"]);
        let script = format!(
            "echo x > {cache}/hooks/update 2>&1 && echo cache-written; \
             echo x > {repo}/.git/hooks/update 2>/dev/null && echo repo-written; true",
            cache = checkout.join(".git").display(),
            repo = main.display(),
        );
        let stdout = sandboxed_stdout(vec![main.clone()], Vec::new(), script).await;
        std::fs::remove_dir_all(checkout.parent().unwrap()).unwrap();
        assert_eq!(stdout.lines().last(), Some("cache-written"), "{stdout}");
        assert!(!stdout.contains("repo-written"), "{stdout}");
    }

    /// The persistence table forbids creating a `.git` in a granted
    /// directory: a new repository there is refused, one in the session
    /// directory (see the committing subagent's clone test) is not.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_new_repository_in_a_granted_workdir_is_refused() {
        let base = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(base.path()).unwrap();
        let script = format!(
            "cd {root} && if git init fresh >/dev/null 2>&1; then echo init-succeeded; fi; true",
            root = root.display()
        );
        let stdout = sandboxed_stdout(vec![root.clone()], Vec::new(), script).await;
        assert!(!stdout.contains("init-succeeded"), "{stdout}");
        assert!(!root.join("fresh/.git/config").exists(), "{stdout}");
    }

    /// A readable linked worktree brings its repository with read access:
    /// git reads, and nothing is written.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_readable_linked_worktree_reads_its_repository() {
        let (_base, _main, linked) = repository_with_linked_worktree();
        let script = format!(
            "cd {linked} && git log -1 --format=%s 2>&1; true",
            linked = linked.display(),
        );
        let stdout = sandboxed_stdout(Vec::new(), vec![linked.clone()], script).await;
        assert_eq!(stdout.lines().last(), Some("root"), "{stdout}");
    }

    /// A `.git` file anyone can write names whatever it likes: without
    /// matching back-links it adds no grant, and git there gets nothing of
    /// the repository it points at.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_forged_git_pointer_adds_no_grant() {
        let (base, main, linked) = repository_with_linked_worktree();
        let root = std::fs::canonicalize(base.path()).unwrap();
        let entry = main.join(".git/worktrees/linked");
        let forged = root.join("forged");
        std::fs::create_dir(&forged).unwrap();
        // The real entry of another worktree: its `gitdir` names `linked`,
        // not `forged`.
        std::fs::write(
            forged.join(".git"),
            format!("gitdir: {}\n", entry.display()),
        )
        .unwrap();
        // A pointer straight at the repository, and one at nothing.
        let direct = root.join("direct");
        std::fs::create_dir(&direct).unwrap();
        std::fs::write(
            direct.join(".git"),
            format!("gitdir: {}\n", main.join(".git").display()),
        )
        .unwrap();
        let writable = vec![forged.clone(), direct.clone()];
        for path in &writable {
            assert!(
                crate::subagent::confirmed_common_dir(path).await.is_none(),
                "{} confirmed",
                path.display()
            );
        }
        assert_eq!(
            crate::subagent::confirmed_common_dir(&linked).await,
            Some(main.join(".git")),
        );
        assert_eq!(
            linked_worktree_grants(&writable, &[], GitDirAccess::ReadWrite)
                .await
                .unwrap()
                .len(),
            0
        );

        // Reads are open under the read denylist policy, so the grant is
        // probed by what it would make writable: the repository, directly and
        // through git run in the forged worktree.
        let planted = main.join(".git/forged_probe");
        let script = format!(
            "echo x > {planted} 2>&1; git -C {forged} update-ref refs/heads/forged_probe HEAD 2>&1; \
             git -C {direct} update-ref refs/heads/direct_probe HEAD 2>&1; true",
            planted = planted.display(),
            forged = forged.display(),
            direct = direct.display(),
        );
        sandboxed_stdout(writable, Vec::new(), script).await;
        assert!(!planted.exists(), "the repository became writable");
        for branch in ["forged_probe", "direct_probe"] {
            assert!(
                !main.join(".git/refs/heads").join(branch).exists(),
                "git wrote {branch} into the repository through a forged pointer"
            );
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn failed_command_reports_nonzero_exit_code() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
                local: true,
                container: false,
                ssh: false,
            });
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let tool = tool.with_registry(registry);

        let result = tool
            .call(
                TerminalArgs {
                    description: "exit with non-zero status".to_string(),
                    script: "exit 42".to_string(),
                    language: ScriptLanguage::Shell,
                    mode: TerminalExecutionMode::Sandboxed,
                    ssh_server_id: None,
                    expect: OutputFormat::Text,
                    resolution: MediaResolution::Auto,
                    max_lines: 50,
                    raw: false,
                    timeout: 30,
                    background: false,
                },
                ToolContext::new(),
            )
            .await
            .expect("terminal call should not be promoted to transport error on non-zero exit");

        assert!(
            !result.is_error(),
            "non-zero exit must not produce ToolResult::Error, got: {result:?}"
        );
        assert_eq!(
            render_terminal_result(&result),
            "(no output)\nExit code: 42.\n"
        );
        assert_eq!(
            result.command().map(|command| &command.outcome),
            Some(&CommandOutcome::Exited { code: 42 })
        );
    }

    /// What a host reading the registry can tell: whether the session still
    /// owes its agent a turn.
    fn host_sees_owed_turn(jobs: &[crate::JobInfo]) -> bool {
        jobs.iter()
            .any(|job| job.status == JobStatus::Running || job.status.completion_pending())
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_detached_job_reads_pending_until_its_completion_is_taken() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
                local: true,
                container: false,
                ssh: false,
            });
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let tool = tool.with_registry(registry);
        let receiver = tool.background_receiver();
        let jobs = tool.job_registry();

        tool.run_background(TerminalArgs {
            description: "finish at once".to_string(),
            script: "exit 3".to_string(),
            language: ScriptLanguage::Shell,
            mode: TerminalExecutionMode::Sandboxed,
            ssh_server_id: None,
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            max_lines: 50,
            raw: false,
            timeout: 30,
            background: true,
        })
        .await
        .expect("terminal call should succeed");
        let task_id = started_task_id(&receiver);

        // The agent's receiver is the gate: the completion it receives is
        // held, not yet taken, while the host reads the registry.
        let completed = tokio::time::timeout(Duration::from_secs(30), receiver.recv())
            .await
            .expect("the job should deliver its completion")
            .expect("the completion channel stays open");
        assert_eq!(completed.task_id, task_id);
        let held = jobs.list().await;
        assert!(
            held.iter().all(|job| job.status != JobStatus::Running),
            "the job has finished: {held:?}"
        );
        assert!(
            host_sees_owed_turn(&held),
            "a finished job whose completion the agent has not taken reads as done: {held:?}"
        );

        // The agent takes the completion; the registry serves the take
        // before the list that follows it, and forgets the job.
        drop(completed);
        let taken = jobs.list().await;
        assert!(taken.is_empty(), "{taken:?}");
        assert!(!host_sees_owed_turn(&taken), "{taken:?}");
        assert!(
            jobs.get_by_task_id(&task_id).await.is_none(),
            "a delivered job's id is unknown"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn background_terminal_accepts_terminal_input() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
                local: true,
                container: false,
                ssh: false,
            });
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let tool = tool.with_registry(registry);
        let background_receiver = tool.background_receiver();
        let input_tool = InputTerminalTool::new(tool.job_registry());

        let result = tool
            .run_background(TerminalArgs {
                description: "wait for terminal input and echo it back".to_string(),
                script: "printf 'name? '; read name; printf 'hello %s\\n' \"$name\"".to_string(),
                language: ScriptLanguage::Shell,
                mode: TerminalExecutionMode::Sandboxed,
                ssh_server_id: None,
                expect: OutputFormat::Text,
                resolution: MediaResolution::Auto,
                max_lines: 50,
                raw: false,
                timeout: 30,
                background: true,
            })
            .await
            .expect("terminal call should succeed");

        let rendered = render_terminal_result(&result);
        assert!(
            rendered.contains("Started in background as task '"),
            "{rendered}"
        );
        let task_id = started_task_id(&tool.background_receiver());

        input_tool
            .call(
                InputTerminalArgs {
                    task_id: task_id.clone(),
                    input: "lexo".to_string(),
                    append_newline: true,
                },
                ToolContext::new(),
            )
            .await
            .expect("terminal_input should succeed");

        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
        let terminal_result = completed
            .result
            .expect("background task should complete successfully after stdin input");
        let stdout =
            output_text(&terminal_result.stdout).expect("completed task should include stdout");
        assert!(
            stdout.contains("hello lexo"),
            "stdin input should reach the terminal process, got: {stdout}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn killing_background_terminal_kills_descendant_processes() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
                local: true,
                container: false,
                ssh: false,
            });
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let tool = tool.with_registry(registry);
        let child_pid_path = dir.path().join("child.pid");

        let result = tool
            .run_background(TerminalArgs {
                description: "start a descendant process".to_string(),
                script: "sleep 30 & echo $! > child.pid; wait".to_string(),
                language: ScriptLanguage::Shell,
                mode: TerminalExecutionMode::Sandboxed,
                ssh_server_id: None,
                expect: OutputFormat::Text,
                resolution: MediaResolution::Auto,
                max_lines: 50,
                raw: false,
                timeout: 30,
                background: true,
            })
            .await
            .expect("terminal call should succeed");
        let rendered = render_terminal_result(&result);
        assert!(
            rendered.contains("Started in background as task '"),
            "{rendered}"
        );

        let mut child_pid = None;
        for _ in 0..100 {
            // `echo $! > child.pid` creates the file before writing to it,
            // so a successful read can still yield empty or partial
            // content — poll until the pid actually parses.
            let parsed = match async_fs::read_to_string(&child_pid_path).await {
                Ok(value) => value.trim().parse::<i32>().ok(),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
                Err(error) => panic!("failed to read child pid: {error}"),
            };
            if let Some(pid) = parsed {
                child_pid = Some(pid);
                break;
            }
            async_io::Timer::after(std::time::Duration::from_millis(20)).await;
        }
        let child_pid = child_pid.expect("descendant pid should be written before timeout");

        assert_eq!(tool.job_registry().kill_running().await, 1);

        for _ in 0..100 {
            let exists = unsafe { libc::kill(child_pid, 0) } == 0;
            if !exists {
                return;
            }
            async_io::Timer::after(std::time::Duration::from_millis(20)).await;
        }
        panic!("descendant process {child_pid} survived terminal cancellation");
    }

    /// A foreground command blocked on stdin sees no EOF: every job owns a
    /// live stdin pipe, so at the foreground window the call promotes it to
    /// a background task the model feeds through `terminal_input`.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn foreground_command_blocked_on_stdin_promotes_at_the_window() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(1),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;
        let background_receiver = tool.background_receiver();

        let result = tool
            .call(
                terminal_args("read all of stdin", "cat"),
                ToolContext::new(),
            )
            .await
            .expect("terminal call should succeed");

        let command = result.command().expect("terminal returns a command result");
        let CommandOutcome::Running { task_id, .. } = &command.outcome else {
            panic!(
                "cat blocked on stdin must promote to a task, got {:?}",
                command.outcome
            );
        };
        assert_eq!(started_task_id(&background_receiver), *task_id);

        assert!(
            tool.job_registry().kill_by_task_id(task_id).await,
            "the promoted task must still be running"
        );
    }

    #[cfg(unix)]
    fn terminal_args(description: &str, script: &str) -> TerminalArgs {
        TerminalArgs {
            description: description.to_string(),
            script: script.to_string(),
            language: ScriptLanguage::Shell,
            mode: TerminalExecutionMode::Sandboxed,
            ssh_server_id: None,
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            max_lines: 50,
            raw: false,
            timeout: 30,
            background: false,
        }
    }

    /// Starts `script` as a background job and returns its task id.
    #[cfg(unix)]
    async fn start_background_job(
        tool: &TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
        script: &str,
    ) -> String {
        let result = tool
            .run_background(TerminalArgs {
                background: true,
                ..terminal_args("background job", script)
            })
            .await
            .expect("terminal should start the job");
        match result.command().map(|command| &command.outcome) {
            Some(CommandOutcome::Running { task_id, .. }) => task_id.clone(),
            other => panic!("background job needs a task id, got {other:?}"),
        }
    }

    /// Python terminal arguments for `code`.
    #[cfg(unix)]
    fn python_args(code: &str) -> TerminalArgs {
        TerminalArgs {
            language: ScriptLanguage::Python,
            ..terminal_args("run python", code)
        }
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn python_runs_and_a_raised_exception_carries_file_line_numbers() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(20),
            Duration::from_secs(60),
            Duration::from_secs(600),
        )
        .await;

        let ok = tool
            .call(
                python_args("import sys\nprint(sys.version_info[0] * 6)"),
                ToolContext::new(),
            )
            .await
            .expect("python should run");
        let ok = ok.command().expect("a command result");
        assert_eq!(ok.outcome, CommandOutcome::Exited { code: 0 });
        assert_eq!(output_text(&ok.stdout).map(str::trim), Some("18"));

        let failed = tool
            .call(
                python_args("x = 1\nraise ValueError('boom')"),
                ToolContext::new(),
            )
            .await
            .expect("a raising script is still a result");
        let failed = failed.command().expect("a command result");
        assert_eq!(failed.outcome, CommandOutcome::Exited { code: 1 });
        let stderr = failed
            .stderr
            .as_ref()
            .and_then(output_text)
            .expect("the traceback is on stderr");
        assert!(stderr.contains("line 2"), "{stderr}");
        assert!(stderr.contains("ValueError: boom"), "{stderr}");
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn python_background_job_is_read_and_killed_like_a_shell_job() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(60),
            Duration::from_secs(600),
        )
        .await;
        let receiver = tool.background_receiver();
        let result = tool
            .run_background(python_args(
                "import time\nprint('ready', flush=True)\ntime.sleep(60)",
            ))
            .await
            .expect("python should start detached");
        let task_id = match result.command().map(|command| &command.outcome) {
            Some(CommandOutcome::Running { task_id, .. }) => task_id.clone(),
            other => panic!("a background job needs a task id, got {other:?}"),
        };
        assert_eq!(started_task_id(&receiver), task_id);

        let jobs = tool.job_registry().list().await;
        let job = jobs
            .iter()
            .find(|job| job.task_id == task_id)
            .expect("the job is recorded");
        assert_eq!(job.language, ScriptLanguage::Python);
        assert!(job.script.contains("time.sleep(60)"), "{}", job.script);

        let deadline = std::time::Instant::now() + Duration::from_secs(20);
        loop {
            let read =
                query_control(tool.registry(), "terminal_read", &["--task-id", &task_id]).await;
            if read.to_string().contains("ready") {
                break;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "the job never printed: {read}"
            );
            tokio::time::sleep(Duration::from_millis(100)).await;
        }

        assert!(tool.job_registry().kill_by_task_id(&task_id).await);
        wait_for_completed_task(&receiver, &task_id).await;
    }

    /// Records the unsafe approvals it is asked for and refuses them.
    #[derive(Default)]
    struct RecordingApprovals {
        asked: Mutex<Vec<(String, ScriptLanguage)>>,
    }

    impl PermissionHandler for RecordingApprovals {
        fn check(
            &self,
            _mode: TerminalMode,
            script: &str,
            language: ScriptLanguage,
        ) -> impl std::future::Future<Output = Result<bool, PermissionError>> + Send {
            self.asked
                .lock()
                .unwrap()
                .push((script.to_string(), language));
            std::future::ready(Ok(false))
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn unsafe_python_asks_for_approval_with_its_code_and_language() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = TerminalTool::new_exact(
            dir.path(),
            RecordingApprovals::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted");
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        let tool = tool.with_registry(registry);

        let code = "import os\nprint(os.getcwd())";
        let refused = tool
            .call(
                TerminalArgs {
                    mode: TerminalExecutionMode::Unsafe,
                    ..python_args(code)
                },
                ToolContext::new(),
            )
            .await;
        assert!(refused.is_err(), "the refused approval stops the run");
        assert_eq!(
            *tool.permission_handler.asked.lock().unwrap(),
            [(code.to_string(), ScriptLanguage::Python)]
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn omitting_language_runs_shell() {
        let args: TerminalArgs = serde_json::from_value(serde_json::json!({
            "description": "print",
            "script": "echo $((6 * 7))",
            "timeout": 30,
        }))
        .expect("language is optional");
        assert_eq!(args.language, ScriptLanguage::Shell);

        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(20),
            Duration::from_secs(60),
            Duration::from_secs(600),
        )
        .await;
        let result = tool
            .call(args, ToolContext::new())
            .await
            .expect("shell should run");
        let command = result.command().expect("a command result");
        assert_eq!(output_text(&command.stdout).map(str::trim), Some("42"));
    }

    /// Collects the alerts that arrive within `window`.
    #[cfg(unix)]
    async fn alerts_within(receiver: &BackgroundTaskReceiver, window: Duration) -> Vec<JobAlert> {
        let deadline = std::time::Instant::now() + window;
        let mut alerts = Vec::new();
        while std::time::Instant::now() < deadline {
            alerts.extend(receiver.take_job_alerts());
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        alerts
    }

    /// A foreground container command gets a live stdin pipe like every
    /// other job: no EOF shortcut. The exec's stdin channel stays open and
    /// its blocked watch channel is wired, so a reader can be fed through
    /// `terminal_input` once the call promotes.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn container_foreground_command_gets_a_live_stdin_pipe() {
        /// A container executor that asserts stdin is a watched live pipe.
        struct ForegroundStdinPipeExec;

        impl crate::ContainerExec for ForegroundStdinPipeExec {
            async fn exec(
                &self,
                _container_id: &str,
                _script: &str,
                _working_dir: &str,
                _kill_rx: Receiver<()>,
                stdin_rx: Receiver<Vec<u8>>,
                _lifetime: ExecLifetime,
            ) -> Result<ContainerExecOutcome, String> {
                let eof = futures_lite::future::or(async { Some(stdin_rx.recv().await) }, async {
                    async_io::Timer::after(Duration::from_secs(5)).await;
                    None
                })
                .await
                .expect("a foreground exec's stdin must be EOF at once, not left open");
                assert!(eof.is_err(), "a foreground exec's stdin must carry no data");
                Ok(ContainerExecOutcome::Completed {
                    output: std::process::Output {
                        status: std::os::unix::process::ExitStatusExt::from_raw(0),
                        stdout: Vec::new(),
                        stderr: Vec::new(),
                    },
                    killed: Vec::new(),
                })
            }

            fn exec_streamed(
                &self,
                _container_id: &str,
                _script: &str,
                _working_dir: &str,
                _kill_rx: Receiver<()>,
                _stdin_rx: Receiver<Vec<u8>>,
                _stdout: Sender<Vec<u8>>,
            ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
            {
                std::future::ready(Err("a foreground command does not stream".to_string()))
            }
        }

        let dir = tempfile::tempdir().expect("temp dir should be created");
        let registry = Arc::new(ToolRegistryBuilder::new().build(test_outputs(dir.path())));
        let (job_registry, job_registry_service) = job_registry_channel();
        tokio::spawn(async move { job_registry_service.serve().await });
        let container_tools =
            crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools());
        let runtime = ContainerShellRuntime::new(
            "aither-test-foreground-stdin",
            crate::ContainerIpcRoute::new(
                "host.docker.internal",
                crate::BridgeAddress::try_from(std::net::IpAddr::from([127, 0, 0, 1]))
                    .expect("loopback binds the bridge"),
            ),
            crate::AnyContainerExec::new(Arc::new(ForegroundStdinPipeExec)),
        );
        let (startup_tx, _startup_rx) = async_channel::bounded(1);
        let (alert_tx, _alert_rx) = async_channel::unbounded();
        let (_pid, output) = execute_container_background(ContainerBackgroundExecution {
            executor: executor_core::tokio::TokioGlobal,
            env_source: &None,
            registry: &registry,
            task_id: &crate::test_ids::lease("probe"),
            execution_id: "exec-test",
            script: "cat",
            language: ScriptLanguage::Shell,
            mode: TerminalMode::Sandboxed,
            container_runtime: &runtime,
            prepared_tools: &container_tools,
            ipc_commands: &[],
            job_registry: &job_registry,
            stdin_alerts: Some(StdinAlerts {
                tx: alert_tx.clone(),
                task_id: "probe".to_string(),
                script: "cat".to_string(),
            }),
            lifetime: JobLifetime::Foreground { alerts: alert_tx },
            background_startup: &BackgroundStartup::new(startup_tx),
            priority: ProcessPriority::default(),
            confinement: None,
            carry: None,
            #[cfg(all(unix, feature = "jobserver"))]
            job_fifo: None,
        })
        .await
        .expect("a foreground container exec should complete");
        assert_eq!(output.status.code(), Some(0));
    }

    /// A subagent's command in a container gets write access to its
    /// jobserver fifo on top of its confinement; an unconfined command gets
    /// no grants at all.
    #[cfg(all(unix, feature = "jobserver"))]
    #[test]
    fn container_job_fifo_is_granted_to_a_confined_command() {
        let fifo = ContainerPath::new("/tmp/aither-jobserver-1.fifo").unwrap();
        let confinement = ContainerConfinement {
            working_dir: ContainerPath::new("/workspace/.subagents/a").unwrap(),
            writable: vec![ContainerPath::new("/workspace/.subagents/a").unwrap()],
        };
        assert_eq!(job_confinement(None, Some(&fifo)), None);
        let confined = job_confinement(Some(&confinement), Some(&fifo)).unwrap();
        let tools_dir = container_tools_dir();
        let wrapped = wrap_container_script(
            "make",
            &[],
            None,
            ProcessPriority::default(),
            &tools_dir,
            "/workspace",
            Some(&confined),
        )
        .unwrap();
        assert!(
            wrapped.contains(
                "--grant '/workspace/.subagents/a=rw' --grant '/tmp/aither-jobserver-1.fifo=rw'"
            ),
            "{wrapped}"
        );
        assert_eq!(
            job_confinement(Some(&confinement), None).as_ref(),
            Some(&confinement)
        );
    }

    /// With a pool configured, a container command's script exports the
    /// jobserver variables naming its own fifo inside the container, and the
    /// fifo's relay is told once the command's exec ends.
    /// Captures each command's script; plays a jobserver relay that reports
    /// ready and records what the host tells it.
    #[cfg(all(unix, feature = "jobserver"))]
    struct CapturingExec {
        scripts: Sender<String>,
        relay_heard: Sender<Vec<u8>>,
    }

    #[cfg(all(unix, feature = "jobserver"))]
    impl crate::ContainerExec for CapturingExec {
        async fn exec(
            &self,
            _container_id: &str,
            script: &str,
            _working_dir: &str,
            _kill_rx: Receiver<()>,
            _stdin_rx: Receiver<Vec<u8>>,
            _lifetime: ExecLifetime,
        ) -> Result<ContainerExecOutcome, String> {
            self.scripts.send(script.to_string()).await.unwrap();
            Ok(ContainerExecOutcome::Completed {
                output: std::process::Output {
                    status: std::os::unix::process::ExitStatusExt::from_raw(0),
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                },
                killed: Vec::new(),
            })
        }

        async fn exec_streamed(
            &self,
            _container_id: &str,
            _script: &str,
            _working_dir: &str,
            _kill_rx: Receiver<()>,
            stdin_rx: Receiver<Vec<u8>>,
            stdout: Sender<Vec<u8>>,
        ) -> Result<ContainerExecOutcome, String> {
            stdout.send(b"R".to_vec()).await.unwrap();
            while let Ok(message) = stdin_rx.recv().await {
                let finished = message == b"F";
                self.relay_heard.send(message).await.unwrap();
                if finished {
                    break;
                }
            }
            Err("the relay exits".to_string())
        }
    }

    #[cfg(all(unix, feature = "jobserver"))]
    #[tokio::test(flavor = "multi_thread")]
    async fn container_command_environment_names_its_own_fifo() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let pool = crate::jobserver::JobPool::create_fifo(dir.path().join("pool.fifo"), 2)
            .expect("pool should be created");
        let (broker, service) =
            crate::jobserver::job_broker_channel(pool, dir.path().join("commands"))
                .expect("broker should start");
        tokio::spawn(async move { service.serve().await });
        let registry = Arc::new(ToolRegistryBuilder::new().build(test_outputs(dir.path())));
        let (job_registry, job_registry_service) = job_registry_channel();
        tokio::spawn(async move { job_registry_service.serve().await });
        let container_tools =
            crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools());
        let (scripts_tx, scripts) = async_channel::unbounded();
        let (heard_tx, heard) = async_channel::unbounded();
        let runtime = ContainerShellRuntime::new(
            "aither-test-jobserver",
            crate::ContainerIpcRoute::new(
                "host.docker.internal",
                crate::BridgeAddress::try_from(std::net::IpAddr::from([127, 0, 0, 1]))
                    .expect("loopback binds the bridge"),
            ),
            crate::AnyContainerExec::new(Arc::new(CapturingExec {
                scripts: scripts_tx,
                relay_heard: heard_tx,
            })),
        );
        let job_fifo = crate::container_jobserver::open_container_job_fifo(
            &broker,
            &runtime,
            &container_tools.bin_dir().join("python3"),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("the relay reports ready");
        let fifo_path = job_fifo.path().clone();
        let (startup_tx, _startup_rx) = async_channel::bounded(1);
        let (alert_tx, _alert_rx) = async_channel::unbounded();
        execute_container_background(ContainerBackgroundExecution {
            executor: executor_core::tokio::TokioGlobal,
            env_source: &None,
            registry: &registry,
            task_id: &crate::test_ids::lease("probe"),
            execution_id: "exec-test",
            script: "make",
            language: ScriptLanguage::Shell,
            mode: TerminalMode::Sandboxed,
            container_runtime: &runtime,
            prepared_tools: &container_tools,
            ipc_commands: &[],
            job_registry: &job_registry,
            stdin_alerts: None,
            lifetime: JobLifetime::Foreground { alerts: alert_tx },
            background_startup: &BackgroundStartup::new(startup_tx),
            priority: ProcessPriority::default(),
            confinement: None,
            carry: None,
            job_fifo: Some(job_fifo),
        })
        .await
        .expect("the container exec completes");

        let script = scripts.recv().await.expect("the command ran");
        let flags = format!("'-j --jobserver-auth=fifo:{fifo_path}'");
        for name in ["MAKEFLAGS", "CARGO_MAKEFLAGS", "MFLAGS"] {
            assert!(
                script.contains(&format!("export {name}={flags}\n")),
                "{name} names the container fifo: {script}"
            );
        }
        assert!(!script.contains(dir.path().to_str().unwrap()));
        // The relay asked for nothing, so all it hears is the finish.
        assert_eq!(heard.recv().await.unwrap(), b"F");
    }

    /// A job whose `reader` script blocks on stdin yields exactly one alert
    /// until it is fed, and finishes once it is.
    #[cfg(unix)]
    async fn stdin_reader_alerts_once_and_resumes_when_fed(reader: &str) {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(60),
            Duration::from_secs(600),
        )
        .await;
        let background_receiver = tool.background_receiver();
        let task_id = start_background_job(&tool, reader).await;

        let alerts = alerts_within(&background_receiver, Duration::from_secs(8)).await;
        assert!(
            matches!(
                alerts.as_slice(),
                [JobAlert::StdinBlocked(job)] if job.task_id == task_id
            ),
            "a blocked reader must yield exactly one stdin alert: {alerts:?}"
        );

        InputTerminalTool::new(tool.job_registry())
            .call(
                InputTerminalArgs {
                    task_id: task_id.clone(),
                    input: "lexo".to_string(),
                    append_newline: true,
                },
                ToolContext::new(),
            )
            .await
            .expect("terminal_input should succeed");
        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
        let terminal_result = completed.result.expect("the fed job should complete");
        let stdout =
            output_text(&terminal_result.stdout).expect("completed task should include stdout");
        assert!(stdout.contains("hello lexo"), "got: {stdout}");
        assert!(
            background_receiver.take_job_alerts().is_empty(),
            "a fed job that finished must not alert again"
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn background_job_blocked_on_stdin_yields_one_alert() {
        stdin_reader_alerts_once_and_resumes_when_fed("read name; printf 'hello %s\\n' \"$name\"")
            .await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn background_grandchild_blocked_on_stdin_yields_one_alert() {
        stdin_reader_alerts_once_and_resumes_when_fed(
            "( ( read name; printf 'hello %s\\n' \"$name\" ); true )",
        )
        .await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn background_job_that_never_reads_stdin_yields_no_alert() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(60),
            Duration::from_secs(600),
        )
        .await;
        let background_receiver = tool.background_receiver();
        let task_id = start_background_job(&tool, "sleep 3; echo finished").await;

        let alerts = alerts_within(&background_receiver, Duration::from_secs(4)).await;
        assert!(alerts.is_empty(), "no alert expected: {alerts:?}");
        wait_for_completed_task(&background_receiver, &task_id).await;
    }

    /// The nice value `level` steps below this test process lands at, capped
    /// at the kernel's lowest priority — the same computation heel applies.
    #[cfg(unix)]
    fn expected_lowered_nice(level: u8) -> i64 {
        // SAFETY: reads the calling process's own nice value.
        let current = unsafe { libc::getpriority(libc::PRIO_PROCESS as _, 0) };
        i64::from(current + i32::from(level)).min(19)
    }

    #[cfg(unix)]
    fn test_nice_priority() -> ProcessPriority {
        ProcessPriority::new(
            CpuPriority::Nice(NiceLevel::new(10).expect("nice level 10 is in range")),
            IoPriority::Normal,
        )
    }

    /// A configured terminal tool with prepared local tools and the given
    /// shortened limits. Returns the tool and the cache owning its tools.
    #[cfg(unix)]
    async fn configured_test_terminal(
        dir: &Path,
        foreground_wait: Duration,
        timeout_cap: Duration,
        alert_after: Duration,
    ) -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
    ) {
        let (cache, tool) =
            unconfigured_test_terminal(dir, foreground_wait, timeout_cap, alert_after).await;
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        (cache, tool.with_registry(registry))
    }

    /// [`configured_test_terminal`] before its registry is bound.
    async fn unconfigured_test_terminal(
        dir: &Path,
        foreground_wait: Duration,
        timeout_cap: Duration,
        alert_after: Duration,
    ) -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Unconfigured>,
    ) {
        let (cache, shell_sessions) = prepared_test_registry().await;
        let tool = TerminalTool::new_exact(
            dir,
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted")
        .with_foreground_wait(foreground_wait)
        .with_timeout_cap(timeout_cap)
        .with_long_job_alert_after(alert_after);
        (cache, tool)
    }

    /// A foreground command still running at the window promotes to a
    /// background task instead of dying; its `timeout` then kills it with
    /// its descendants.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn foreground_command_still_running_at_the_window_promotes_and_times_out_with_descendants()
     {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(1),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;
        let background_receiver = tool.background_receiver();
        let child_pid_path = dir.path().join("child.pid");

        let result = tool
            .call(
                TerminalArgs {
                    description: "start a descendant process".to_string(),
                    script: "sleep 30 & echo $! > child.pid; wait".to_string(),
                    language: ScriptLanguage::Shell,
                    mode: TerminalExecutionMode::Sandboxed,
                    ssh_server_id: None,
                    expect: OutputFormat::Text,
                    resolution: MediaResolution::Auto,
                    max_lines: 50,
                    raw: false,
                    timeout: 3,
                    background: false,
                },
                ToolContext::new(),
            )
            .await
            .expect("terminal call should succeed");
        let rendered = render_terminal_result(&result);
        assert!(
            rendered.contains("Started in background as task '"),
            "the still-running command must promote: {rendered}"
        );
        let task_id = started_task_id(&background_receiver);

        let child_pid = async_fs::read_to_string(&child_pid_path)
            .await
            .expect("descendant pid file should exist")
            .trim()
            .parse::<i32>()
            .expect("descendant pid should parse");
        for _ in 0..500 {
            // SAFETY: signal 0 probes process existence.
            if unsafe { libc::kill(child_pid, 0) } != 0 {
                break;
            }
            async_io::Timer::after(std::time::Duration::from_millis(20)).await;
        }
        assert!(
            unsafe { libc::kill(child_pid, 0) } != 0,
            "descendant process {child_pid} survived the timeout kill"
        );

        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
        let info = tool
            .job_registry()
            .get_by_task_id(&task_id)
            .await
            .expect("the finished job stays in the registry");
        assert_eq!(
            info.status,
            JobStatus::Killed {
                cause: crate::KillCause::User,
                delivery: crate::Delivery::Pending
            },
            "the promoted job should be killed at its timeout: {completed:?}"
        );
    }

    /// A longer foreground window put in force through the shared handle
    /// keeps a command that outlasts the normal window in the foreground, and
    /// the normal window applies again once it is restored.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_longer_foreground_window_holds_until_restored() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(1),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;
        let wait = tool.foreground_wait();
        let run = || async {
            let result = tool
                .call(
                    TerminalArgs {
                        description: "outlast the normal window".to_string(),
                        script: "sleep 2 & wait; echo finished".to_string(),
                        language: ScriptLanguage::Shell,
                        mode: TerminalExecutionMode::Sandboxed,
                        ssh_server_id: None,
                        expect: OutputFormat::Text,
                        resolution: MediaResolution::Auto,
                        max_lines: 50,
                        raw: false,
                        timeout: 30,
                        background: false,
                    },
                    ToolContext::new(),
                )
                .await
                .expect("terminal call should succeed");
            render_terminal_result(&result)
        };

        wait.extend(Duration::from_secs(20));
        let during = run().await;
        assert!(
            during.contains("finished") && !during.contains("Started in background"),
            "the longer window keeps the command in the foreground: {during}"
        );

        wait.restore();
        let after = run().await;
        assert!(
            after.contains("Started in background as task '"),
            "the normal window applies again: {after}"
        );
    }

    /// What a test leaves running after its shell exits.
    ///
    /// `Plain` is a `sleep` in the shell's process group. `Setsid` is a helper
    /// program that calls `setsid` and stays alive, so it also leaves the
    /// group and the session. The helper is built here because macOS ships no
    /// `setsid` binary, and because the kernel withholds the environment of
    /// Apple's own binaries (`sleep`, `perl`), which is what finds a `setsid`
    /// descendant once its parent is gone.
    #[cfg(unix)]
    #[derive(Clone, Copy, Debug)]
    enum Descendant {
        Plain,
        Setsid,
    }

    /// The name of the `setsid` helper program, and so of its process.
    #[cfg(unix)]
    const SETSID_HELPER: &str = "setsid-helper";

    /// The directory the sandbox may execute programs from.
    #[cfg(unix)]
    fn exec_dir<P, E>(tool: &TerminalTool<P, E, Configured>) -> PathBuf {
        tool.shell_sessions
            .local_tools()
            .expect("the terminal has local tools")
            .bin_dir()
            .clone()
    }

    /// Builds the `setsid` helper into `dir` and returns its path. The sandbox
    /// executes only what lies under a granted directory, so `dir` is the
    /// prepared tools' [`exec_dir`].
    #[cfg(unix)]
    fn build_setsid_helper(dir: &Path) -> PathBuf {
        let source = dir.join("setsid_helper.rs");
        std::fs::write(
            &source,
            "extern \"C\" { fn setsid() -> i32; }\n\
             fn main() {\n\
                 let seconds: u64 = std::env::args().nth(1).expect(\"seconds\").parse().expect(\"seconds\");\n\
                 // SAFETY: `setsid` takes no arguments.\n\
                 if unsafe { setsid() } < 0 { std::process::exit(1); }\n\
                 std::thread::sleep(std::time::Duration::from_secs(seconds));\n\
             }\n",
        )
        .expect("helper source should be written");
        let binary = dir.join(SETSID_HELPER);
        let status = std::process::Command::new("rustc")
            .arg("--edition=2021")
            .arg("-o")
            .arg(&binary)
            .arg(&source)
            .status()
            .expect("rustc should run");
        assert!(status.success(), "the setsid helper should compile");
        binary
    }

    #[cfg(unix)]
    impl Descendant {
        /// The name the descendant's process has once it ran `exec`.
        const fn process_name(self) -> &'static str {
            match self {
                Self::Plain => "sleep",
                Self::Setsid => SETSID_HELPER,
            }
        }

        /// A command that starts the descendant for `seconds` detached from
        /// the shell's output, records its pid in `child.pid` and returns once
        /// the child exists.
        fn script(self, exec_dir: &Path, seconds: u32) -> String {
            // The foreground `sleep` guard refuses a plain `sleep 0.3`, so
            // the settle wait is a `kill -0` check on the recorded pid.
            match self {
                Self::Plain => format!(
                    "sleep {seconds} > /dev/null 2>&1 & echo $! > child.pid; until kill -0 \"$(cat child.pid)\" 2>/dev/null; do :; done"
                ),
                Self::Setsid => format!(
                    "'{}' {seconds} > /dev/null 2>&1 & echo $! > child.pid; until kill -0 \"$(cat child.pid)\" 2>/dev/null; do :; done",
                    build_setsid_helper(exec_dir).display()
                ),
            }
        }
    }

    /// The pid `child.pid` in `dir` holds, once the shell wrote it.
    #[cfg(unix)]
    async fn recorded_child_pid(dir: &Path) -> i32 {
        for _ in 0..250 {
            // The redirect creates the file before `echo` writes it, so an
            // empty read only means the pid is not there yet.
            if let Ok(text) = async_fs::read_to_string(dir.join("child.pid")).await
                && let Ok(pid) = text.trim().parse()
            {
                return pid;
            }
            async_io::Timer::after(Duration::from_millis(20)).await;
        }
        panic!("the descendant never recorded its pid");
    }

    /// Whether `pid` is a live process.
    #[cfg(unix)]
    fn process_exists(pid: i32) -> bool {
        // SAFETY: signal 0 probes process existence.
        unsafe { libc::kill(pid, 0) == 0 }
    }

    /// Fails unless `pid` is gone within a few seconds.
    #[cfg(unix)]
    async fn assert_process_gone(pid: i32, context: &str) {
        for _ in 0..250 {
            if !process_exists(pid) {
                return;
            }
            async_io::Timer::after(Duration::from_millis(20)).await;
        }
        panic!("process {pid} survived: {context}");
    }

    #[cfg(unix)]
    async fn foreground_command_leaving_a_descendant_kills_it_and_alerts_once(
        descendant: Descendant,
    ) {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;
        let receiver = tool.background_receiver();

        let result = tool
            .call(
                terminal_args(
                    "leave a descendant",
                    &descendant.script(&exec_dir(&tool), 300),
                ),
                ToolContext::new(),
            )
            .await
            .expect("terminal call should succeed");
        let command = result.command().expect("terminal returns a command result");
        assert!(
            matches!(command.outcome, CommandOutcome::Exited { code: 0 }),
            "{:?}",
            command.outcome
        );

        let child = recorded_child_pid(tool.working_dir()).await;
        assert_process_gone(
            child,
            &format!("{descendant:?} descendant of a foreground command"),
        )
        .await;
        let alerts = receiver.take_job_alerts();
        match alerts.as_slice() {
            [JobAlert::DescendantsKilled(killed)] => {
                assert_eq!(killed.omitted, 0);
                // The name is read after the freeze, once the child exec'd.
                assert_eq!(
                    killed
                        .processes
                        .iter()
                        .map(|process| i64::from(process.pid))
                        .collect::<Vec<_>>(),
                    [i64::from(child)]
                );
                assert_eq!(killed.processes[0].name, descendant.process_name());
            }
            other => panic!("expected one descendants-killed alert, got {other:?}"),
        }
        assert!(
            receiver.take_job_alerts().is_empty(),
            "the same event must not alert twice"
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn foreground_command_leaving_a_descendant_kills_it_and_alerts_once_plain() {
        foreground_command_leaving_a_descendant_kills_it_and_alerts_once(Descendant::Plain).await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn foreground_command_leaving_a_setsid_descendant_kills_it_and_alerts_once() {
        foreground_command_leaving_a_descendant_kills_it_and_alerts_once(Descendant::Setsid).await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn foreground_background_jobs_joined_by_wait_run_without_an_alert() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;
        let receiver = tool.background_receiver();

        let result = tool
            .call(
                terminal_args(
                    "run two jobs and join them",
                    "(sleep 1; echo one > one.txt) & (sleep 1; echo two > two.txt) & wait",
                ),
                ToolContext::new(),
            )
            .await
            .expect("terminal call should succeed");
        let command = result.command().expect("terminal returns a command result");
        assert!(
            matches!(command.outcome, CommandOutcome::Exited { code: 0 }),
            "{:?}",
            command.outcome
        );
        for name in ["one.txt", "two.txt"] {
            assert!(
                tool.working_dir().join(name).exists(),
                "{name} must be written before the command returns"
            );
        }
        assert!(
            receiver.take_job_alerts().is_empty(),
            "a joined job is no survivor"
        );
    }

    /// Starts the background `script`, waits until its shell has exited with the
    /// descendant still alive, and returns the task id and the descendant's pid.
    #[cfg(unix)]
    async fn background_job_whose_shell_exited(
        tool: &TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
        script: &str,
        timeout: u64,
    ) -> (String, i32) {
        let result = tool
            .run_background(TerminalArgs {
                background: true,
                timeout,
                ..terminal_args("background job", script)
            })
            .await
            .expect("terminal should start the background job");
        let task_id = match result.command().map(|command| &command.outcome) {
            Some(CommandOutcome::Running { task_id, .. }) => task_id.clone(),
            other => panic!("background job needs a task id, got {other:?}"),
        };
        let child = recorded_child_pid(tool.working_dir()).await;
        // Past the shell's exit and several of the tree's checks.
        tokio::time::sleep(Duration::from_millis(1200)).await;
        assert!(
            process_exists(child),
            "the descendant must outlive the shell"
        );
        (task_id, child)
    }

    #[cfg(unix)]
    async fn background_job_stays_running_until_its_descendant_exits(descendant: Descendant) {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;

        let (task_id, child) =
            background_job_whose_shell_exited(&tool, &descendant.script(&exec_dir(&tool), 3), 30)
                .await;
        let info = tool
            .job_registry()
            .get_by_task_id(&task_id)
            .await
            .expect("the job is registered");
        assert_eq!(
            info.status,
            JobStatus::Running,
            "the job runs while its descendant does"
        );
        assert!(
            tool.job_registry()
                .format_running_jobs()
                .await
                .contains(&task_id),
            "the running-jobs context lists the job"
        );

        assert_process_gone(child, "the descendant's own exit").await;
        let receiver = tool.background_receiver();
        let completed = wait_for_completed_task(&receiver, &task_id).await;
        assert!(completed.result.is_ok(), "{completed:?}");
        let info = tool
            .job_registry()
            .get_by_task_id(&task_id)
            .await
            .expect("the finished job stays in the registry");
        assert_eq!(
            info.status,
            JobStatus::Completed {
                exit_code: 0,
                delivery: crate::Delivery::Pending
            }
        );
        assert!(
            tool.job_registry().format_running_jobs().await.is_empty(),
            "a finished job is no longer listed"
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn background_job_stays_running_until_its_plain_descendant_exits() {
        background_job_stays_running_until_its_descendant_exits(Descendant::Plain).await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn background_job_stays_running_until_its_setsid_descendant_exits() {
        background_job_stays_running_until_its_descendant_exits(Descendant::Setsid).await;
    }

    #[cfg(unix)]
    async fn killing_a_background_job_kills_its_descendant(descendant: Descendant) {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;

        let (task_id, child) =
            background_job_whose_shell_exited(&tool, &descendant.script(&exec_dir(&tool), 300), 30)
                .await;
        assert!(
            tool.job_registry().kill_by_task_id(&task_id).await,
            "a job with a live descendant is killable"
        );
        assert_process_gone(
            child,
            &format!("terminal_kill of a job with a {descendant:?} descendant"),
        )
        .await;
        let info = tool
            .job_registry()
            .get_by_task_id(&task_id)
            .await
            .expect("the killed job stays in the registry");
        assert!(
            matches!(info.status, JobStatus::Killed { .. }),
            "{:?}",
            info.status
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn killing_a_background_job_kills_its_plain_descendant() {
        killing_a_background_job_kills_its_descendant(Descendant::Plain).await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn killing_a_background_job_kills_its_setsid_descendant() {
        killing_a_background_job_kills_its_descendant(Descendant::Setsid).await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn background_timeout_kills_a_descendant_that_outlived_the_shell() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;

        // The timeout fires while the shell is long gone: the job is only its
        // descendant by then.
        let (task_id, child) = background_job_whose_shell_exited(
            &tool,
            &Descendant::Setsid.script(&exec_dir(&tool), 300),
            2,
        )
        .await;
        assert_process_gone(child, "the timeout of a job whose shell exited").await;
        let receiver = tool.background_receiver();
        let completed = wait_for_completed_task(&receiver, &task_id).await;
        let info = tool
            .job_registry()
            .get_by_task_id(&task_id)
            .await
            .expect("the finished job stays in the registry");
        assert_eq!(
            info.status,
            JobStatus::Killed {
                cause: crate::KillCause::User,
                delivery: crate::Delivery::Pending
            },
            "{completed:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_subagents_cleanup_kills_a_descendant_that_outlived_the_shell() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;

        let (_task_id, child) = background_job_whose_shell_exited(
            &tool,
            &Descendant::Plain.script(&exec_dir(&tool), 300),
            30,
        )
        .await;
        // What `kill_running_terminal_jobs` and the subagent run's cleanup call.
        assert_eq!(tool.job_registry().kill_running().await, 1);
        assert_process_gone(child, "the cleanup of a subagent's job").await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn terminal_rejects_timeout_above_cap_and_kills_at_timeout() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(2),
            Duration::from_secs(60),
        )
        .await;
        let background_receiver = tool.background_receiver();
        let args = |timeout: u64| TerminalArgs {
            description: "sleep in the background".to_string(),
            script: "sleep 30".to_string(),
            language: ScriptLanguage::Shell,
            mode: TerminalExecutionMode::Sandboxed,
            ssh_server_id: None,
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            max_lines: 50,
            raw: false,
            timeout,
            background: true,
        };

        assert!(
            tool.call(args(3), ToolContext::new()).await.is_err(),
            "a timeout above the cap must be rejected"
        );

        let result = tool
            .call(args(1), ToolContext::new())
            .await
            .expect("a timeout within the cap should start the job");
        let rendered = render_terminal_result(&result);
        assert!(
            rendered.contains("Started in background as task '"),
            "{rendered}"
        );
        let task_id = started_task_id(&background_receiver);

        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
        let info = tool
            .job_registry()
            .get_by_task_id(&task_id)
            .await
            .expect("the finished job stays in the registry");
        assert_eq!(
            info.status,
            JobStatus::Killed {
                cause: crate::KillCause::User,
                delivery: crate::Delivery::Pending
            },
            "the job should have been killed at its timeout: {completed:?}"
        );
    }

    #[test]
    fn the_timeout_notice_states_both_utc_times() {
        let kill = TimeoutKill {
            timeout: Duration::from_secs(90),
            started: "2026-11-04T12:00:00Z".parse().expect("valid timestamp"),
            killed: "2026-11-04T12:01:31Z".parse().expect("valid timestamp"),
        };
        assert_eq!(
            crate::DefaultSandboxNotices.command_killed(&crate::CommandKilled::TimedOut(&kill)),
            "Its 90s timeout bound passed; it started at 2026-11-04 12:00:00 UTC \
             and was killed at 2026-11-04 12:01:31 UTC."
        );
    }

    #[cfg(unix)]
    fn spinning_args(timeout: u64, background: bool) -> TerminalArgs {
        TerminalArgs {
            description: "spin past the timeout".to_string(),
            script: if background {
                "while :; do sleep 0.1; done"
            } else {
                // A foreground `sleep` is refused; a niced spin leaves the
                // other tests their CPU.
                "nice -n 19 sh -c 'while :; do :; done'"
            }
            .to_string(),
            language: ScriptLanguage::Shell,
            mode: TerminalExecutionMode::Sandboxed,
            ssh_server_id: None,
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            max_lines: 50,
            raw: false,
            timeout,
            background,
        }
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_background_job_killed_at_its_timeout_reports_its_utc_times() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;
        let background_receiver = tool.background_receiver();
        tool.call(spinning_args(1, true), ToolContext::new())
            .await
            .expect("the job starts");
        let task_id = started_task_id(&background_receiver);
        let completed = wait_for_completed_task(&background_receiver, &task_id).await;

        assert_eq!(completed.kill, Some(crate::KillCause::User));
        let kill = completed
            .timeout_kill
            .expect("a job killed at its timeout carries the times");
        assert_eq!(kill.timeout, Duration::from_secs(1));
        assert!(
            kill.killed.duration_since(kill.started).as_secs_f64() >= 1.0,
            "{kill:?}"
        );
        assert!(
            kill.killed.duration_since(kill.started).as_secs() < 10,
            "{kill:?}"
        );
        assert!(
            crate::DefaultSandboxNotices
                .command_killed(&crate::CommandKilled::TimedOut(&kill))
                .starts_with("Its 1s timeout bound passed; it started at ")
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_job_killed_by_hand_is_not_a_timeout_kill() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;
        let background_receiver = tool.background_receiver();
        tool.call(spinning_args(30, true), ToolContext::new())
            .await
            .expect("the job starts");
        let task_id = started_task_id(&background_receiver);
        assert!(tool.job_registry().kill_by_task_id(&task_id).await);
        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
        assert_eq!(completed.kill, Some(crate::KillCause::User));
        assert_eq!(completed.timeout_kill, None);
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_foreground_command_killed_at_its_timeout_reports_its_utc_times() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(20),
            Duration::from_secs(60),
            Duration::from_secs(60),
        )
        .await;
        let before = jiff::Timestamp::now();
        let result = tool
            .call(spinning_args(1, false), ToolContext::new())
            .await
            .expect("a killed command still returns a result");
        let rendered = render_terminal_result(&result);
        let utc = |marker: &str| {
            let text = rendered
                .split(marker)
                .nth(1)
                .and_then(|rest| rest.split(" UTC").next())
                .unwrap_or_else(|| panic!("{marker:?} missing: {rendered}"));
            jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M:%S", text)
                .expect("a UTC date and time")
                .to_zoned(jiff::tz::TimeZone::UTC)
                .expect("UTC has no gaps")
                .timestamp()
        };
        assert!(
            rendered.contains("Its 1s timeout bound passed; it started at "),
            "{rendered}"
        );
        let started = utc("it started at ");
        let killed = utc("was killed at ");
        assert!(started.as_second() >= before.as_second(), "{rendered}");
        assert!(killed.as_second() - started.as_second() >= 1, "{rendered}");
        assert!(killed.as_second() - started.as_second() < 10, "{rendered}");
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn background_job_past_the_alert_threshold_yields_one_alert() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(60),
            Duration::from_millis(300),
        )
        .await;
        let background_receiver = tool.background_receiver();

        let _result = tool
            .run_background(TerminalArgs {
                description: "sleep in the background".to_string(),
                script: "sleep 30".to_string(),
                language: ScriptLanguage::Shell,
                mode: TerminalExecutionMode::Sandboxed,
                ssh_server_id: None,
                expect: OutputFormat::Text,
                resolution: MediaResolution::Auto,
                max_lines: 50,
                raw: false,
                timeout: 30,
                background: true,
            })
            .await
            .expect("terminal should start the job");
        let task_id = started_task_id(&background_receiver);

        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        let alerts = loop {
            let alerts = background_receiver.take_job_alerts();
            if !alerts.is_empty() {
                break alerts;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "long-running alert did not fire"
            );
            tokio::time::sleep(Duration::from_millis(50)).await;
        };
        assert_eq!(alerts.len(), 1);
        assert!(
            matches!(&alerts[0], JobAlert::LongRunning(job) if job.task_id == task_id),
            "expected the long-running alert for the job: {alerts:?}"
        );
        assert!(
            background_receiver.take_job_alerts().is_empty(),
            "the same job must not alert twice"
        );

        assert!(
            tool.job_registry().kill_by_task_id(&task_id).await,
            "test cleanup should kill the job"
        );
    }

    /// A terminal tool with prepared local tools and `priority` applied. The
    /// returned `TempDir` owns the prepared tools' cache; it must outlive the
    /// tool.
    #[cfg(unix)]
    async fn prioritized_terminal_tool(
        dir: &Path,
        priority: ProcessPriority,
    ) -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
    ) {
        let (cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir,
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_process_priority(priority);
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        (cache, tool.with_registry(registry))
    }

    /// A probe script made only of `sh` builtins: a strict sandbox executes
    /// nothing but the launched shell, the prepared tools and granted paths,
    /// so it reports its own `$$` into `pid` and waits for the host's `go`
    /// marker instead of running `nice`.
    #[cfg(unix)]
    fn pid_probe_args() -> TerminalArgs {
        TerminalArgs {
            description: "report the process pid and wait".to_string(),
            script: concat!(
                "printf '%s\\n' $$ > \"$PWD/pid\"; ",
                "while [ ! -f \"$PWD/go\" ]; do :; done"
            )
            .to_string(),
            language: ScriptLanguage::Shell,
            mode: TerminalExecutionMode::Sandboxed,
            ssh_server_id: None,
            expect: OutputFormat::Text,
            resolution: MediaResolution::Auto,
            max_lines: 50,
            raw: false,
            timeout: 30,
            background: false,
        }
    }

    /// Reads the pid the sandboxed probe wrote, retrying while the sandbox
    /// starts.
    #[cfg(unix)]
    async fn probe_pid(dir: &Path) -> u32 {
        let path = dir.join("pid");
        for _ in 0..150 {
            if let Ok(text) = std::fs::read_to_string(&path)
                && let Ok(pid) = text.trim().parse()
            {
                return pid;
            }
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }
        panic!("the sandboxed probe did not write {}", path.display());
    }

    /// The `pid`'s nice level, read from the host while the probe is alive.
    #[cfg(unix)]
    fn probe_nice(pid: u32) -> i64 {
        // SAFETY: queries the kernel for the named process's priority.
        i64::from(unsafe { libc::getpriority(libc::PRIO_PROCESS as _, pid as _) })
    }

    /// Releases the sandboxed probe by creating the `go` marker it polls for.
    #[cfg(unix)]
    fn release_probe(dir: &Path) {
        std::fs::File::create(dir.join("go")).expect("create the probe marker");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn foreground_command_runs_with_configured_nice() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_tools_cache, tool) =
            prioritized_terminal_tool(dir.path(), test_nice_priority()).await;

        let call = tool.call(pid_probe_args(), ToolContext::new());
        let probe = async {
            let pid = probe_pid(dir.path()).await;
            assert_eq!(
                probe_nice(pid),
                expected_lowered_nice(10),
                "foreground command should run at the configured nice level"
            );
            release_probe(dir.path());
        };
        let (result, ()) = futures::join!(call, probe);
        let rendered = render_terminal_result(&result.expect("terminal call should succeed"));
        assert!(!rendered.contains("Exit code:"), "{rendered}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn persistent_session_runs_with_configured_nice() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_tools_cache, tool) =
            prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
        let background_receiver = tool.background_receiver();
        let input_tool = InputTerminalTool::new(tool.job_registry());

        // `exec` keeps `$$` — the pid the probe wrote — on the interactive
        // shell the session then drives.
        let result = tool
            .run_background(TerminalArgs {
                description: "start a persistent shell".to_string(),
                script: "printf '%s\\n' $$ > \"$PWD/pid\"; exec sh".to_string(),
                language: ScriptLanguage::Shell,
                mode: TerminalExecutionMode::Sandboxed,
                ssh_server_id: None,
                expect: OutputFormat::Text,
                resolution: MediaResolution::Auto,
                max_lines: 50,
                raw: false,
                timeout: 30,
                background: true,
            })
            .await
            .expect("terminal call should succeed");
        let rendered = render_terminal_result(&result);
        assert!(
            rendered.contains("Started in background as task '"),
            "{rendered}"
        );
        let task_id = started_task_id(&tool.background_receiver());

        let pid = probe_pid(dir.path()).await;
        assert_eq!(
            probe_nice(pid),
            expected_lowered_nice(10),
            "persistent session should run at the configured nice level"
        );

        input_tool
            .call(
                InputTerminalArgs {
                    task_id: task_id.clone(),
                    input: "exit".to_string(),
                    append_newline: true,
                },
                ToolContext::new(),
            )
            .await
            .expect("terminal_input should succeed");

        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
        let terminal_result = completed
            .result
            .expect("persistent shell should exit cleanly after input");
        assert_eq!(terminal_result.exit_code, 0);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn background_job_runs_with_configured_nice() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_tools_cache, tool) =
            prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
        let background_receiver = tool.background_receiver();

        let result = tool
            .run_background(TerminalArgs {
                background: true,
                ..pid_probe_args()
            })
            .await
            .expect("terminal call should succeed");
        let rendered = render_terminal_result(&result);
        let mut started = tool.background_receiver().take_started();
        assert_eq!(started.len(), 1, "expected one started-task event");
        let started = started.remove(0);
        let task_id = started.task_id;
        assert_eq!(
            rendered,
            format!(
                "Started in background as task '{task_id}'; output is being written to {} (absolute path: {}).\n",
                started.output_file.url, started.output_file.path
            )
        );
        assert_eq!(
            result.command().map(|command| &command.outcome),
            Some(&CommandOutcome::Running {
                task_id: task_id.clone(),
                output: started.output_file.clone(),
            })
        );

        let pid = probe_pid(dir.path()).await;
        assert_eq!(
            probe_nice(pid),
            expected_lowered_nice(10),
            "background job should run at the configured nice level"
        );
        release_probe(dir.path());

        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
        let terminal_result = completed
            .result
            .expect("background job should complete successfully");
        assert_eq!(terminal_result.exit_code, 0);
    }

    #[test]
    fn wrap_container_script_applies_configured_priority() {
        let priority = ProcessPriority::new(
            CpuPriority::Nice(NiceLevel::new(5).expect("nice level 5 is in range")),
            IoPriority::Background,
        );
        let tools_dir = container_tools_dir();
        let executable = format!("--executable {}", shell_escape(tools_dir.as_str()));
        let wrapped = wrap_container_script(
            "echo ok",
            &[String::from("websearch")],
            Some(ContainerIpcEndpoint {
                host: "host.docker.internal",
                port: 9000,
            }),
            priority,
            &tools_dir,
            "/workspace",
            None,
        )
        .expect("wrap script");
        assert!(wrapped.contains(
            "\"$MAY_IPC_BIN\" run --isolation permissive --working-dir '/workspace' \
             --env-passthrough PATH --env-passthrough HOME"
        ));
        assert!(wrapped.contains(&executable));
        assert!(wrapped.contains(
            "--ipc-endpoint 'tcp://host.docker.internal:9000' --grant \"$MAY_IPC_DIR=rx\" \
             --nice 5 --io-priority background -- sh -c 'echo ok'"
        ));
        assert!(wrapped.contains("HEEL_IPC_ENDPOINT"));

        let bare = wrap_container_script(
            "echo ok",
            &[],
            None,
            priority,
            &tools_dir,
            "/workspace",
            None,
        )
        .expect("wrap script");
        assert!(bare.contains("MAY_HEEL_BIN=\"$(command -v heel || true)\""));
        assert!(bare.contains(
            "\"$MAY_HEEL_BIN\" run --isolation permissive --working-dir '/workspace' \
             --env-passthrough PATH --env-passthrough HOME"
        ));
        assert!(bare.contains(&executable));
        assert!(bare.contains("--nice 5 --io-priority background -- sh -c 'echo ok'"));

        let normal = wrap_container_script(
            "echo ok",
            &[],
            None,
            ProcessPriority::default(),
            &tools_dir,
            "/workspace",
            None,
        )
        .expect("wrap script");
        assert_eq!(normal, "echo ok");
    }

    #[test]
    fn wrap_container_script_prioritizes_each_half_independently() {
        let io_only = wrap_container_script(
            "echo ok",
            &[],
            None,
            ProcessPriority::new(CpuPriority::Normal, IoPriority::Utility),
            &container_tools_dir(),
            "/workspace",
            None,
        )
        .expect("wrap script");
        assert!(io_only.contains(" --io-priority utility -- sh -c 'echo ok'"));
        assert!(!io_only.contains("--nice"));

        let cpu_only = wrap_container_script(
            "echo ok",
            &[],
            None,
            ProcessPriority::new(
                CpuPriority::Nice(NiceLevel::new(9).expect("nice level 9 is in range")),
                IoPriority::Normal,
            ),
            &container_tools_dir(),
            "/workspace",
            None,
        )
        .expect("wrap script");
        assert!(cpu_only.contains(" --nice 9 -- sh -c 'echo ok'"));
        assert!(!cpu_only.contains("--io-priority"));
    }

    /// Probe tool for the container acceptance test: it answers an IPC call
    /// with the marker it was invoked with, so a request that actually reached
    /// the live handler is unmistakable.
    #[derive(Debug, Deserialize, JsonSchema)]
    struct ProbeEchoArgs {
        /// Marker echoed back to the caller.
        marker: String,
    }

    struct ProbeEchoTool;

    impl Tool for ProbeEchoTool {
        fn name(&self) -> Cow<'static, str> {
            "probe_echo".into()
        }

        type Arguments = ProbeEchoArgs;
        type Res = ToolResult;

        fn call(
            &self,
            arguments: Self::Arguments,
            _cx: ToolContext,
        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
            std::future::ready(Ok(ToolResult::text(format!(
                "marker: {}",
                arguments.marker
            ))))
        }
    }

    /// Host side of the container IPC transport on every platform: a client
    /// speaking the bridge's framing over loopback TCP reaches the registry's
    /// live handler and gets its envelope back.
    #[tokio::test(flavor = "multi_thread")]
    async fn container_ipc_bridge_round_trips_a_command_over_tcp() {
        let outputs = tempfile::tempdir().expect("outputs dir should be created");
        let mut builder = ToolRegistryBuilder::new();
        builder.configure_tool(ProbeEchoTool);
        let registry = Arc::new(builder.build(test_outputs(outputs.path())));
        let loopback = std::net::IpAddr::from([127, 0, 0, 1]);
        let bridge = start_container_ipc_bridge(
            executor_core::tokio::TokioGlobal,
            registry,
            None,
            BridgeAddress::try_from(loopback).expect("loopback binds the bridge"),
        )
        .expect("bridge should start on loopback");

        let mut stream = Async::<StdTcpStream>::connect(SocketAddr::new(loopback, bridge.port()))
            .await
            .expect("client should connect to the bridge");

        let params = rmp_serde::to_vec_named(&serde_json::json!({ "marker": "pong" }))
            .expect("params should encode");
        let request = heel::ipc::IpcRequest::encode("probe_echo", Path::new("/workspace"), &params)
            .expect("request should encode");
        stream
            .write_all(&request)
            .await
            .expect("request frame should be written");

        let mut length_bytes = [0_u8; 4];
        stream
            .read_exact(&mut length_bytes)
            .await
            .expect("response length should be read");
        let mut response = vec![0_u8; u32::from_be_bytes(length_bytes) as usize];
        stream
            .read_exact(&mut response)
            .await
            .expect("response body should be read");

        let (success, payload) = response
            .split_first()
            .expect("response carries a success flag");
        assert_eq!(*success, 1, "bridge should report success");
        let rendered: String =
            rmp_serde::from_slice(payload).expect("response should decode as msgpack");
        assert_eq!(
            rendered, "marker: pong",
            "probe_echo should answer with the CLI-rendered payload, as `heel ipc` prints it"
        );

        drop(stream);
        bridge.stop().await;
    }

    /// Scratch `ubuntu:24.04` container used by the acceptance test; removed
    /// on drop.
    #[cfg(all(unix, aither_container_acceptance))]
    struct TestDockerContainer(String);

    #[cfg(all(unix, aither_container_acceptance))]
    impl TestDockerContainer {
        /// Starts a container with `heel_bin` mounted at `/usr/local/bin/heel`,
        /// the staged tool bundle mounted read-only where the image carries
        /// it, and `host.docker.internal` resolving to the docker host gateway,
        /// and prepares the `/workspace` directory container executions run
        /// in. Returns `None` when docker cannot start the container.
        fn start(heel_bin: &Path, tools: &crate::MountSpec) -> Option<Self> {
            let name = format!("aither-test-{}", uuid::Uuid::new_v4().simple());
            let mount = format!("{}:/usr/local/bin/heel:ro", heel_bin.display());
            let tools_mount = format!("{}:{}:ro", tools.host_path.display(), tools.container_path);
            let output = std::process::Command::new("docker")
                .args([
                    "run",
                    "-d",
                    "--name",
                    &name,
                    "--add-host=host.docker.internal:host-gateway",
                    "-v",
                    &mount,
                    "-v",
                    &tools_mount,
                    "ubuntu:24.04",
                    "tail",
                    "-f",
                    "/dev/null",
                ])
                .output()
                .ok()?;
            if !output.status.success() {
                return None;
            }
            let prepared = std::process::Command::new("docker")
                .args(["exec", &name, "mkdir", "-p", CONTAINER_EXEC_WORKING_DIR])
                .output()
                .is_ok_and(|output| output.status.success());
            if !prepared {
                let _ = std::process::Command::new("docker")
                    .args(["rm", "-f", &name])
                    .output();
                return None;
            }
            Some(Self(name))
        }
    }

    #[cfg(all(unix, aither_container_acceptance))]
    impl Drop for TestDockerContainer {
        fn drop(&mut self) {
            let _ = std::process::Command::new("docker")
                .args(["rm", "-f", &self.0])
                .output();
        }
    }

    /// The docker `bridge` network's gateway as the host owns it — the
    /// address `host.docker.internal` resolves to inside the container via
    /// `--add-host …:host-gateway`, so it is the address the IPC bridge binds.
    #[cfg(all(unix, aither_container_acceptance))]
    async fn container_bridge_address(
        client: &bollard::Docker,
        container_id: &str,
    ) -> BridgeAddress {
        client
            .inspect_container(
                container_id,
                None::<bollard::query_parameters::InspectContainerOptions>,
            )
            .await
            .expect("container acceptance should inspect the container")
            .network_settings
            .and_then(|settings| settings.networks)
            .and_then(|mut networks| networks.remove("bridge"))
            .and_then(|endpoint| endpoint.gateway)
            .expect("container acceptance requires the bridge network gateway")
            .parse::<std::net::IpAddr>()
            .expect("the bridge gateway should parse as an IP address")
            .try_into()
            .expect("the bridge gateway should be a usable bridge address")
    }

    /// A Linux `heel` binary for the container under test: `HEEL_BIN` wins,
    /// then a `heel` already on `PATH`.
    #[cfg(all(unix, aither_container_acceptance))]
    fn container_test_heel_binary() -> Option<PathBuf> {
        std::env::var_os("HEEL_BIN")
            .map(PathBuf::from)
            .filter(|path| path.is_file())
            .or_else(|| {
                std::process::Command::new("sh")
                    .args(["-c", "command -v heel"])
                    .output()
                    .ok()
                    .filter(|output| output.status.success())
                    .and_then(|output| String::from_utf8(output.stdout).ok())
                    .map(|resolved| PathBuf::from(resolved.trim()))
            })
            .filter(|path| path.is_file())
    }

    /// End-to-end container path: `TerminalTool` execs the wrapped script in a
    /// real container through `BollardContainerExec`, and the script fires a
    /// real `heel ipc` request at the live host bridge.
    ///
    /// The wrapped `heel run` carries the configured priority through heel's
    /// own sandbox configuration, and `--ipc-endpoint` relays the nested
    /// sandbox's local IPC socket to the host bridge, so `probe_echo` answers
    /// from the live handler rather than failing at the transport.
    ///
    /// Compiled only with `--cfg aither_container_acceptance`: the test needs
    /// a real docker daemon and a Linux `heel` binary, which the dedicated CI
    /// job provides and the feature matrices do not. A missing daemon or
    /// binary fails the test — it is never skipped silently.
    /// Starts the acceptance container with the test bundle staged as an
    /// image build stages it and mounted read-only where the image carries
    /// it, so the wrapped script runs a prepared command from that directory.
    /// The returned directory holds the staged bundle and must outlive the
    /// container.
    #[cfg(all(unix, aither_container_acceptance))]
    async fn start_acceptance_container() -> (
        TestDockerContainer,
        crate::tool_runtime::ImageTools,
        crate::tool_runtime::tests::UnlockingTempDir,
    ) {
        let docker_ready = std::process::Command::new("docker")
            .arg("info")
            .output()
            .is_ok_and(|output| output.status.success());
        assert!(
            docker_ready,
            "container acceptance requires a docker daemon"
        );
        let heel_bin = container_test_heel_binary()
            .expect("container acceptance requires a Linux heel binary (set HEEL_BIN)");
        let image = crate::tool_runtime::tests::image_tools();
        let bundle = crate::tool_runtime::tests::bundle();
        let tools_cache = crate::tool_runtime::tests::unlocking_tempdir();
        // Stage the executables under the image's cache key — exactly what
        // `stage_image_tools` produces — and mount the directory where the
        // image carries it.
        let prepared = bundle
            .prepare_local_sync(tools_cache.path(), &image.cache_key().unwrap(), None)
            .expect("test bundle should stage for the image");
        let staged = prepared
            .bin_dir()
            .parent()
            .expect("prepared binaries have a parent directory")
            .to_path_buf();
        let tools_mount =
            crate::MountSpec::read_only(&staged, image.container_directory().unwrap());
        let container = TestDockerContainer::start(&heel_bin, &tools_mount)
            .expect("container acceptance could not start ubuntu:24.04");
        (container, image, tools_cache)
    }

    /// The shell sessions of a terminal whose home is the acceptance
    /// container, reaching the host IPC bridge through the docker gateway.
    #[cfg(all(unix, aither_container_acceptance))]
    async fn acceptance_shell_sessions(
        container: &TestDockerContainer,
        image: &crate::tool_runtime::ImageTools,
        workspace: &Path,
    ) -> ShellSessionRegistry {
        let client = Arc::new(
            bollard::Docker::connect_with_local_defaults().expect("docker client should connect"),
        );
        // The bridge binds the container network's gateway as the host owns
        // it (docker0), because native Linux Docker resolves
        // `host.docker.internal` (via `--add-host …:host-gateway`) to exactly
        // that address.
        let bind = container_bridge_address(&client, &container.0).await;
        println!("ipc bridge bind: {}", bind.ip());
        let exec = crate::AnyContainerExec::new(Arc::new(crate::BollardContainerExec::new(client)));
        let runtime = ContainerShellRuntime::new(
            container.0.clone(),
            crate::ContainerIpcRoute::new("host.docker.internal", bind),
            exec,
        )
        .with_workspace_mount(MountRoot::new(
            workspace,
            ContainerPath::new(CONTAINER_EXEC_WORKING_DIR).expect("the workspace is absolute"),
        ));

        // The container backend needs its own prepared tools: the registry
        // entry names the container and its `/opt/aither/tools` bin dir, which
        // the wrapped script puts on `PATH` and heel must grant execute on.
        let container_tools = crate::tool_runtime::tests::container_tools(image);
        ShellSessionRegistry::new(ShellRuntimeAvailability {
            local: false,
            container: true,
            ssh: false,
        })
        .with_container_runtime(runtime)
        .with_test_container_tools(container_tools, container.0.clone())
    }

    /// The streamed exec of the real docker backend delivers a command's
    /// stdout in order and whole across chunks, reports its exit status, and
    /// kills the command when its kill switch is dropped.
    #[cfg(all(unix, aither_container_acceptance))]
    #[tokio::test]
    async fn container_streamed_exec_streams_stdout_reports_status_and_kills_on_drop() {
        use crate::ContainerExec as _;
        let (container, _bundle, _tools_cache) = start_acceptance_container().await;
        let client = Arc::new(
            bollard::Docker::connect_with_local_defaults().expect("docker client should connect"),
        );
        let exec = crate::BollardContainerExec::new(client);

        let (_kill_tx, kill_rx) = async_channel::bounded::<()>(1);
        let (stdin_tx, stdin_rx) = async_channel::bounded::<Vec<u8>>(1);
        drop(stdin_tx);
        let (out_tx, out_rx) = async_channel::bounded::<Vec<u8>>(8);
        let streaming = exec.exec_streamed(
            &container.0,
            "head -c 300000 /dev/zero | tr '\\0' 'x'; exit 3",
            "/",
            kill_rx,
            stdin_rx,
            out_tx,
        );
        let collect = async {
            let mut total = 0;
            while let Ok(chunk) = out_rx.recv().await {
                assert!(chunk.iter().all(|byte| *byte == b'x'));
                total += chunk.len();
            }
            total
        };
        let (outcome, total) = futures::join!(streaming, collect);
        assert_eq!(total, 300_000, "every byte arrives");
        match outcome.expect("the exec runs") {
            ContainerExecOutcome::Completed { output, .. } => {
                assert_eq!(output.status.code(), Some(3));
            }
            ContainerExecOutcome::Killed => panic!("nothing killed it"),
        }

        // A reader that goes away ends the command.
        let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
        let (stdin_tx, stdin_rx) = async_channel::bounded::<Vec<u8>>(1);
        drop(stdin_tx);
        let (out_tx, out_rx) = async_channel::bounded::<Vec<u8>>(1);
        drop(out_rx);
        let outcome = exec
            .exec_streamed(&container.0, "yes", "/", kill_rx, stdin_rx, out_tx)
            .await;
        drop(kill_tx);
        assert!(
            matches!(outcome, Ok(ContainerExecOutcome::Killed) | Err(_)),
            "a gone reader stops the command: {outcome:?}"
        );
    }

    /// In a real container the main agent's command runs unconfined, while a
    /// subagent's runs under its per-command sandbox: it writes its own space
    /// and nothing else of the workspace.
    #[cfg(all(unix, aither_container_acceptance))]
    #[tokio::test]
    async fn container_subagent_is_confined_while_the_main_agent_is_not() {
        let (container, bundle, _tools_cache) = start_acceptance_container().await;
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let shell_sessions = acceptance_shell_sessions(&container, &bundle, dir.path()).await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted");
        let parent = tool.with_registry(Arc::new(
            ToolRegistryBuilder::new().build(test_outputs(dir.path())),
        ));
        let child = parent
            .subagent_without_grant()
            .await
            .expect("an empty grant is always given");
        // The acceptance container does not really mount the host workspace,
        // so the subagent's space is created inside it too.
        let root = dunce::canonicalize(dir.path()).expect("workspace root should resolve");
        let space = child
            .working_dir()
            .strip_prefix(&root)
            .expect("the space is inside the workspace");
        let container_space = format!("{CONTAINER_EXEC_WORKING_DIR}/{}", space.display());
        let made = std::process::Command::new("docker")
            .args(["exec", &container.0, "mkdir", "-p", &container_space])
            .output()
            .expect("docker exec should run");
        assert!(made.status.success(), "{made:?}");

        let host_workspace_write =
            |name: &str| format!("touch {CONTAINER_EXEC_WORKING_DIR}/{name}");
        assert_eq!(
            exit_code_of(&parent, &host_workspace_write("main.txt")).await,
            0,
            "the main agent is unconfined in its container"
        );
        assert_ne!(
            exit_code_of(&child, &host_workspace_write("sub.txt")).await,
            0,
            "a subagent cannot write the workspace root"
        );
        assert_eq!(
            exit_code_of(&child, &format!("touch {container_space}/own.txt")).await,
            0,
            "a subagent writes its own space"
        );
    }

    #[cfg(all(unix, aither_container_acceptance))]
    #[tokio::test]
    async fn container_command_runs_with_configured_nice_and_reaches_ipc() {
        let (container, bundle, _tools_cache) = start_acceptance_container().await;

        let shell_sessions = acceptance_shell_sessions(&container, &bundle, Path::new("/")).await;

        let dir = tempfile::tempdir().expect("temp dir should be created");
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir.path(),
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_process_priority(ProcessPriority::new(
                CpuPriority::Nice(NiceLevel::new(5).expect("nice level 5 is in range")),
                IoPriority::Normal,
            ));
        let mut builder = ToolRegistryBuilder::new();
        builder.configure_tool(ProbeEchoTool);
        let registry = Arc::new(builder.build(tool.output_store().clone()));
        let tool = tool.with_registry(registry);

        let result = tool
            .call(
                TerminalArgs {
                    description: "probe container priority and IPC transport".to_string(),
                    script: concat!(
                        "printf 'nice=%s\\n' \"$(nice)\"; ",
                        "jq --version; ",
                        "probe_echo --marker pong; ",
                        "printf 'probe_exit=%s\\n' \"$?\""
                    )
                    .to_string(),
                    language: ScriptLanguage::Shell,
                    mode: TerminalExecutionMode::Sandboxed,
                    ssh_server_id: None,
                    expect: OutputFormat::Text,
                    resolution: MediaResolution::Auto,
                    max_lines: 50,
                    raw: false,
                    timeout: 30,
                    background: false,
                },
                ToolContext::new(),
            )
            .await
            .expect("container terminal call should succeed");
        let stdout = render_terminal_result(&result);
        assert!(
            !stdout.contains("Exit code:"),
            "container command failed; stdout: {stdout}"
        );
        // The CI job runs the test with --nocapture so the container's output
        // — the applied nice level and the live probe reply — lands in the
        // job log.
        println!("container script output:\n{stdout}");
        assert!(
            stdout.contains("nice=5"),
            "container command should run at the configured nice level; stdout: {stdout}"
        );
        assert!(
            stdout.contains("jq 1.0.0"),
            "a prepared command should run from the read-only tools mount; stdout: {stdout}"
        );
        assert!(
            stdout.contains("pong"),
            "probe_echo should answer from the live handler; stdout: {stdout}"
        );
        assert!(
            stdout.contains("probe_exit=0"),
            "heel ipc should exit 0 through the relayed endpoint; stdout: {stdout}"
        );
    }

    // ---- subagent authority -------------------------------------------------

    type ConfiguredTestTool =
        TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>;

    /// Runs `script` in `tool`'s sandbox and returns its exit code.
    #[cfg(unix)]
    async fn exit_code_of(tool: &ConfiguredTestTool, script: &str) -> i32 {
        let result = tool
            .call(terminal_args("authority probe", script), ToolContext::new())
            .await
            .expect("terminal call should succeed");
        match result.command().map(|command| &command.outcome) {
            Some(CommandOutcome::Exited { code }) => *code,
            other => panic!("the probe should run to completion, got {other:?}"),
        }
    }

    #[cfg(unix)]
    async fn authority_terminal(
        dir: &Path,
    ) -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        ConfiguredTestTool,
    ) {
        configured_test_terminal(
            dir,
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(600),
        )
        .await
    }

    /// A script the sandboxed command writes into its working directory and
    /// chmods executes — writable space also carries EXEC.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_script_written_into_the_working_dir_executes() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        assert_eq!(
            exit_code_of(
                &tool,
                "echo '#!/bin/sh\necho ok' > run.sh && chmod +x run.sh && ./run.sh",
            )
            .await,
            0,
            "a script the command writes and chmods runs"
        );
    }

    /// The host Rust toolchain works end to end inside the local sandbox:
    /// cargo runs, and `cargo test` executes the binary it just built under
    /// the writable working dir.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn the_host_rust_toolchain_builds_and_tests_a_crate() {
        assert!(
            std::process::Command::new("cargo")
                .arg("--version")
                .output()
                .is_ok_and(|output| output.status.success()),
            "cargo must be on the host PATH for this test"
        );
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;

        assert_eq!(
            exit_code_of(&tool, "cargo --version").await,
            0,
            "cargo is reachable inside the sandbox"
        );

        let krate = dir.path().join("probe");
        std::fs::create_dir_all(krate.join("src")).unwrap();
        std::fs::write(
            krate.join("Cargo.toml"),
            "[package]\nname = \"probe\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        std::fs::write(
            krate.join("src/lib.rs"),
            "#[test]\nfn it_runs() { assert_eq!(1 + 1, 2); }\n",
        )
        .unwrap();
        let script = format!(
            "cd '{}' && CARGO_TARGET_DIR='{}' cargo test",
            krate.display(),
            krate.join("target").display()
        );
        assert_eq!(
            exit_code_of(&tool, &script).await,
            0,
            "cargo test executes the binary it built under the working dir"
        );
    }

    /// Credential files inside the granted toolchain homes stay unreadable.
    #[cfg(all(unix, target_os = "macos"))]
    #[tokio::test(flavor = "multi_thread")]
    async fn cargo_credentials_inside_the_granted_home_stay_unreadable() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let code = exit_code_of(&tool, "cat ~/.cargo/credentials.toml").await;
        assert_ne!(
            code, 0,
            "a credential file under ~/.cargo stays denied inside the sandbox"
        );
    }
    /// Launches a subagent of `parent` the way its launcher does, with a
    /// launch history of its own.
    async fn launch(
        parent: &ConfiguredTestTool,
        grant: SubagentGrant,
    ) -> Result<ConfiguredTestTool, SubagentGrantError> {
        parent
            .subagent(&mut LaunchHistory::default(), grant, None)
            .await
    }

    /// What a [`CloneSpaces`] was asked to prepare, as `(space, launcher,
    /// caller)`.
    type SeenSpace = (PathBuf, PathBuf, PathBuf);

    /// How a test's [`SubagentSpaces`] fills a space.
    #[derive(Clone, Copy)]
    enum Filling {
        /// Clones the source repository into `repo` and names it.
        Clone,
        /// Writes a file into the space, then fails.
        Fail,
        /// Names the launcher's working directory as the working copy.
        Outside,
    }

    #[derive(Debug, thiserror::Error)]
    #[error("the session has no clone to give")]
    struct NoClone;

    /// Prepares each space from `source`, the launcher's repository, and
    /// records what it was asked.
    struct CloneSpaces {
        source: PathBuf,
        filling: Filling,
        seen: async_channel::Sender<SeenSpace>,
    }

    impl SubagentSpaces for CloneSpaces {
        type Error = NoClone;

        async fn prepare(&self, run: RunSpace<'_>) -> Result<PreparedSpace, NoClone> {
            self.seen
                .send((
                    run.space.to_path_buf(),
                    run.launcher.to_path_buf(),
                    run.caller.to_path_buf(),
                ))
                .await
                .expect("the test records each space");
            let clone = run.space.join("repo");
            match self.filling {
                Filling::Clone => {
                    let (source, target) = (self.source.clone(), clone.clone());
                    blocking::unblock(move || {
                        crate::test_git::git(
                            &source,
                            &["clone", "-q", "--local", ".", target.to_str().unwrap()],
                        )
                    })
                    .await;
                    Ok(PreparedSpace::new().with_working_copy(clone))
                }
                Filling::Fail => {
                    async_fs::write(run.space.join("half-done"), "x")
                        .await
                        .unwrap();
                    Err(NoClone)
                }
                Filling::Outside => Ok(PreparedSpace::new().with_working_copy(run.launcher)),
            }
        }
    }

    /// A terminal in `dir` whose subagents' spaces `filling` prepares from
    /// the repository `dir/repo`, with the receiver of what it is asked.
    async fn spaced_terminal(
        dir: &Path,
        filling: Filling,
    ) -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        ConfiguredTestTool,
        async_channel::Receiver<SeenSpace>,
    ) {
        let source = dir.join("repo");
        std::fs::create_dir_all(&source).unwrap();
        crate::test_git::git(&source, &["init", "-q", "--initial-branch=main"]);
        crate::test_git::git(&source, &["commit", "-q", "--allow-empty", "-m", "base"]);
        let (seen, seen_rx) = async_channel::unbounded();
        let (cache, tool) = unconfigured_test_terminal(
            dir,
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(600),
        )
        .await;
        let tool = tool.with_subagent_spaces(CloneSpaces {
            source,
            filling,
            seen,
        });
        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.output_store().clone()));
        (cache, tool.with_registry(registry), seen_rx)
    }

    /// A subagent works in the clone its launcher's spaces prepared: it
    /// commits there, cannot push into the launcher's repository, and its
    /// work reaches the launcher only when the launcher fetches it. The space
    /// outlives the subagent's terminal for that, and the launcher can
    /// remove it; a subagent's own launches are prepared by the same spaces.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_subagent_works_in_the_clone_its_launchers_spaces_prepared() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let root = dunce::canonicalize(dir.path()).unwrap();
        let (_cache, parent, seen) = spaced_terminal(dir.path(), Filling::Clone).await;
        let caller = dir.path().join("repo");
        let child = parent
            .subagent(
                &mut LaunchHistory::default(),
                SubagentGrant::new(),
                Some(&caller),
            )
            .await
            .expect("the space is prepared");

        let (space, launcher, asked_from) = seen.try_recv().expect("the spaces were asked");
        assert_eq!(&space, child.working_dir(), "the run works in the space");
        assert!(space.starts_with(root.join(SUBAGENT_SPACES_DIR)));
        assert_eq!(launcher, root, "the launcher is the main agent's terminal");
        assert_eq!(asked_from, caller, "the caller's directory is passed on");
        let clone = space.join("repo");
        assert_eq!(
            child.prepared_space().unwrap().working_copies(),
            std::slice::from_ref(&clone)
        );
        let dyn_child = child.clone().to_dyn();
        assert_eq!(
            dyn_child.prepared_space().unwrap().working_copies(),
            std::slice::from_ref(&clone),
            "the bundle a subagent's agent gets names its working copies"
        );
        assert!(parent.prepared_space().is_none());

        let git = "git -c user.name=t -c user.email=t@t -c commit.gpgSign=false";
        assert_eq!(
            exit_code_of(
                &child,
                &format!(
                    "cd '{}' && echo work > file && {git} add file && {git} commit -q -m work",
                    clone.display()
                ),
            )
            .await,
            0,
            "the subagent commits in its clone"
        );
        assert_ne!(
            exit_code_of(
                &child,
                &format!(
                    "cd '{}' && {git} push -q origin HEAD:refs/heads/pushed",
                    clone.display()
                ),
            )
            .await,
            0,
            "the launcher's repository is read-only to the subagent"
        );
        assert!(!crate::test_git::succeeds(
            &caller,
            &["rev-parse", "--verify", "-q", "refs/heads/pushed"]
        ));

        let nested = child
            .subagent(&mut LaunchHistory::default(), SubagentGrant::new(), None)
            .await
            .expect("a nested space is prepared");
        let (nested_space, nested_launcher, nested_caller) = seen.try_recv().unwrap();
        assert_eq!(&nested_space, nested.working_dir());
        assert_eq!(nested_launcher, space, "a subagent launches from its space");
        assert_eq!(nested_caller, space, "the caller defaults to the launcher");
        drop((nested, dyn_child, child));

        assert!(clone.join(".git").is_dir(), "the space outlives the run");
        assert_eq!(
            exit_code_of(
                &parent,
                &format!(
                    "cd repo && {git} fetch -q '{}' HEAD && {git} merge -q --ff-only FETCH_HEAD",
                    clone.display()
                ),
            )
            .await,
            0,
            "the launcher merges the run's work"
        );
        assert_eq!(
            crate::test_git::git(&caller, &["log", "-1", "--format=%s"]),
            "work"
        );
        assert_eq!(
            exit_code_of(&parent, &format!("rm -rf '{}'", space.display())).await,
            0,
            "the launcher owns the space"
        );
        assert!(!space.exists());
    }

    /// A space the launcher's spaces cannot prepare fails the launch with
    /// their error, and is removed with what they left in it.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_space_that_cannot_be_prepared_fails_the_launch_and_is_removed() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, parent, seen) = spaced_terminal(dir.path(), Filling::Fail).await;
        let error = parent
            .binding()
            .launcher()
            .create(SubagentGrant::new(), None, None, None)
            .await
            .expect_err("the launch fails");
        let (asked, _, _) = seen.try_recv().unwrap();
        let TerminalToolFactoryError::Grant(SubagentGrantError::Preparation { space, source }) =
            &error
        else {
            panic!("the launch fails with the preparation error: {error}");
        };
        assert_eq!(space, &asked);
        assert!(source.downcast_ref::<NoClone>().is_some(), "{error}");
        assert!(
            error
                .to_string()
                .contains("the session has no clone to give")
        );
        assert!(!space.exists(), "the failed space is removed");
    }

    /// A working copy named outside the space fails the launch, and the space
    /// is removed.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_working_copy_outside_the_space_fails_the_launch() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, parent, seen) = spaced_terminal(dir.path(), Filling::Outside).await;
        let error = launch(&parent, SubagentGrant::new())
            .await
            .expect_err("the launch fails");
        let (asked, launcher, _) = seen.try_recv().unwrap();
        let SubagentGrantError::PreparedOutsideSpace { path, space } = &error else {
            panic!("the launch fails on the working copy: {error}");
        };
        assert_eq!((path, space), (&launcher, &asked));
        assert!(!asked.exists(), "the refused space is removed");
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn subagent_cannot_write_the_session_root_but_writes_its_space_and_granted_worktrees() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, parent) = authority_terminal(dir.path()).await;
        let granted = dir.path().join("granted");
        let ungranted = dir.path().join("ungranted");
        std::fs::create_dir_all(&granted).unwrap();
        std::fs::create_dir_all(&ungranted).unwrap();
        let child = launch(&parent, SubagentGrant::new().with_worktree(&granted))
            .await
            .expect("a writable directory can be granted");

        let touch = |path: &Path| format!("touch '{}'", path.display());
        let root_file = dir.path().join("root.txt");
        assert_eq!(
            exit_code_of(&parent, &touch(&root_file)).await,
            0,
            "the main agent writes its own space"
        );
        std::fs::remove_file(&root_file).unwrap();

        assert_ne!(
            exit_code_of(&child, &touch(&root_file)).await,
            0,
            "the session root is read-only to a subagent"
        );
        assert!(!root_file.exists());
        assert_ne!(
            exit_code_of(&child, &touch(&ungranted.join("x"))).await,
            0,
            "what the parent can write but did not grant is read-only"
        );
        assert_eq!(
            exit_code_of(&child, &touch(&child.working_dir().join("own.txt"))).await,
            0,
            "a subagent writes its own space"
        );
        assert!(
            child
                .working_dir()
                .starts_with(dunce::canonicalize(dir.path()).unwrap())
        );
        assert_ne!(child.working_dir(), parent.working_dir());
        assert_eq!(
            exit_code_of(&child, &touch(&granted.join("g.txt"))).await,
            0,
            "a subagent writes the worktrees it was granted"
        );
    }

    /// Runs `script` in `tool` and returns its trimmed standard output.
    #[cfg(unix)]
    async fn stdout_of(tool: &ConfiguredTestTool, script: &str) -> String {
        let result = tool
            .call(terminal_args("carry probe", script), ToolContext::new())
            .await
            .expect("terminal call should succeed");
        render_terminal_result(&result).trim().to_string()
    }

    /// The directory `pwd` prints for the next command.
    #[cfg(unix)]
    async fn pwd_of(tool: &ConfiguredTestTool) -> PathBuf {
        PathBuf::from(stdout_of(tool, "pwd").await)
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_successful_cd_carries_to_the_next_foreground_command() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let root = dunce::canonicalize(dir.path()).unwrap();
        assert_eq!(pwd_of(&tool).await, root);

        assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
        assert_eq!(pwd_of(&tool).await, root.join("sub"));
        // Relative to the carried directory, and a later `cd` carries on.
        assert_eq!(exit_code_of(&tool, "mkdir -p a/b && cd a/b").await, 0);
        assert_eq!(pwd_of(&tool).await, root.join("sub/a/b"));
        // A direct command starts in the carried directory too.
        assert_eq!(
            PathBuf::from(stdout_of(&tool, "/bin/pwd").await),
            root.join("sub/a/b")
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_failure_an_outside_cd_and_a_background_cd_leave_the_directory() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let root = dunce::canonicalize(dir.path()).unwrap();
        stdout_of(&tool, "mkdir sub other && cd sub").await;
        let sub = root.join("sub");
        assert_eq!(pwd_of(&tool).await, sub);

        assert_eq!(
            exit_code_of(&tool, "cd ../other; exit 3").await,
            3,
            "the command fails"
        );
        assert_eq!(pwd_of(&tool).await, sub, "a failed command carries nothing");

        // Readable to the sandbox, yet in none of the terminal's grants.
        assert_eq!(
            exit_code_of(&tool, "cd /usr").await,
            0,
            "the cd itself succeeds"
        );
        assert_eq!(
            pwd_of(&tool).await,
            sub,
            "a directory outside the readable paths carries nothing"
        );

        start_background_job(&tool, "cd ../other && pwd").await;
        for _ in 0..500 {
            if tool.running_tasks.load(Ordering::Acquire) == 0 {
                break;
            }
            async_io::Timer::after(Duration::from_millis(20)).await;
        }
        assert_eq!(tool.running_tasks.load(Ordering::Acquire), 0);
        assert_eq!(pwd_of(&tool).await, sub, "a background cd carries nothing");
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn an_exported_variable_does_not_reach_the_next_command() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        assert_eq!(
            stdout_of(
                &tool,
                "export CARRY_PROBE=set; mkdir sub; cd sub; echo $CARRY_PROBE"
            )
            .await,
            "set"
        );
        assert_eq!(
            stdout_of(&tool, "printenv CARRY_PROBE; echo rc=$?").await,
            "rc=1"
        );
        assert_eq!(
            pwd_of(&tool).await,
            dunce::canonicalize(dir.path()).unwrap().join("sub")
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_symlinked_working_directory_is_resolved_for_the_report() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let real = dunce::canonicalize(dir.path()).unwrap().join("real");
        std::fs::create_dir(&real).unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        let (_cache, tool) = authority_terminal(&link).await;
        assert_eq!(tool.working_dir(), &real);
        assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
        assert_eq!(pwd_of(&tool).await, real.join("sub"));
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_subagents_cd_does_not_carry_over() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, parent) = authority_terminal(dir.path()).await;
        let child = launch(&parent, SubagentGrant::new())
            .await
            .expect("a subagent without grants launches");
        let space = child.working_dir().clone();

        assert_eq!(exit_code_of(&child, "mkdir sub && cd sub").await, 0);
        assert_eq!(
            pwd_of(&child).await,
            space,
            "the subagent starts in its space"
        );
        // Nor does it disturb the main agent's directory.
        assert_eq!(
            pwd_of(&parent).await,
            dunce::canonicalize(dir.path()).unwrap()
        );
    }

    #[cfg(unix)]
    #[test]
    fn container_directory_report_is_written_by_the_rendered_script() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let report = dir.path().join("it's report");
        let script = carry_cwd_script("mkdir sub && cd sub", &report.to_string_lossy())
            .expect("the trailer should render");
        let status = std::process::Command::new("sh")
            .args(["-c", &script])
            .current_dir(dir.path())
            .status()
            .expect("sh should run");
        assert!(status.success());
        let written = std::fs::read_to_string(&report).expect("the trailer writes the report");
        assert_eq!(
            PathBuf::from(written.trim_end()),
            dunce::canonicalize(dir.path().join("sub")).unwrap()
        );
        // The script's own exit status survives the trailer, whether the
        // script ends through `exit` or its last command fails.
        for (script, code) in [("exit 7", 7), ("cd sub; (exit 5)", 5)] {
            let status = std::process::Command::new("sh")
                .args([
                    "-c",
                    &carry_cwd_script(script, &report.to_string_lossy()).unwrap(),
                ])
                .current_dir(dir.path())
                .status()
                .expect("sh should run");
            assert_eq!(status.code(), Some(code), "{script}");
        }
        // The script's own syntax cannot swallow the trailer: an unterminated
        // here-document holding a quote still ends before the report.
        std::fs::remove_file(&report).expect("the report exists");
        let output = std::process::Command::new("sh")
            .args([
                "-c",
                &carry_cwd_script("cd sub; cat <<EOF\nit's", &report.to_string_lossy()).unwrap(),
            ])
            .current_dir(dir.path())
            .output()
            .expect("sh should run");
        assert!(output.status.success());
        // bash ends the unterminated body with a newline, dash does not.
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim_end(), "it's");
        let written = std::fs::read_to_string(&report).expect("the trailer writes the report");
        assert_eq!(
            PathBuf::from(written.trim_end()),
            dunce::canonicalize(dir.path().join("sub")).unwrap()
        );
    }

    /// Asserts `receiver` holds exactly one alert: a reset of the carried
    /// directory to `dir` for `reason`.
    #[cfg(unix)]
    fn assert_directory_reset(
        receiver: &BackgroundTaskReceiver,
        dir: impl AsRef<Path>,
        reason: DirectoryResetReason,
    ) {
        let alerts = receiver.take_job_alerts();
        match alerts.as_slice() {
            [JobAlert::DirectoryReset(reset)] => {
                assert_eq!(reset.dir, dir.as_ref());
                assert_eq!(reset.reason, reason);
            }
            other => panic!("expected one directory reset, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_carried_directory_raises_no_alert() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let receiver = tool.background_receiver();

        assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
        assert_eq!(exit_code_of(&tool, "true").await, 0);
        assert_eq!(exit_code_of(&tool, "pwd").await, 0);
        // A failure that stayed in its directory, and a direct command.
        assert_ne!(exit_code_of(&tool, "false").await, 0);
        assert_ne!(exit_code_of(&tool, "ls /nonexistent-directory").await, 0);
        assert!(receiver.take_job_alerts().is_empty());
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_failed_command_alerts_once_with_the_directory_commands_run_in() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let receiver = tool.background_receiver();
        let root = dunce::canonicalize(dir.path()).unwrap();

        assert_ne!(exit_code_of(&tool, "mkdir sub && cd sub && false").await, 0);
        assert_directory_reset(&receiver, &root, DirectoryResetReason::Failed);
        assert_eq!(pwd_of(&tool).await, root);
        assert!(receiver.take_job_alerts().is_empty());
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn exit_without_a_report_alerts_once() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let receiver = tool.background_receiver();
        let root = dunce::canonicalize(dir.path()).unwrap();

        assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
        assert_eq!(exit_code_of(&tool, "cd ..; exit 0").await, 0);
        assert_directory_reset(
            &receiver,
            root.join("sub"),
            DirectoryResetReason::Unreported,
        );
        assert_eq!(pwd_of(&tool).await, root.join("sub"));
        assert!(receiver.take_job_alerts().is_empty());
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_directory_outside_the_readable_paths_alerts_once() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let receiver = tool.background_receiver();
        let root = dunce::canonicalize(dir.path()).unwrap();

        // Readable to the sandbox, yet in none of the terminal's grants.
        assert_eq!(exit_code_of(&tool, "cd /usr").await, 0);
        assert_directory_reset(&receiver, &root, DirectoryResetReason::OutsideReadable);
        assert_eq!(pwd_of(&tool).await, root);
        assert!(receiver.take_job_alerts().is_empty());
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_removed_carried_directory_alerts_once() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let receiver = tool.background_receiver();
        let root = dunce::canonicalize(dir.path()).unwrap();

        assert_eq!(exit_code_of(&tool, "mkdir gone && cd gone").await, 0);
        assert!(receiver.take_job_alerts().is_empty());
        std::fs::remove_dir(root.join("gone")).unwrap();
        assert_eq!(pwd_of(&tool).await, root);
        assert_directory_reset(&receiver, &root, DirectoryResetReason::Removed);
        assert_eq!(pwd_of(&tool).await, root);
        assert!(receiver.take_job_alerts().is_empty());
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_container_directory_report_maps_through_the_workspace_mount() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let mount = MountRoot::new(
            tool.working_dir(),
            ContainerPath::new("/workspace").expect("absolute"),
        );
        let report = tool.working_dir().join(".cwd-container");
        let carry = CwdCarry {
            start: None,
            report: Some(report.clone()),
            container: Some(ContainerCarry {
                mount: mount.clone(),
                report: Some(
                    mount
                        .container_path(&report)
                        .expect("report is in the mount"),
                ),
                start: ContainerPath::new("/workspace").unwrap(),
            }),
            shell: true,
        };
        let receiver = tool.background_receiver();
        assert_eq!(
            carry
                .container
                .as_ref()
                .unwrap()
                .report
                .as_ref()
                .unwrap()
                .as_str(),
            format!(
                "/workspace/{}",
                report.file_name().unwrap().to_string_lossy()
            )
        );
        let carried = tool.carried_dir.as_ref().unwrap();

        // A directory inside the mount, spelled as the container sees it.
        std::fs::write(&report, "/workspace/sub/dir\n").unwrap();
        tool.record_carried_dir(&carry, true).await;
        assert_eq!(carried.get(), Some(tool.working_dir().join("sub/dir")));
        assert!(!report.exists(), "the report is consumed");

        assert!(
            receiver.take_job_alerts().is_empty(),
            "a carried directory raises no alert"
        );

        // Outside the mount, after a failure and an empty report: unchanged,
        // and each raises one alert naming where the next command starts.
        std::fs::write(&report, "/etc\n").unwrap();
        tool.record_carried_dir(&carry, true).await;
        assert_eq!(carried.get(), Some(tool.working_dir().join("sub/dir")));
        assert_directory_reset(
            &receiver,
            "/workspace",
            DirectoryResetReason::OutsideWorkspace,
        );
        std::fs::write(&report, "/workspace/other\n").unwrap();
        tool.record_carried_dir(&carry, false).await;
        assert_eq!(carried.get(), Some(tool.working_dir().join("sub/dir")));
        assert_directory_reset(&receiver, "/workspace", DirectoryResetReason::Failed);
        tool.record_carried_dir(&carry, true).await;
        assert_directory_reset(&receiver, "/workspace", DirectoryResetReason::Unreported);
        // A failure that stayed where it started changes nothing.
        std::fs::write(&report, "/workspace\n").unwrap();
        tool.record_carried_dir(&carry, false).await;
        assert!(receiver.take_job_alerts().is_empty());

        // The mapping back to the container for the next start.
        assert_eq!(
            mount
                .container_path(&tool.working_dir().join("sub/dir"))
                .unwrap()
                .as_str(),
            "/workspace/sub/dir"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_grant_outside_the_launchers_authority_is_refused() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let outside = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, parent) = authority_terminal(dir.path()).await;
        let error = launch(&parent, SubagentGrant::new().with_worktree(outside.path()))
            .await
            .expect_err("a launcher cannot hand on what it cannot write");
        assert!(
            matches!(error, SubagentGrantError::OutsideAuthority(_)),
            "{error}"
        );
    }

    #[cfg(unix)]
    fn commit_script(worktree: &Path, subject: &str) -> String {
        format!(
            "git -c user.name=agent -c user.email=agent@example.com -c commit.gpgSign=false -C '{}' commit --allow-empty -m '{subject}'",
            worktree.display()
        )
    }

    /// A repository with a worktree one can commit in, and the paths the
    /// commit grant is about, all canonical.
    #[cfg(unix)]
    struct CommitSetup {
        dir: tempfile::TempDir,
        worktree: PathBuf,
        /// The main repository's git directory.
        common: PathBuf,
        /// The worktree's entry in it.
        entry: PathBuf,
        /// The subagent's repository.
        subagent: PathBuf,
        parent: ConfiguredTestTool,
        _cache: crate::tool_runtime::tests::UnlockingTempDir,
    }

    #[cfg(unix)]
    impl CommitSetup {
        async fn new(namespace: &str) -> Self {
            let dir = tempfile::tempdir().expect("temp dir should be created");
            let worktree =
                crate::subagent::tests::repository_with_linked_worktree(dir.path(), namespace);
            let (cache, parent) = authority_terminal(dir.path()).await;
            let common = dunce::canonicalize(dir.path().join("repository/.git")).unwrap();
            let entry = common.join("worktrees").join(namespace);
            Self {
                worktree: dunce::canonicalize(worktree).unwrap(),
                subagent: entry.join("subagent"),
                common,
                entry,
                parent,
                dir,
                _cache: cache,
            }
        }

        async fn committing_child(&self, launcher: &ConfiguredTestTool) -> ConfiguredTestTool {
            launch(
                launcher,
                SubagentGrant::new().with_committing_worktree(&self.worktree),
            )
            .await
            .expect("the worktree can be granted with commit")
        }

        fn main_has(&self, id: &str) -> bool {
            crate::test_git::command()
                .args(["cat-file", "-e", id])
                .current_dir(&self.common)
                .output()
                .unwrap()
                .status
                .success()
        }

        fn main(&self, args: &[&str]) -> String {
            crate::subagent::tests::git_in(&self.common, args)
        }
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_sandboxed_commit_lands_in_the_subagents_repository_and_the_main_one_is_read_only() {
        let setup = CommitSetup::new("one").await;
        let child = setup.committing_child(&setup.parent).await;
        let ledger = child.commit_ledger().expect("a commit grant has a ledger");
        let mark = ledger.mark().await.expect("the namespace can be read");
        let before = setup.main(&["rev-parse", "refs/heads/subagent/one/work"]);

        assert_eq!(
            exit_code_of(&child, &commit_script(&setup.worktree, "authorized")).await,
            0,
            "a commit grant lets the subagent commit"
        );
        assert_eq!(
            setup.main(&["rev-parse", "refs/heads/subagent/one/work"]),
            before,
            "the commit is not in the main repository yet"
        );

        let commits = ledger.since(&mark).await.expect("commits can be listed");
        assert_eq!(commits.len(), 1, "{commits:?}");
        assert_eq!(commits[0].subject, "authorized");
        assert_eq!(commits[0].worktree, setup.worktree);
        assert!(setup.main_has(&commits[0].commit));
        assert_eq!(
            setup.main(&["rev-parse", "refs/heads/subagent/one/work"]),
            commits[0].commit
        );
        setup.main(&["fsck", "--strict", "--no-dangling"]);
    }

    /// The main agent's `git` in a committing worktree resolves the
    /// worktree's host-owned repository entry through the terminal's shim:
    /// no program the subagent's repository config names — fsmonitor,
    /// hooks, filters — and no `.git` file it replaced decides what runs.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn the_main_agents_git_in_a_committing_worktree_runs_nothing_the_subagent_chose() {
        use std::fmt::Write as _;
        use std::os::unix::fs::PermissionsExt as _;
        let setup = CommitSetup::new("guarded").await;
        let _child = setup.committing_child(&setup.parent).await;

        // A program only subagent-chosen configuration can reach.
        let marker = setup.dir.path().join("subagent-ran");
        let program = setup.dir.path().join("ran-by-git.sh");
        std::fs::write(
            &program,
            format!("#!/bin/sh\nprintf ran >> '{}'\n", marker.display()),
        )
        .unwrap();
        std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
        let hooks = setup.dir.path().join("evil-hooks");
        std::fs::create_dir(&hooks).unwrap();
        let pre_commit = hooks.join("pre-commit");
        std::fs::write(
            &pre_commit,
            format!("#!/bin/sh\nprintf hook >> '{}'\n", marker.display()),
        )
        .unwrap();
        std::fs::set_permissions(&pre_commit, std::fs::Permissions::from_mode(0o755)).unwrap();

        // Its repository's configuration names the program everywhere a
        // program can be named; the worktree's attributes bind the filter.
        let mut config = std::fs::read_to_string(setup.subagent.join("config")).unwrap();
        write!(
            config,
            "\n[core]\n\tfsmonitor = {}\n\thooksPath = {}\n[filter \"pwn\"]\n\tclean = {}\n\trequired = true\n",
            program.display(),
            hooks.display(),
            program.display()
        )
        .unwrap();
        std::fs::write(setup.subagent.join("config"), config).unwrap();
        std::fs::write(setup.worktree.join(".gitattributes"), "* filter=pwn\n").unwrap();

        let worktree = setup.worktree.display().to_string();
        for script in [
            format!("git -C '{worktree}' status"),
            format!("cd '{worktree}' && git status"),
            format!(
                "git -C '{worktree}' add -A && \
                 git -C '{worktree}' -c user.name=a -c user.email=a@a -c commit.gpgSign=false \
                 commit --allow-empty -m x"
            ),
        ] {
            assert_eq!(
                exit_code_of(&setup.parent, &script).await,
                0,
                "the ordinary git command should keep working: {script}"
            );
        }
        assert!(
            !marker.exists(),
            "no program of the subagent's choosing ran through the worktree's repository"
        );

        // A replaced `.git` file resolves nothing either: the shim acts on
        // the worktree's path, not on what its `.git` says.
        std::fs::write(
            setup.worktree.join(".git"),
            format!("gitdir: {}\n", setup.subagent.display()),
        )
        .unwrap();
        assert_eq!(
            exit_code_of(&setup.parent, &format!("git -C '{worktree}' status")).await,
            0
        );
        assert!(
            !marker.exists(),
            "a replaced .git file chose no program either"
        );

        // Git anywhere else is untouched.
        let repository = dunce::canonicalize(setup.dir.path().join("repository")).unwrap();
        assert_eq!(
            exit_code_of(
                &setup.parent,
                &format!("git -C '{}' log --oneline -1", repository.display())
            )
            .await,
            0,
            "git in unrelated repositories still reaches them"
        );
    }

    /// Nothing of the main repository's git directory is writable to a
    /// committing subagent: each attempt on the main repository fails, and the
    /// same command shape on the subagent's own repository, its positive
    /// control, succeeds.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    #[allow(clippy::too_many_lines)]
    async fn a_committing_subagent_can_change_nothing_the_main_repository_reads() {
        let setup = CommitSetup::new("two").await;
        let child = setup.committing_child(&setup.parent).await;

        // A fan-out directory known to be absent, and a loose object known to
        // exist, in the main object store.
        let absent = setup.common.join("objects/ff");
        let _ = std::fs::remove_dir(&absent);
        assert!(!absent.exists());
        let loose_dir = std::fs::read_dir(setup.common.join("objects"))
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .find(|path| {
                path.file_name()
                    .and_then(|name| name.to_str())
                    .is_some_and(|name| name.len() == 2 && name != "ff")
            })
            .expect("the initial commit left loose objects");
        let loose = std::fs::read_dir(&loose_dir)
            .unwrap()
            .next()
            .unwrap()
            .unwrap()
            .path();
        let loose_name = loose.file_name().unwrap().to_str().unwrap().to_string();
        let loose_dir_name = loose_dir.file_name().unwrap().to_str().unwrap().to_string();
        let loose_bytes = std::fs::read(&loose).unwrap();

        // The subagent's own repository, for the controls.
        let own = &setup.subagent;
        std::fs::create_dir_all(own.join("objects").join(&loose_dir_name)).unwrap();
        std::fs::write(
            own.join("objects").join(&loose_dir_name).join(&loose_name),
            b"own",
        )
        .unwrap();

        let main_objects = setup.common.join("objects");
        let own_objects = own.join("objects");
        let attempts: Vec<(&str, String, String)> = vec![
            (
                "create a fan-out directory",
                format!("mkdir '{}'", main_objects.join("ff").display()),
                format!("mkdir '{}'", own_objects.join("ff").display()),
            ),
            (
                "create an object in an existing fan-out directory",
                format!(
                    "touch '{}'",
                    main_objects.join(&loose_dir_name).join("new").display()
                ),
                format!(
                    "touch '{}'",
                    own_objects.join(&loose_dir_name).join("new").display()
                ),
            ),
            (
                "overwrite an existing loose object",
                format!("echo evil > '{}'", loose.display()),
                format!(
                    "echo evil > '{}'",
                    own_objects
                        .join(&loose_dir_name)
                        .join(&loose_name)
                        .display()
                ),
            ),
            (
                "replace an existing loose object by renaming over it",
                format!(
                    "echo evil > '{}/stage' && mv -f '{}/stage' '{}'",
                    own_objects.display(),
                    own_objects.display(),
                    loose.display()
                ),
                format!(
                    "echo evil > '{}/stage' && mv -f '{}/stage' '{}'",
                    own_objects.display(),
                    own_objects.display(),
                    own_objects
                        .join(&loose_dir_name)
                        .join(&loose_name)
                        .display()
                ),
            ),
            (
                "remove an existing loose object",
                format!("rm -f '{}'", loose.display()),
                format!(
                    "rm -f '{}'",
                    own_objects
                        .join(&loose_dir_name)
                        .join(&loose_name)
                        .display()
                ),
            ),
            (
                "create a pack",
                format!(
                    "touch '{}'",
                    main_objects.join("pack/pack-x.pack").display()
                ),
                format!("touch '{}'", own_objects.join("pack/pack-x.pack").display()),
            ),
            (
                "write an alternates file",
                format!(
                    "echo /tmp > '{}'",
                    main_objects.join("info/alternates").display()
                ),
                format!(
                    "echo /tmp > '{}'",
                    own_objects.join("info/scratch").display()
                ),
            ),
            (
                "move the worktree's branch",
                format!(
                    "echo {} > '{}'",
                    "a".repeat(40),
                    setup.common.join("refs/heads/subagent/two/work").display()
                ),
                format!(
                    "echo {} > '{}'",
                    "a".repeat(40),
                    own.join("refs/heads/subagent/two/scratch").display()
                ),
            ),
            (
                "rewrite the entry's HEAD",
                format!("echo evil >> '{}'", setup.entry.join("HEAD").display()),
                format!("echo evil >> '{}'", own.join("scratch-head").display()),
            ),
            (
                "rewrite the entry's index",
                format!("echo evil >> '{}'", setup.entry.join("index").display()),
                format!("echo evil >> '{}'", own.join("scratch-index").display()),
            ),
            (
                "rewrite the repository's configuration",
                format!("echo evil >> '{}'", setup.common.join("config").display()),
                format!("echo evil >> '{}'", own.join("scratch-config").display()),
            ),
        ];
        for (what, denied, control) in attempts {
            assert_ne!(
                exit_code_of(&child, &denied).await,
                0,
                "must not {what} in the main repository"
            );
            assert_eq!(
                exit_code_of(&child, &control).await,
                0,
                "the same command succeeds in the subagent's own repository: {what}"
            );
        }
        assert!(!absent.exists(), "no fan-out directory appeared");
        assert_eq!(
            std::fs::read(&loose).unwrap(),
            loose_bytes,
            "the object is as it was"
        );
        assert!(
            !std::fs::read_to_string(setup.common.join("config"))
                .unwrap()
                .contains("evil")
        );
        setup.main(&["fsck", "--strict", "--no-dangling"]);
    }

    /// Git in a repository the sandbox can read keeps working next to the
    /// redirected worktree: nothing is set process-wide.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn git_in_another_repository_works_inside_a_committing_subagents_sandbox() {
        let setup = CommitSetup::new("three").await;
        let other = setup.dir.path().join("other");
        std::fs::create_dir_all(&other).unwrap();
        crate::subagent::tests::git_in(&other, &["init", "--initial-branch=main"]);
        crate::subagent::tests::git_in(&other, &["commit", "--allow-empty", "-m", "elsewhere"]);
        let child = setup.committing_child(&setup.parent).await;

        assert!(
            stdout_of(
                &child,
                &format!("git -C '{}' log --oneline", other.display())
            )
            .await
            .contains("elsewhere")
        );
        let clone = child.working_dir().join("clone");
        assert_eq!(
            exit_code_of(
                &child,
                &format!("git clone '{}' '{}'", other.display(), clone.display())
            )
            .await,
            0
        );
        assert!(clone.join(".git").exists());
    }

    /// A subagent a committing subagent launches with the commit grant it
    /// holds works in the same repository: it sees its parent's commits and
    /// the parent's ledger reports both.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_committing_child_shares_its_parents_repository() {
        let setup = CommitSetup::new("four").await;
        let parent_subagent = setup.committing_child(&setup.parent).await;
        let parent_ledger = parent_subagent.commit_ledger().unwrap();
        let parent_mark = parent_ledger.mark().await.unwrap();
        assert_eq!(
            exit_code_of(
                &parent_subagent,
                &commit_script(&setup.worktree, "parent work")
            )
            .await,
            0
        );

        let child = setup.committing_child(&parent_subagent).await;
        let child_ledger = child.commit_ledger().unwrap();
        let child_mark = child_ledger.mark().await.unwrap();
        assert!(
            stdout_of(
                &child,
                &format!("git -C '{}' log --oneline", setup.worktree.display())
            )
            .await
            .contains("parent work"),
            "the child sees its parent's commit"
        );
        assert_eq!(
            exit_code_of(&child, &commit_script(&setup.worktree, "child work")).await,
            0
        );

        let child_commits = child_ledger.since(&child_mark).await.unwrap();
        assert_eq!(
            child_commits
                .iter()
                .map(|commit| commit.subject.as_str())
                .collect::<Vec<_>>(),
            ["child work"]
        );
        let parent_commits = parent_ledger.since(&parent_mark).await.unwrap();
        assert_eq!(
            parent_commits
                .iter()
                .map(|commit| commit.subject.as_str())
                .collect::<Vec<_>>(),
            ["parent work", "child work"]
        );
        for commit in &parent_commits {
            assert!(setup.main_has(&commit.commit));
        }
        setup.main(&["fsck", "--strict", "--no-dangling"]);
    }

    /// The import asks a sandbox that cannot read another repository for that
    /// repository's objects: they cannot reach the main one.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn objects_the_subagent_cannot_read_never_reach_the_main_repository() {
        let setup = CommitSetup::new("five").await;
        let child = setup.committing_child(&setup.parent).await;
        let outside = tempfile::tempdir().expect("temp dir should be created");
        std::fs::write(outside.path().join("secret.txt"), "secret").unwrap();
        crate::subagent::tests::git_in(outside.path(), &["init", "--initial-branch=main"]);
        crate::subagent::tests::git_in(outside.path(), &["add", "secret.txt"]);
        crate::subagent::tests::git_in(outside.path(), &["commit", "-m", "secret commit"]);
        let secret = crate::subagent::tests::git_in(outside.path(), &["rev-parse", "HEAD"]);
        // Reads are open except the denylist, so the other repository is
        // unreadable to the subagent only by an embedder denial.
        child
            .grants()
            .deny_read(std::fs::canonicalize(outside.path()).unwrap());
        assert_ne!(
            exit_code_of(
                &child,
                &format!("cat '{}'", outside.path().join("secret.txt").display())
            )
            .await,
            0,
            "the control: the sandbox cannot read the other repository"
        );

        let ledger = child.commit_ledger().unwrap();
        let mark = ledger.mark().await.unwrap();
        // The subagent's repository names a commit only the other one has,
        // and reaches its objects through symlinks, as its own: a process
        // that could read the other repository would pack them (the pack
        // leaves out only objects borrowed from an alternate).
        for entry in std::fs::read_dir(outside.path().join(".git/objects")).unwrap() {
            let entry = entry.unwrap();
            let name = entry.file_name();
            if name.len() == 2 {
                std::os::unix::fs::symlink(entry.path(), setup.subagent.join("objects").join(name))
                    .unwrap();
            }
        }
        std::fs::write(
            setup.subagent.join("refs/heads/subagent/five/stolen"),
            format!("{secret}\n"),
        )
        .unwrap();
        assert_eq!(
            crate::subagent::tests::git_in(
                &setup.subagent,
                &["--git-dir", ".", "cat-file", "-t", &secret]
            ),
            "commit",
            "the control: a git that could read the other repository packs its commit"
        );
        let error = ledger
            .since(&mark)
            .await
            .expect_err("the sandbox cannot read the objects it is asked to pack");
        assert!(
            matches!(error, crate::CommitLedgerError::Export { .. }),
            "the sandboxed git is what refuses: {error}"
        );
        assert!(!setup.main_has(&secret), "the secret commit never arrives");
        assert!(
            !setup
                .common
                .join("refs/heads/subagent/five/stolen")
                .exists(),
            "and no ref names it"
        );
    }

    /// The import budget is the terminal's operator setting: 1 GiB unless set,
    /// and a change through its handle reaches the subagents already running.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn the_import_budget_is_a_setting_adjustable_while_subagents_run() {
        let setup = CommitSetup::new("budget").await;
        let budget = setup.parent.subagent_import_budget();
        assert_eq!(budget.get(), DEFAULT_SUBAGENT_IMPORT_LIMIT);
        let child = setup.committing_child(&setup.parent).await;
        let ledger = child.commit_ledger().unwrap();
        let mark = ledger.mark().await.unwrap();
        assert_eq!(
            exit_code_of(
                &child,
                &commit_script(&setup.worktree, "heavier than 1 byte")
            )
            .await,
            0
        );

        budget.set(1);
        let error = ledger
            .since(&mark)
            .await
            .expect_err("the setting changed after the subagent launched applies to it");
        assert!(
            matches!(
                error,
                crate::CommitLedgerError::Export { .. } | crate::CommitLedgerError::Rejected { .. }
            ),
            "{error}"
        );
        budget.set(0);
        let listed = ledger.since(&mark).await.expect("zero bounds nothing");
        assert_eq!(listed.len(), 1);
    }

    /// A commit the main agent makes between runs is visible to the next run,
    /// and what the subagent had not yet shared survives the refresh.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn the_run_start_refresh_shows_new_main_commits_and_keeps_unimported_work() {
        let setup = CommitSetup::new("six").await;
        let child = setup.committing_child(&setup.parent).await;
        let ledger = child.commit_ledger().unwrap();
        ledger.mark().await.unwrap();
        assert_eq!(
            exit_code_of(&child, &commit_script(&setup.worktree, "unimported")).await,
            0
        );

        crate::subagent::tests::git_in(
            &dunce::canonicalize(setup.dir.path().join("repository")).unwrap(),
            &["commit", "--allow-empty", "-m", "main moved on"],
        );
        let log = |branch: &str| {
            format!(
                "git -C '{}' log --format=%s {branch}",
                setup.worktree.display()
            )
        };
        assert!(
            !stdout_of(&child, &log("main"))
                .await
                .contains("main moved on"),
            "the snapshot is the one from before"
        );

        ledger.mark().await.unwrap();
        assert!(
            stdout_of(&child, &log("main"))
                .await
                .contains("main moved on"),
            "the next run starts with the main agent's new commit"
        );
        assert!(
            stdout_of(&child, &log("subagent/six/work"))
                .await
                .contains("unimported"),
            "the subagent's own work survives the refresh"
        );
    }

    /// A container backend spells the repository's remote and runs the
    /// refresh, as the subagent, through the confined streamed exec.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_container_commit_grant_refreshes_through_the_confined_streamed_exec() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let worktree = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "seven");
        let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
        let child = launch(
            &parent,
            SubagentGrant::new().with_committing_worktree(&worktree),
        )
        .await
        .expect("a worktree inside the workspace can be granted commit");

        let subagent = dunce::canonicalize(dir.path())
            .unwrap()
            .join("repository/.git/worktrees/seven/subagent");
        let config = std::fs::read_to_string(subagent.join("config")).unwrap();
        assert!(
            config.contains("url = \"/workspace/repository/.git\""),
            "the remote is spelled as the container sees it: {config}"
        );
        assert!(
            config.contains("hooksPath = \"../repository/.git/hooks\""),
            "{config}"
        );

        // The recording exec prints nothing, so the import that follows the
        // refresh finds no report; only the refresh is of interest here.
        let _ = child.commit_ledger().unwrap().mark().await;
        let scripts = scripts.lock().unwrap().clone();
        let refresh = scripts
            .iter()
            .find(|script| script.contains("fetch"))
            .expect("the refresh ran in the container");
        assert!(refresh.contains("run --working-dir"), "{refresh}");
        assert!(
            refresh.contains("--grant '/workspace/repository/.git/worktrees/seven/subagent=rw'"),
            "{refresh}"
        );
        assert!(
            refresh.contains("git --git-dir /workspace/repository/.git/worktrees/seven/subagent"),
            "{refresh}"
        );
        assert!(refresh.contains("main-repository"), "{refresh}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_commit_grant_needs_a_linked_worktree_whose_repository_the_launcher_can_write() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let repository = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "two")
            .parent()
            .unwrap()
            .join("repository");
        let plain = dir.path().join("plain");
        std::fs::create_dir_all(&plain).unwrap();
        let (_cache, parent) = authority_terminal(dir.path()).await;

        let checkout = launch(
            &parent,
            SubagentGrant::new().with_committing_worktree(&repository),
        )
        .await
        .expect_err("a checkout holds its git data inside the grant");
        assert!(
            matches!(checkout, SubagentGrantError::RepositoryCheckout(_)),
            "{checkout}"
        );
        let not_git = launch(
            &parent,
            SubagentGrant::new().with_committing_worktree(&plain),
        )
        .await
        .expect_err("a plain directory has nothing to commit in");
        assert!(
            matches!(not_git, SubagentGrantError::NotAWorktree(_)),
            "{not_git}"
        );

        // A worktree inside the launcher's space whose repository is not.
        let elsewhere = tempfile::tempdir().expect("temp dir should be created");
        let foreign =
            crate::subagent::tests::repository_with_linked_worktree(elsewhere.path(), "three");
        let inside = dir.path().join("three");
        std::fs::rename(&foreign, &inside).unwrap();
        crate::subagent::tests::git_in(
            &elsewhere.path().join("repository"),
            &["worktree", "repair", inside.to_str().unwrap()],
        );
        let outside = launch(
            &parent,
            SubagentGrant::new().with_committing_worktree(&inside),
        )
        .await
        .expect_err("the launcher cannot hand on git data it cannot write");
        assert!(
            matches!(outside, SubagentGrantError::OutsideAuthority(_)),
            "{outside}"
        );
    }

    /// A subagent hands on only what it holds: commit where it was granted
    /// commit, and paths inside its own authority.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_nested_launch_never_exceeds_its_launcher() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let worktree = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "four");
        let sibling = dir.path().join("sibling");
        std::fs::create_dir_all(&sibling).unwrap();
        let (_cache, parent) = authority_terminal(dir.path()).await;

        let writer = launch(&parent, SubagentGrant::new().with_worktree(&worktree))
            .await
            .unwrap();
        let escalated = launch(
            &writer,
            SubagentGrant::new().with_committing_worktree(&worktree),
        )
        .await
        .expect_err("a subagent without commit cannot grant it");
        assert!(
            matches!(escalated, SubagentGrantError::CommitOutsideAuthority(_)),
            "{escalated}"
        );
        let sideways = launch(&writer, SubagentGrant::new().with_worktree(&sibling))
            .await
            .expect_err("a subagent cannot grant what it cannot write");
        assert!(
            matches!(sideways, SubagentGrantError::OutsideAuthority(_)),
            "{sideways}"
        );

        let committer = launch(
            &parent,
            SubagentGrant::new().with_committing_worktree(&worktree),
        )
        .await
        .unwrap();
        let handed_on = launch(
            &committer,
            SubagentGrant::new().with_committing_worktree(&worktree),
        )
        .await
        .expect("a subagent hands on the commit grant it holds");
        assert_eq!(
            handed_on.grants().snapshot().writable,
            committer.grants().snapshot().writable
        );
        assert!(handed_on.working_dir().starts_with(committer.working_dir()));
    }

    #[derive(Debug, Deserialize, JsonSchema)]
    struct LaunchProbeArgs {
        /// A directory to grant the launched subagent.
        #[serde(default)]
        worktree: Option<String>,
    }

    /// Launches a subagent from the terminal it is bound to and reports
    /// where it works.
    struct LaunchProbe {
        binding: TerminalBinding,
    }

    impl Tool for LaunchProbe {
        fn name(&self) -> Cow<'static, str> {
            "launch_probe".into()
        }

        type Arguments = LaunchProbeArgs;
        type Res = ToolResult;

        async fn call(
            &self,
            arguments: Self::Arguments,
            _cx: ToolContext,
        ) -> aither_core::Result<Self::Res> {
            let grant = arguments
                .worktree
                .into_iter()
                .fold(SubagentGrant::new(), SubagentGrant::with_worktree);
            let launched = self
                .binding
                .launcher()
                .create(grant, None, None, None)
                .await?;
            Ok(ToolResult::Text {
                text: launched.working_dir().display().to_string(),
            })
        }
    }

    /// A subagent that runs the launching command launches from its own
    /// terminal: the child lives in its space and gets nothing it lacks.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_subagent_running_the_launch_command_launches_with_its_own_authority() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let granted = dir.path().join("granted");
        let sibling = dir.path().join("sibling");
        std::fs::create_dir_all(&granted).unwrap();
        std::fs::create_dir_all(&sibling).unwrap();
        let tool = TerminalTool::new_exact(
            dir.path(),
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted");
        let mut builder = ToolRegistryBuilder::new();
        builder.configure_terminal_bound_tool("launch_probe", |binding: &TerminalBinding| {
            LaunchProbe {
                binding: binding.clone(),
            }
        });
        let parent = tool.with_registry(Arc::new(
            builder.build(test_outputs(dir.path().join("outputs"))),
        ));

        // The main agent launches the subagent through the command.
        let sibling_arg = sibling.to_str().unwrap();
        let from_main = query_control(
            parent.registry(),
            "launch_probe",
            &["--worktree", sibling_arg],
        )
        .await;
        assert_eq!(from_main["ok"], true, "{from_main}");

        let child = launch(&parent, SubagentGrant::new().with_worktree(&granted))
            .await
            .unwrap();
        let refused = query_control(
            child.registry(),
            "launch_probe",
            &["--worktree", sibling_arg],
        )
        .await;
        assert_eq!(refused["ok"], false, "{refused}");
        assert!(
            refused["error"]
                .as_str()
                .is_some_and(|error| error.contains("is not writable by the agent launching")),
            "{refused}"
        );
        let nested = query_control(
            child.registry(),
            "launch_probe",
            &["--worktree", granted.to_str().unwrap()],
        )
        .await;
        assert_eq!(nested["ok"], true, "{nested}");
        let grandchild = nested["payload"].to_string();
        let child_space = child.working_dir().display().to_string();
        assert!(
            grandchild.contains(&child_space),
            "the grandchild works inside its caller's space: {grandchild} vs {child_space}"
        );
    }

    /// Stands in for a host program inside sandboxed modes: answers with a
    /// refusal naming itself.
    #[cfg(unix)]
    struct SandboxedUname;

    #[cfg(unix)]
    #[derive(Debug, Deserialize, JsonSchema)]
    struct SandboxedUnameArgs {}

    #[cfg(unix)]
    impl Tool for SandboxedUname {
        fn name(&self) -> Cow<'static, str> {
            "uname".into()
        }

        type Arguments = SandboxedUnameArgs;
        type Res = ToolResult;

        fn call(
            &self,
            _arguments: Self::Arguments,
            _cx: ToolContext,
        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
            std::future::ready(Ok(ToolResult::text("sandboxed uname refused")))
        }
    }

    /// A command registered for sandboxed modes answers a sandboxed script,
    /// while an unsafe script resolves the same name on the host's `PATH`.
    #[cfg(unix)]
    #[tokio::test]
    async fn sandboxed_only_command_leaves_unsafe_scripts_the_host_program() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = TerminalTool::new_exact(
            dir.path(),
            TestPermissionHandler {
                allow_unsafe: true,
                ..Default::default()
            },
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted");
        let mut builder = ToolRegistryBuilder::new();
        builder.sandboxed_only(|sandboxed| sandboxed.configure_tool(SandboxedUname));
        let tool = tool.with_registry(Arc::new(
            builder.build(test_outputs(dir.path().join("outputs"))),
        ));

        let sandboxed = tool
            .call(
                terminal_args("sandboxed uname", "uname"),
                ToolContext::new(),
            )
            .await
            .expect("sandboxed call should succeed");
        let sandboxed = render_terminal_result(&sandboxed);
        assert!(
            sandboxed.contains("sandboxed uname refused"),
            "a sandboxed script reaches the command: {sandboxed}"
        );

        let unsafe_run = tool
            .call(
                TerminalArgs {
                    mode: TerminalExecutionMode::Unsafe,
                    ..terminal_args("host uname", "uname -s; ipc uname")
                },
                ToolContext::new(),
            )
            .await
            .expect("unsafe call should succeed");
        let unsafe_run = render_terminal_result(&unsafe_run);
        let host = std::process::Command::new("uname")
            .arg("-s")
            .output()
            .expect("the host runs uname");
        let host = String::from_utf8(host.stdout).expect("uname prints UTF-8");
        assert!(
            unsafe_run.contains(host.trim()),
            "an unsafe script runs the host program: {unsafe_run}"
        );
        assert!(
            !unsafe_run.contains("sandboxed uname refused"),
            "an unsafe script never reaches the command, not even through `ipc`: {unsafe_run}"
        );
    }

    /// A terminal that approves unsafe scripts, with the managed tools adopted.
    #[cfg(unix)]
    async fn unsafe_terminal(
        dir: &Path,
        shell_sessions: ShellSessionRegistry,
    ) -> TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured> {
        let tool = TerminalTool::new_exact(
            dir,
            TestPermissionHandler {
                allow_unsafe: true,
                ..Default::default()
            },
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted");
        tool.with_registry(Arc::new(
            ToolRegistryBuilder::new().build(test_outputs(dir.join("outputs"))),
        ))
    }

    /// Runs an approved unsafe `script` to its end and renders the result.
    #[cfg(unix)]
    async fn run_unsafe(
        tool: &TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
        script: &str,
    ) -> String {
        let result = tool
            .call(
                TerminalArgs {
                    mode: TerminalExecutionMode::Unsafe,
                    ..terminal_args("unsafe probe", script)
                },
                ToolContext::new(),
            )
            .await
            .expect("the unsafe call succeeds");
        render_terminal_result(&result)
    }

    /// An approved unsafe script reads a file its sandboxed sibling cannot:
    /// host access grants the invoking user's whole filesystem, not a grant
    /// list.
    #[cfg(unix)]
    #[tokio::test]
    async fn an_unsafe_script_reads_a_file_outside_every_grant() {
        let session = tempfile::tempdir().expect("temp dir should be created");
        let home = tempfile::Builder::new()
            .prefix("aither-unsafe-home-")
            .tempdir_in(std::env::var_os("HOME").expect("HOME is set"))
            .expect("a temp dir under the real home");
        let secret = home.path().join("secret.txt");
        std::fs::write(&secret, "token-value").expect("secret written");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = unsafe_terminal(session.path(), shell_sessions).await;

        let result = run_unsafe(&tool, &format!("cat {}", secret.display())).await;

        assert!(
            result.contains("token-value"),
            "the unsafe run read the file: {result}"
        );
    }

    /// Host access also writes wherever the invoking user may write.
    #[cfg(unix)]
    #[tokio::test]
    async fn an_unsafe_script_writes_a_file_outside_every_grant() {
        let session = tempfile::tempdir().expect("temp dir should be created");
        let outside = tempfile::tempdir().expect("temp dir should be created");
        let probe = outside.path().join("written.txt");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = unsafe_terminal(session.path(), shell_sessions).await;

        let result = run_unsafe(&tool, &format!("printf %s written > {}", probe.display())).await;

        assert!(
            !result.contains("Exit code"),
            "the unsafe run failed: {result}"
        );
        assert_eq!(
            std::fs::read_to_string(&probe).expect("written file reads back"),
            "written"
        );
    }

    /// Confined profiles deny exec in the shared temp directories; host access
    /// runs what a user put there.
    #[cfg(unix)]
    #[tokio::test]
    async fn an_unsafe_script_executes_a_program_written_to_the_temp_directory() {
        let session = tempfile::tempdir().expect("temp dir should be created");
        let outside = tempfile::tempdir().expect("temp dir should be created");
        let probe = outside.path().join("probe.sh");
        std::fs::write(&probe, "#!/bin/sh\necho executed\n").expect("probe written");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = unsafe_terminal(session.path(), shell_sessions).await;

        let result = run_unsafe(&tool, &format!("chmod +x {0} && {0}", probe.display())).await;

        assert!(
            result.contains("executed"),
            "the unsafe run ran the probe: {result}"
        );
    }

    /// No proxy stands between an unsafe script and the network: a loopback
    /// listener the test binds accepts its connection directly.
    #[cfg(unix)]
    #[tokio::test]
    async fn an_unsafe_script_connects_to_loopback_without_a_proxy() {
        let session = tempfile::tempdir().expect("temp dir should be created");
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let port = listener.local_addr().expect("local addr").port();
        let (accepted, got) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let _ = accepted.send(listener.accept());
        });
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = unsafe_terminal(session.path(), shell_sessions).await;

        let result = run_unsafe(
            &tool,
            &format!("/bin/bash -c 'exec 3<>/dev/tcp/127.0.0.1/{port}'"),
        )
        .await;

        assert!(
            !result.contains("Exit code"),
            "the unsafe run failed: {result}"
        );
        got.recv_timeout(Duration::from_secs(10))
            .expect("the listener accepted the connection")
            .expect("accept succeeded");
    }

    #[tokio::test]
    async fn a_subagent_of_a_subagent_gets_the_subagent_registry() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = TerminalTool::new_exact(
            dir.path(),
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted");
        let mut builder = ToolRegistryBuilder::new();
        builder.main_only(|reserved| reserved.configure_tool(ProbeEchoTool));
        let parent = tool.with_registry(Arc::new(
            builder.build(test_outputs(dir.path().join("outputs"))),
        ));
        assert_eq!(parent.registry().role(), crate::CommandRole::Main);

        let child = launch(&parent, SubagentGrant::new()).await.unwrap();
        let grandchild = launch(&child, SubagentGrant::new()).await.unwrap();
        for terminal in [&child, &grandchild] {
            assert_eq!(terminal.registry().role(), crate::CommandRole::Subagent);
            let refused =
                query_control(terminal.registry(), "probe_echo", &["--marker", "x"]).await;
            assert_eq!(refused["ok"], false, "{refused}");
            assert!(
                refused["error"]
                    .as_str()
                    .is_some_and(|error| error.contains("reserved for the main agent")),
                "{refused}"
            );
        }
        assert!(grandchild.working_dir().starts_with(child.working_dir()));
        let served = parent.clone().to_dyn();
        assert!(served.has_command("probe_echo"));
        assert_eq!(served.role(), crate::CommandRole::Main);
        assert_eq!(parent.binding().role(), crate::CommandRole::Main);
        assert_eq!(child.binding().role(), crate::CommandRole::Subagent);
        let child = child.to_dyn();
        assert!(!child.has_command("probe_echo"));
        assert_eq!(child.role(), crate::CommandRole::Subagent);
    }

    // ---- terminal runner ----------------------------------------------------

    /// Runs a script on the terminal serving it and answers with how the
    /// script ended and what it printed.
    #[cfg(unix)]
    struct CheckProbe {
        runner: TerminalRunner,
    }

    #[cfg(unix)]
    #[derive(Debug, Deserialize, JsonSchema)]
    struct CheckProbeArgs {
        /// The directory the script starts in.
        dir: String,
        /// The script.
        script: String,
        /// Seconds before the script is killed.
        timeout: u64,
    }

    #[cfg(unix)]
    impl Tool for CheckProbe {
        fn name(&self) -> Cow<'static, str> {
            "check_probe".into()
        }

        type Arguments = CheckProbeArgs;
        type Res = ToolResult;

        async fn call(
            &self,
            arguments: Self::Arguments,
            _cx: ToolContext,
        ) -> aither_core::Result<Self::Res> {
            let result = self
                .runner
                .run(TerminalScript::new(
                    arguments.script,
                    arguments.dir,
                    Duration::from_secs(arguments.timeout),
                ))
                .await?;
            let answer = match (&result.outcome, &result.stdout) {
                (CommandOutcome::Exited { code }, CommandStream::Inline { text }) => {
                    format!("exit={code} stdout={text}")
                }
                (CommandOutcome::Killed { .. }, _) => "killed".to_string(),
                other => panic!("a run ends exited with inline output or killed: {other:?}"),
            };
            Ok(ToolResult::text(answer))
        }
    }

    /// Calls `check_probe` on `terminal` and returns its answer.
    #[cfg(unix)]
    async fn run_check_probe(
        terminal: &ConfiguredTestTool,
        dir: &Path,
        script: &str,
        timeout: u64,
    ) -> String {
        let timeout = timeout.to_string();
        let answer = query_control(
            terminal.registry(),
            "check_probe",
            &[
                "--dir",
                dir.to_str().unwrap(),
                "--script",
                script,
                "--timeout",
                &timeout,
            ],
        )
        .await;
        assert_eq!(answer["ok"], true, "{answer}");
        answer["payload"]["content"].as_str().unwrap().to_string()
    }

    /// A terminal-bound command runs scripts on the terminal serving it,
    /// under that terminal's policy as it stands at the run — a grant made
    /// after the registry was bound included — and the runner ends with the
    /// terminal.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_terminal_bound_command_runs_a_script_under_its_terminals_policy() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let clone = tempfile::tempdir().expect("clone dir should be created");
        let read_only = tempfile::tempdir().expect("read-only dir should be created");
        let (_cache, shell_sessions) = prepared_test_registry().await;
        let tool = TerminalTool::new_exact(
            dir.path(),
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted")
        .with_readable_paths([read_only.path()]);
        let mut builder = ToolRegistryBuilder::new();
        builder.configure_terminal_bound_tool("check_probe", |binding: &TerminalBinding| {
            CheckProbe {
                runner: binding.runner().clone(),
            }
        });
        let terminal = tool.with_registry(Arc::new(
            builder.build(test_outputs(dir.path().join("outputs"))),
        ));
        terminal.grants().add_writable(clone.path());

        let clone_dir = std::fs::canonicalize(clone.path()).unwrap();
        let answer = run_check_probe(&terminal, &clone_dir, "pwd && touch checked", 30).await;
        assert!(answer.starts_with("exit=0 "), "{answer}");
        assert!(
            answer.contains(clone_dir.to_str().unwrap()),
            "the run starts in the directory it names: {answer}"
        );
        assert!(clone_dir.join("checked").exists());

        let read_only_dir = std::fs::canonicalize(read_only.path()).unwrap();
        let answer = run_check_probe(&terminal, &read_only_dir, "touch denied", 30).await;
        assert!(
            !answer.starts_with("exit=0 "),
            "a read-only grant stays read-only: {answer}"
        );
        assert!(!read_only_dir.join("denied").exists());

        let answer = run_check_probe(&terminal, &clone_dir, "sleep 30", 1).await;
        assert_eq!(answer, "killed", "the timeout kills the run");

        let runner = terminal.binding().runner().clone();
        let unsafe_run = runner
            .run(
                TerminalScript::new("true", &clone_dir, Duration::from_secs(30))
                    .with_mode(TerminalMode::Unsafe),
            )
            .await;
        assert!(
            matches!(
                unsafe_run,
                Err(TerminalRunError::Terminal(TerminalError::PermissionDenied(
                    TerminalMode::Unsafe
                )))
            ),
            "an unsafe run is put to the permission handler: {unsafe_run:?}"
        );

        drop(terminal);
        let gone = runner
            .run(TerminalScript::new(
                "true",
                &clone_dir,
                Duration::from_secs(30),
            ))
            .await;
        assert!(
            matches!(gone, Err(TerminalRunError::TerminalGone)),
            "the runner ends with its terminal: {gone:?}"
        );
    }

    // ---- call identity ------------------------------------------------------

    use aither_core::llm::{AgentIdentity, SubagentIdentity, ToolCallId};

    /// Answers with the identity its call carries, and reports it to the test
    /// the moment it arrives. With `hold` set it then waits for the test's go
    /// signal, so two calls can be made to overlap inside their handlers.
    struct IdentityProbe {
        entered: async_channel::Sender<CallIdentity>,
        hold: Option<Receiver<()>>,
    }

    #[derive(Debug, Deserialize, JsonSchema)]
    struct IdentityProbeArgs {}

    impl Tool for IdentityProbe {
        fn name(&self) -> Cow<'static, str> {
            "identity_probe".into()
        }

        type Arguments = IdentityProbeArgs;
        type Res = ToolResult;

        async fn call(
            &self,
            _arguments: Self::Arguments,
            cx: ToolContext,
        ) -> aither_core::Result<Self::Res> {
            let identity = cx.identity().expect("a terminal call identifies itself");
            self.entered.send(identity.clone()).await.unwrap();
            if let Some(hold) = &self.hold {
                hold.recv().await.unwrap();
            }
            Ok(ToolResult::text(format!("seen={}", identity.call())))
        }
    }

    /// Reports the identity of every command call the registry serves.
    struct IdentityObserver(async_channel::Sender<(String, Option<CallIdentity>)>);

    impl crate::CommandObserver for IdentityObserver {
        async fn command_called(&self, call: &crate::CommandCall<'_>) {
            self.0
                .send((call.name.to_string(), call.call.cloned()))
                .await
                .unwrap();
        }
    }

    fn call_identity(id: &str, agent: AgentIdentity) -> CallIdentity {
        CallIdentity::new(ToolCallId::new(id), agent)
    }

    /// Fails the test instead of hanging it when `future` does not finish.
    async fn within_deadline<T>(future: impl std::future::Future<Output = T>) -> T {
        futures_lite::future::or(async { Some(future.await) }, async {
            async_io::Timer::after(Duration::from_secs(60)).await;
            None
        })
        .await
        .expect("the probe should finish within its deadline")
    }

    #[cfg(unix)]
    async fn identity_terminal(
        dir: &Path,
        probe: IdentityProbe,
        observer: async_channel::Sender<(String, Option<CallIdentity>)>,
    ) -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        ConfiguredTestTool,
    ) {
        let (cache, shell_sessions) = prepared_test_registry().await;
        let tool = TerminalTool::new_exact(
            dir,
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted");
        let mut builder = ToolRegistryBuilder::new();
        builder.configure_tool(probe);
        builder.observe_commands(crate::AnyCommandObserver::new(IdentityObserver(observer)));
        (
            cache,
            tool.with_registry(Arc::new(builder.build(test_outputs(dir.join("outputs"))))),
        )
    }

    /// A command a `terminal` call's script runs is handed that call's id and
    /// agent, and so is the registry's observer.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn an_ipc_command_receives_the_identity_of_its_terminal_call() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (entered, entered_rx) = async_channel::unbounded();
        let (observed, observed_rx) = async_channel::unbounded();
        let (_cache, tool) = identity_terminal(
            dir.path(),
            IdentityProbe {
                entered,
                hold: None,
            },
            observed,
        )
        .await;
        let subagent = AgentIdentity::Subagent(SubagentIdentity::new(
            "explore",
            Some(call_identity("call_parent", AgentIdentity::Main)),
        ));
        let identity = call_identity("call_a", subagent);

        let result = within_deadline(tool.call(
            terminal_args("identity probe", "identity_probe"),
            ToolContext::new().with_identity(identity.clone()),
        ))
        .await
        .expect("terminal call should succeed");

        assert!(
            render_terminal_result(&result).contains("seen=call_a"),
            "{}",
            render_terminal_result(&result)
        );
        assert_eq!(entered_rx.recv().await.unwrap(), identity);
        assert_eq!(
            observed_rx.recv().await.unwrap(),
            ("identity_probe".to_string(), Some(identity))
        );
    }

    /// Two overlapping `terminal` calls each get their own id in the command
    /// their script runs, even though both commands are in flight at once.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn concurrent_terminal_calls_deliver_their_own_ids() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (entered, entered_rx) = async_channel::unbounded();
        let (hold_tx, hold) = async_channel::unbounded();
        let (observed, _observed_rx) = async_channel::unbounded();
        let (_cache, tool) = identity_terminal(
            dir.path(),
            IdentityProbe {
                entered,
                hold: Some(hold),
            },
            observed,
        )
        .await;

        let run = |id: &'static str| {
            let tool = &tool;
            async move {
                let result = tool
                    .call(
                        terminal_args("identity probe", "identity_probe"),
                        ToolContext::new().with_identity(call_identity(id, AgentIdentity::Main)),
                    )
                    .await
                    .expect("terminal call should succeed");
                render_terminal_result(&result)
            }
        };
        let release = async {
            // Both handlers are inside their command before either answers.
            let mut inside = [
                entered_rx.recv().await.unwrap(),
                entered_rx.recv().await.unwrap(),
            ];
            inside.sort_by(|a, b| a.call().as_str().cmp(b.call().as_str()));
            assert_eq!(
                inside
                    .iter()
                    .map(|identity| identity.call().as_str())
                    .collect::<Vec<_>>(),
                ["call_a", "call_b"]
            );
            hold_tx.send(()).await.unwrap();
            hold_tx.send(()).await.unwrap();
        };
        let (a, b, ()) =
            within_deadline(async { futures::join!(run("call_a"), run("call_b"), release) }).await;

        assert!(a.contains("seen=call_a") && !a.contains("call_b"), "{a}");
        assert!(b.contains("seen=call_b") && !b.contains("call_a"), "{b}");
    }

    /// A command run by a backgrounded job is told the id of the call that
    /// started the job, long after that call returned.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_backgrounded_job_keeps_the_id_of_the_call_that_started_it() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (entered, entered_rx) = async_channel::unbounded();
        let (observed, observed_rx) = async_channel::unbounded();
        let (_cache, tool) = identity_terminal(
            dir.path(),
            IdentityProbe {
                entered,
                hold: None,
            },
            observed,
        )
        .await;
        let identity = call_identity("call_bg", AgentIdentity::Main);

        let mut args = terminal_args("identity probe", "identity_probe");
        args.background = true;
        within_deadline(tool.call(args, ToolContext::new().with_identity(identity.clone())))
            .await
            .expect("terminal call should succeed");

        assert_eq!(within_deadline(entered_rx.recv()).await.unwrap(), identity);
        assert_eq!(
            within_deadline(observed_rx.recv()).await.unwrap().1,
            Some(identity)
        );
    }

    /// Records the script every container exec runs.
    #[cfg(unix)]
    struct RecordingExec {
        scripts: Arc<std::sync::Mutex<Vec<String>>>,
    }

    #[cfg(unix)]
    impl crate::ContainerExec for RecordingExec {
        fn exec(
            &self,
            _container_id: &str,
            script: &str,
            _working_dir: &str,
            _kill_rx: Receiver<()>,
            _stdin_rx: Receiver<Vec<u8>>,
            _lifetime: ExecLifetime,
        ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
        {
            self.scripts.lock().unwrap().push(script.to_string());
            std::future::ready(Ok(ContainerExecOutcome::Completed {
                output: std::process::Output {
                    status: std::os::unix::process::ExitStatusExt::from_raw(0),
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                },
                killed: Vec::new(),
            }))
        }

        fn exec_streamed(
            &self,
            _container_id: &str,
            script: &str,
            _working_dir: &str,
            _kill_rx: Receiver<()>,
            _stdin_rx: Receiver<Vec<u8>>,
            _stdout: Sender<Vec<u8>>,
        ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
        {
            self.scripts.lock().unwrap().push(script.to_string());
            std::future::ready(Ok(ContainerExecOutcome::Completed {
                output: std::process::Output {
                    status: std::os::unix::process::ExitStatusExt::from_raw(0),
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                },
                killed: Vec::new(),
            }))
        }
    }

    /// A terminal whose home backend is a recording container, which mounts
    /// `workspace` as `/workspace` when one is given.
    #[cfg(unix)]
    async fn recording_container_terminal(
        dir: &Path,
        workspace: Option<&Path>,
    ) -> (Arc<std::sync::Mutex<Vec<String>>>, ConfiguredTestTool) {
        let scripts = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = ContainerShellRuntime::new(
            "aither-test-confinement",
            crate::ContainerIpcRoute::new(
                "host.docker.internal",
                crate::BridgeAddress::try_from(std::net::IpAddr::from([127, 0, 0, 1]))
                    .expect("loopback binds the bridge"),
            ),
            crate::AnyContainerExec::new(Arc::new(RecordingExec {
                scripts: scripts.clone(),
            })),
        );
        let runtime = match workspace {
            Some(workspace) => runtime.with_workspace_mount(MountRoot::new(
                workspace,
                ContainerPath::new(CONTAINER_EXEC_WORKING_DIR).expect("the workspace is absolute"),
            )),
            None => runtime,
        };
        let container_tools =
            crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools());
        let shell_sessions = ShellSessionRegistry::new(ShellRuntimeAvailability {
            local: false,
            container: true,
            ssh: false,
        })
        .with_container_runtime(runtime)
        .with_test_container_tools(container_tools, "aither-test-confinement".to_string());
        let tool = TerminalTool::new_exact(
            dir,
            TestPermissionHandler::default(),
            executor_core::tokio::TokioGlobal,
        )
        .await
        .expect("terminal tool should initialize")
        .adopt_prepared_tools(shell_sessions)
        .await
        .expect("prepared tools should be adopted");
        let parent = tool.with_registry(Arc::new(
            ToolRegistryBuilder::new().build(test_outputs(dir)),
        ));
        (scripts, parent)
    }

    /// A container terminal's jobs are the container's: they carry the
    /// marker its memory reader finds them by, are registered as running
    /// there, and the terminal judges the container's memory too.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn container_jobs_are_marked_and_placed_in_the_container() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (scripts, parent) = recording_container_terminal(dir.path(), None).await;
        assert!(parent.container_probe().is_some());
        assert!(parent.job_memory().has_container());

        // A background job, whose completion is held so the registry still
        // keeps it to be read.
        let receiver = parent.background_receiver();
        parent
            .run_background(background_args("mark", "echo marked-command"))
            .await
            .expect("terminal call should succeed");
        let task_id = started_task_id(&receiver);
        let _completed = wait_for_completed_task(&receiver, &task_id).await;

        let scripts = scripts.lock().unwrap().clone();
        let script = scripts
            .iter()
            .find(|script| script.contains("marked-command"))
            .expect("the command ran");
        let jobs = parent.job_registry().list().await;
        let job = jobs
            .iter()
            .find(|job| job.script == "echo marked-command")
            .expect("the job is registered");
        assert_eq!(job.place, crate::JobPlace::Container);
        assert!(
            script.contains(&format!(
                "export {}='{}'",
                crate::memory::JOB_MARKER_ENV,
                job.task_id
            )),
            "{script}"
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_local_terminal_judges_no_container() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(60),
            Duration::from_secs(600),
        )
        .await;
        assert!(tool.container_probe().is_none());
        assert!(!tool.job_memory().has_container());
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn container_session_runs_the_main_agent_unconfined_and_a_subagent_confined() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let granted = dir.path().join("granted");
        std::fs::create_dir_all(&granted).unwrap();
        let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
        let child = launch(&parent, SubagentGrant::new().with_worktree(&granted))
            .await
            .expect("a directory inside the workspace can be granted");

        assert_eq!(exit_code_of(&parent, "echo main-command").await, 0);
        assert_eq!(exit_code_of(&child, "echo subagent-command").await, 0);

        let scripts = scripts.lock().unwrap().clone();
        let main = scripts
            .iter()
            .find(|script| script.contains("main-command"))
            .expect("the main agent's command ran");
        let sub = scripts
            .iter()
            .find(|script| script.contains("subagent-command"))
            .expect("the subagent's command ran");
        assert!(
            !main.contains(" run --"),
            "the container is the main agent's boundary: {main}"
        );
        assert!(sub.contains("\"$MAY_IPC_BIN\" run --working-dir"), "{sub}");
        assert!(!sub.contains("--isolation permissive"), "{sub}");
        let root = dunce::canonicalize(dir.path()).unwrap();
        let space = child
            .working_dir()
            .strip_prefix(&root)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            sub.contains(&format!("--working-dir '/workspace/{space}'")),
            "{sub}"
        );
        let granted_name = granted.file_name().unwrap().to_str().unwrap();
        assert!(
            sub.contains(&format!("--grant '/workspace/{granted_name}=rw'")),
            "{sub}"
        );
    }

    /// The shim inside a container compares its working directory against
    /// the worktree map: the map must spell the paths the mount resolves —
    /// host spellings would leave the worktree unprotected, the `git` shim
    /// unable to hit it.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_containers_git_map_spells_the_worktree_and_gitdir_the_container_way() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let worktree =
            crate::subagent::tests::repository_with_linked_worktree(dir.path(), "mapped");
        let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
        let _child = launch(
            &parent,
            SubagentGrant::new().with_committing_worktree(&worktree),
        )
        .await
        .expect("the worktree can be granted with commit");

        assert_eq!(exit_code_of(&parent, "echo mapped-worktree").await, 0);

        let script = scripts
            .lock()
            .unwrap()
            .iter()
            .find(|script| script.contains("mapped-worktree"))
            .expect("the main agent's command ran")
            .clone();
        assert!(
            script.contains("export AITHER_GIT_WORKTREE_PATH_0=/workspace/mapped"),
            "{script}"
        );
        assert!(
            script.contains(
                "export AITHER_GIT_WORKTREE_GITDIR_0=/workspace/repository/.git/worktrees/mapped"
            ),
            "{script}"
        );
        let host = dunce::canonicalize(&worktree)
            .unwrap()
            .display()
            .to_string();
        assert!(
            !script.contains(&host),
            "the shim sees no host spelling: {script}"
        );
    }

    /// A subagent whose paths the container cannot express is refused when
    /// it is launched, not when it first runs a command.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_container_subagent_outside_the_workspace_mount_is_refused_at_launch() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let mounted = dir.path().join("mounted");
        let granted = dir.path().join("granted");
        std::fs::create_dir_all(&mounted).unwrap();
        std::fs::create_dir_all(&granted).unwrap();

        let (_scripts, parent) = recording_container_terminal(dir.path(), Some(&mounted)).await;
        let error = launch(&parent, SubagentGrant::new().with_worktree(&granted))
            .await
            .expect_err("the subagent's paths are not inside the mount");
        assert!(
            matches!(error, SubagentGrantError::OutsideContainerMount { .. }),
            "{error}"
        );

        let (_scripts, unmounted) = recording_container_terminal(dir.path(), None).await;
        let error = launch(&unmounted, SubagentGrant::new())
            .await
            .expect_err("a container without a declared mount cannot confine a subagent");
        assert!(
            matches!(error, SubagentGrantError::NoContainerMount),
            "{error}"
        );
    }

    /// A configured local terminal in `dir` whose registry `configure` set
    /// up, for the command policy tests.
    #[cfg(unix)]
    async fn policy_tool(
        dir: &Path,
        configure: impl FnOnce(&mut ToolRegistryBuilder),
    ) -> (
        crate::tool_runtime::tests::UnlockingTempDir,
        TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
    ) {
        let (cache, shell_sessions) = prepared_test_registry().await;
        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
            TerminalTool::new_exact(
                dir,
                TestPermissionHandler::default(),
                executor_core::tokio::TokioGlobal,
            )
            .await
            .expect("terminal tool should initialize")
            .adopt_prepared_tools(shell_sessions)
            .await
            .expect("prepared tools should be adopted")
            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
                local: true,
                container: false,
                ssh: false,
            });
        let mut registry = ToolRegistryBuilder::new();
        configure(&mut registry);
        let registry = Arc::new(registry.build(tool.output_store().clone()));
        (cache, tool.with_registry(registry))
    }

    /// Refuses every shell script that runs `program`, and reports how each
    /// script it was asked about ended.
    struct RefuseProgram {
        program: &'static str,
        ends: async_channel::Sender<crate::ScriptOutcome>,
    }

    impl RefuseProgram {
        fn refusal(&self) -> String {
            format!(
                "`{}` does not run here; kill the PID you started.",
                self.program
            )
        }
    }

    impl crate::CommandPolicy for RefuseProgram {
        type State = ();

        fn check(
            &self,
            script: &crate::ScriptCheck<'_>,
            _state: &(),
        ) -> impl Future<Output = crate::PolicyDecision> + Send {
            let runs = matches!(
                script.shell,
                Some(Ok(shell)) if shell.commands().iter().any(|command| command.program() == self.program)
            );
            std::future::ready(if runs {
                crate::PolicyDecision::Refuse(PolicyRefusal::new(self.refusal()))
            } else {
                crate::PolicyDecision::Allow
            })
        }

        async fn ended(&self, end: &crate::ScriptEnd<'_>, _state: &()) {
            self.ends
                .send(end.outcome)
                .await
                .expect("the test holds the receiver");
        }
    }

    /// Refuses a script identical to the agent's last one that exited 0;
    /// a script that failed is not remembered.
    struct RefuseRepeat;

    #[derive(Default)]
    struct Repeats {
        /// Task id → script, for the scripts allowed and not yet ended.
        pending: std::sync::Mutex<std::collections::HashMap<String, String>>,
        last_success: std::sync::Mutex<Option<String>>,
    }

    impl crate::CommandPolicy for RefuseRepeat {
        type State = Repeats;

        fn check(
            &self,
            script: &crate::ScriptCheck<'_>,
            state: &Repeats,
        ) -> impl Future<Output = crate::PolicyDecision> + Send {
            let decision = if state.last_success.lock().unwrap().as_deref() == Some(script.script) {
                crate::PolicyDecision::Refuse(PolicyRefusal::unchanged_read(
                    "It would print what it printed last time.",
                ))
            } else {
                state
                    .pending
                    .lock()
                    .unwrap()
                    .insert(script.task_id.to_string(), script.script.to_string());
                crate::PolicyDecision::Allow
            };
            std::future::ready(decision)
        }

        fn ended(
            &self,
            end: &crate::ScriptEnd<'_>,
            state: &Repeats,
        ) -> impl Future<Output = ()> + Send {
            let script = state.pending.lock().unwrap().remove(end.task_id);
            if end.outcome == (crate::ScriptOutcome::Exited { code: 0 }) {
                *state.last_success.lock().unwrap() = script;
            }
            std::future::ready(())
        }
    }

    /// A policy's refusal is what the caller reads, before any part of the
    /// script runs, in the foreground and the background alike; the policy
    /// is told the script never ran.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_policy_refusal_reaches_the_caller_before_the_script_runs() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (ends, ended) = async_channel::unbounded();
        let policy = RefuseProgram {
            program: "pkill",
            ends,
        };
        let text = policy.refusal();
        let (_cache, tool) =
            policy_tool(dir.path(), |registry| registry.command_policy(policy)).await;
        let marker = dir.path().join("ran");
        let script = format!("touch {}; sudo env pkill anything", marker.display());

        let error = tool
            .call(
                terminal_args("name-based kill", &script),
                ToolContext::new(),
            )
            .await
            .expect_err("the policy refuses the script");
        assert_eq!(error.to_string(), text);
        let refusal = error
            .downcast_ref::<PolicyRefusal>()
            .expect("the refusal stays typed for the agent loop");
        assert!(!refusal.is_unchanged_read());
        let error = tool
            .run_background(terminal_args("name-based kill", &script))
            .await
            .expect_err("the policy refuses the background script");
        assert_eq!(error.to_string(), text);
        assert!(!marker.exists(), "no part of a refused script runs");
        assert_eq!(ended.try_recv(), Ok(crate::ScriptOutcome::NotRun));
        assert_eq!(ended.try_recv(), Ok(crate::ScriptOutcome::NotRun));

        let result = tool
            .call(
                terminal_args("mention a killer", "echo pkill; exit 3"),
                ToolContext::new(),
            )
            .await
            .expect("a script that only names the program runs");
        assert!(render_terminal_result(&result).contains("pkill"));
        assert_eq!(
            ended.try_recv(),
            Ok(crate::ScriptOutcome::Exited { code: 3 }),
            "the policy learns how the script ended before its result returns"
        );
    }

    /// With no policy the sandbox refuses nothing: `grep` and a foreground
    /// `sleep` run.
    #[cfg(unix)]
    #[tokio::test]
    async fn with_no_policy_grep_and_a_foreground_sleep_run() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = policy_tool(dir.path(), |_| {}).await;
        let result = tool
            .call(
                terminal_args(
                    "grep and sleep",
                    "printf 'needle\\n' | grep needle; sleep 1; echo slept",
                ),
                ToolContext::new(),
            )
            .await
            .expect("nothing is refused");
        let rendered = render_terminal_result(&result);
        assert!(rendered.contains("needle"), "{rendered}");
        assert!(rendered.contains("slept"), "{rendered}");
    }

    /// A policy keeps state for its agent across calls, and learns of each
    /// end before the call returns: a repeat of a script that succeeded is
    /// refused, a failed one runs again.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_policy_state_follows_each_script_to_its_end() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = policy_tool(dir.path(), |registry| {
            registry.command_policy(RefuseRepeat);
        })
        .await;
        assert_eq!(exit_code_of(&tool, "exit 3").await, 3);
        assert_eq!(
            exit_code_of(&tool, "exit 3").await,
            3,
            "a failed script is not remembered, so it runs again"
        );
        assert_eq!(exit_code_of(&tool, "echo once").await, 0);
        let error = tool
            .call(terminal_args("again", "echo once"), ToolContext::new())
            .await
            .expect_err("a repeat of a successful script is refused");
        assert!(
            error
                .downcast_ref::<PolicyRefusal>()
                .is_some_and(PolicyRefusal::is_unchanged_read),
            "{error}"
        );
        assert_eq!(exit_code_of(&tool, "echo twice").await, 0);
    }

    use crate::monitor::{MonitorArgs, MonitorEnd, MonitorSource, MonitorTool};

    /// Job alerts the monitor produces until `ended` or `duration` passes.
    async fn monitor_alerts(
        receiver: &BackgroundTaskReceiver,
        duration: Duration,
    ) -> Vec<JobAlert> {
        let deadline = std::time::Instant::now() + duration;
        let mut alerts = Vec::new();
        while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) {
            let Some(event) = receiver.recv_event_timeout(remaining).await else {
                break;
            };
            let BackgroundTaskEvent::Alert(alert) = event else {
                continue;
            };
            let ended = matches!(alert, JobAlert::MonitorEnded(_));
            alerts.push(alert);
            if ended {
                break;
            }
        }
        alerts
    }

    fn monitor_command(command: &str, timeout_secs: u64) -> MonitorArgs {
        MonitorArgs {
            source: MonitorSource::Command {
                command: command.to_string(),
                language: ScriptLanguage::Shell,
            },
            interval_secs: 1,
            filter: None,
            stop_on: None,
            kill_on_stop: false,
            stall_secs: None,
            timeout_secs,
        }
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn monitored_command_delivers_increments_and_its_exit() {
        let dir = tempfile::tempdir().unwrap();
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(7200),
            Duration::from_secs(600),
        )
        .await;
        let monitor = MonitorTool::new(tool.clone());
        monitor
            .call(
                monitor_command("echo a; sleep 2; echo b", 30),
                ToolContext::new(),
            )
            .await
            .expect("monitor starts");

        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(20)).await;
        let increments: Vec<&[String]> = alerts
            .iter()
            .filter_map(|alert| match alert {
                JobAlert::MonitorIncrement(increment) => Some(increment.lines.as_slice()),
                _ => None,
            })
            .collect();
        assert!(
            increments.iter().any(|inc| *inc == ["a".to_string()]),
            "the first line is delivered as it arrives: {alerts:?}"
        );
        assert!(
            increments.iter().any(|inc| *inc == ["b".to_string()]),
            "the later line is delivered in a following increment: {alerts:?}"
        );
        assert!(
            alerts.iter().any(|alert| matches!(
                alert,
                JobAlert::MonitorEnded(ended)
                    if matches!(ended.end, MonitorEnd::Exited { exit_code: 0 })
            )),
            "the monitor reports the command's exit: {alerts:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn monitor_filter_keeps_matching_lines_and_stop_on_ends() {
        let dir = tempfile::tempdir().unwrap();
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(7200),
            Duration::from_secs(600),
        )
        .await;
        let monitor = MonitorTool::new(tool.clone());
        let mut args = monitor_command(
            "printf 'keep one\\ndrop\\nkeep two\\nlast\\n'; sleep 60",
            30,
        );
        args.filter = Some("^keep".to_string());
        args.stop_on = Some("two".to_string());
        monitor
            .call(args, ToolContext::new())
            .await
            .expect("monitor starts");

        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(20)).await;
        let lines: Vec<&String> = alerts
            .iter()
            .filter_map(|alert| match alert {
                JobAlert::MonitorIncrement(increment) => Some(&increment.lines),
                _ => None,
            })
            .flatten()
            .collect();
        assert!(
            lines.iter().all(|line| line.starts_with("keep")),
            "filter drops non-matching lines: {lines:?}"
        );
        assert!(
            !lines.iter().any(|line| *line == "last"),
            "lines after the stop match are not delivered: {lines:?}"
        );
        assert!(
            alerts.iter().any(|alert| matches!(
                alert,
                JobAlert::MonitorEnded(ended)
                    if matches!(&ended.end, MonitorEnd::StopMatched { line } if line == "keep two")
            )),
            "the first stop_on match ends the monitor: {alerts:?}"
        );
        tool.job_registry().kill_running().await;
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn monitor_rejects_a_timeout_over_the_cap_and_times_out_at_the_deadline() {
        let dir = tempfile::tempdir().unwrap();
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(7200),
            Duration::from_secs(600),
        )
        .await;
        let monitor = MonitorTool::new(tool.clone());
        let refused = monitor
            .call(monitor_command("sleep 60", 7201), ToolContext::new())
            .await;
        assert!(refused.is_err(), "timeout_secs over the cap is refused");

        monitor
            .call(monitor_command("sleep 60", 2), ToolContext::new())
            .await
            .expect("monitor starts");
        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
        assert!(
            alerts.iter().any(|alert| matches!(
                alert,
                JobAlert::MonitorEnded(ended) if matches!(ended.end, MonitorEnd::TimedOut)
            )),
            "the deadline kills the run and reports a timeout: {alerts:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn monitor_reports_a_stall_once() {
        let dir = tempfile::tempdir().unwrap();
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(7200),
            Duration::from_secs(600),
        )
        .await;
        let monitor = MonitorTool::new(tool.clone());
        let mut args = monitor_command("sleep 4; echo done", 30);
        args.stall_secs = Some(1);
        monitor
            .call(args, ToolContext::new())
            .await
            .expect("monitor starts");

        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
        let stalls = alerts
            .iter()
            .filter(|alert| matches!(alert, JobAlert::MonitorStalled(_)))
            .count();
        assert_eq!(stalls, 1, "a stall is reported once: {alerts:?}");
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn monitored_file_delivers_appends_and_refuses_an_unreadable_file() {
        let dir = tempfile::tempdir().unwrap();
        let (_cache, tool) = configured_test_terminal(
            dir.path(),
            Duration::from_secs(10),
            Duration::from_secs(7200),
            Duration::from_secs(600),
        )
        .await;
        let monitor = MonitorTool::new(tool.clone());
        let unreadable = monitor
            .call(
                MonitorArgs {
                    source: MonitorSource::File {
                        file: "/etc/sudoers".to_string(),
                    },
                    ..monitor_command("true", 30)
                },
                ToolContext::new(),
            )
            .await;
        assert!(
            unreadable.is_err(),
            "a file the sandbox may not read is refused"
        );

        let path = tool.working_dir().join("followed.log");
        std::fs::write(&path, "existing\n").unwrap();
        monitor
            .call(
                MonitorArgs {
                    source: MonitorSource::File {
                        file: "followed.log".to_string(),
                    },
                    ..monitor_command("true", 30)
                },
                ToolContext::new(),
            )
            .await
            .expect("monitor starts");
        async_io::Timer::after(Duration::from_millis(1500)).await;
        let mut file = std::fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap();
        std::io::Write::write_all(&mut file, b"appended\n").unwrap();
        std::fs::rename(&path, tool.working_dir().join("followed.log.1")).unwrap();
        std::fs::write(&path, "rotated\n").unwrap();
        async_io::Timer::after(Duration::from_millis(500)).await;
        let mut file = std::fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap();
        std::io::Write::write_all(&mut file, b"after\n").unwrap();

        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
        let lines: Vec<&String> = alerts
            .iter()
            .filter_map(|alert| match alert {
                JobAlert::MonitorIncrement(increment) => Some(&increment.lines),
                _ => None,
            })
            .flatten()
            .collect();
        assert!(
            !lines.iter().any(|line| *line == "existing"),
            "content written before the monitor started is not delivered: {lines:?}"
        );
        for expected in ["appended", "rotated", "after"] {
            assert!(
                lines.iter().any(|line| *line == expected),
                "appended line {expected:?} is delivered, across rotation: {lines:?}"
            );
        }
        tool.job_registry().kill_running().await;
    }

    // ---- runtime grants -----------------------------------------------------

    /// The done-when case: a writable grant added at runtime reaches every
    /// command launched afterwards, while a command already running keeps
    /// the grants it launched with.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_runtime_writable_grant_reaches_new_commands_not_running_ones() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let outside = tempfile::tempdir().expect("outside dir should be created");
        let late_target = outside.path().join("late.txt");
        // Launched before the grant; its write happens after the grant is
        // added but its grant snapshot was taken at launch.
        let task_id = start_background_job(
            &tool,
            &format!("sleep 2; echo x > '{}'", late_target.display()),
        )
        .await;
        let receiver = tool.background_receiver();

        assert_ne!(
            exit_code_of(
                &tool,
                &format!("echo x > '{}'", outside.path().join("denied.txt").display())
            )
            .await,
            0,
            "a write outside the sandbox is denied before the grant"
        );
        tool.grants().add_writable(outside.path());
        assert_eq!(
            exit_code_of(
                &tool,
                &format!(
                    "echo x > '{}'",
                    outside.path().join("granted.txt").display()
                )
            )
            .await,
            0,
            "the command after the grant writes the approved dir"
        );

        let completed = wait_for_completed_task(&receiver, &task_id).await;
        let _ = completed.result;
        assert!(
            !late_target.exists(),
            "a command launched before the grant keeps its launch grants"
        );
    }

    /// A grant taken back no longer reaches the next command: the write the
    /// grant allowed is denied again.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_removed_grant_is_gone_from_the_next_command() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let outside = tempfile::tempdir().expect("outside dir should be created");
        tool.grants().add_writable(outside.path());
        assert_eq!(
            exit_code_of(
                &tool,
                &format!("touch '{}'", outside.path().join("granted.txt").display())
            )
            .await,
            0,
            "the granted dir is writable"
        );
        tool.grants().remove_writable(outside.path());
        assert_ne!(
            exit_code_of(
                &tool,
                &format!("touch '{}'", outside.path().join("revoked.txt").display())
            )
            .await,
            0,
            "the command after the removal is denied the write"
        );
    }

    /// Cloned terminals share one grant store: a grant added through the
    /// original's handle reaches the clone's next command.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_cloned_terminal_sees_runtime_grants() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let clone = tool.clone();
        let outside = tempfile::tempdir().expect("outside dir should be created");
        tool.grants().add_writable(outside.path());
        assert_eq!(
            exit_code_of(
                &clone,
                &format!("touch '{}'", outside.path().join("shared.txt").display())
            )
            .await,
            0,
            "the clone's commands carry grants added through the original"
        );
    }

    /// A subagent's derived grants follow its parent's readable list live:
    /// a readable grant added to the parent after the subagent launches is
    /// readable inside it; a writable grant on the parent never becomes
    /// writable in the subagent (it lands on the subagent's readable side).
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_subagent_sees_runtime_readable_but_never_writable_parent_grants() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, parent) = authority_terminal(dir.path()).await;
        let readable_dir = tempfile::tempdir().expect("readable dir");
        let writable_dir = tempfile::tempdir().expect("writable dir");
        std::fs::write(readable_dir.path().join("r.txt"), "data").unwrap();
        std::fs::write(writable_dir.path().join("w.txt"), "data").unwrap();

        let child = launch(&parent, SubagentGrant::new())
            .await
            .expect("subagent launches");
        parent.grants().add_readable(readable_dir.path());
        parent.grants().add_writable(writable_dir.path());

        assert_eq!(
            exit_code_of(
                &child,
                &format!("cat '{}'", readable_dir.path().join("r.txt").display())
            )
            .await,
            0,
            "a runtime readable grant on the parent reaches the subagent"
        );
        let denied_dir = tempfile::tempdir().expect("denied dir");
        std::fs::write(denied_dir.path().join("d.txt"), "data").unwrap();
        parent
            .grants()
            .deny_read(std::fs::canonicalize(denied_dir.path()).unwrap());
        assert_ne!(
            exit_code_of(
                &child,
                &format!("cat '{}'", denied_dir.path().join("d.txt").display())
            )
            .await,
            0,
            "a read denial added to the parent after launch reaches the subagent"
        );
        assert_ne!(
            exit_code_of(
                &child,
                &format!("touch '{}'", writable_dir.path().join("x.txt").display())
            )
            .await,
            0,
            "a parent writable grant is never writable inside the subagent"
        );
    }

    /// A shell launched before the grant keeps the grants it started
    /// with — its sandbox was fixed when it spawned — while every new
    /// command picks the grant up (`add_writable` documents this).
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_running_shell_keeps_the_grants_it_started_with() {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        let (_cache, tool) = authority_terminal(dir.path()).await;
        let outside = tempfile::tempdir().expect("outside dir should be created");
        let shell_target = outside.path().join("from_shell.txt");

        // A shell session launched before the grant: its write lands after
        // the grant was added, but inside its launch-time sandbox.
        let task_id = start_background_job(
            &tool,
            &format!("sleep 2; touch '{}'", shell_target.display()),
        )
        .await;
        let receiver = tool.background_receiver();
        tool.grants().add_writable(outside.path());
        let fresh_target = outside.path().join("fresh.txt");
        assert_eq!(
            exit_code_of(&tool, &format!("touch '{}'", fresh_target.display())).await,
            0,
            "a fresh command picks up the grant"
        );
        let _ = wait_for_completed_task(&receiver, &task_id).await;
        assert!(
            !shell_target.exists(),
            "the shell launched before the grant is still sandboxed without it"
        );
    }
}