codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
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
use super::*;

use crate::tools::spec::ToolContext;
use serde_json::{Value, json};
use tempfile::tempdir;

#[cfg(windows)]
use windows::Win32::Foundation::{DUPLICATE_HANDLE_OPTIONS, DuplicateHandle, HANDLE};
#[cfg(windows)]
use windows::Win32::System::Threading::GetCurrentProcess;

// `env_lock` serializes tests that mutate the process environment.
#[cfg(any(unix, windows))]
use std::sync::{Mutex, OnceLock};

#[cfg(any(unix, windows))]
fn env_lock() -> &'static Mutex<()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
}

const BACKGROUND_COMPLETION_WAIT_MS: u64 = 30_000;

#[test]
fn lowercase_bash_schema_is_small_contract() {
    let schema = LowercaseBashTool.input_schema();
    assert_eq!(schema["required"], json!(["command"]));
    assert_eq!(schema["additionalProperties"], false);
    assert_eq!(
        schema["properties"]
            .as_object()
            .expect("properties")
            .keys()
            .cloned()
            .collect::<std::collections::BTreeSet<_>>(),
        ["command", "justification", "sandbox_permissions", "timeout"]
            .into_iter()
            .map(str::to_string)
            .collect()
    );
    assert!(!BashTool::new("Bash").model_visible());
}

#[test]
fn contract_bash_nonzero_is_an_error_with_status_after_output() {
    let error = finish_contract_bash_result(
        ShellResult {
            task_id: None,
            status: ShellStatus::Failed,
            exit_code: Some(7),
            stdout: "before".to_string(),
            stderr: String::new(),
            duration_ms: 1,
            stdout_len: 6,
            stderr_len: 0,
            stdout_omitted: 0,
            stderr_omitted: 0,
            stdout_truncated: false,
            stderr_truncated: false,
            sandboxed: false,
            sandbox_type: None,
            sandbox_denied: false,
        },
        None,
        &ToolContext::new("."),
    )
    .expect_err("nonzero must be a failed tool call");
    assert!(
        error
            .to_string()
            .ends_with("before\n\nCommand exited with code 7")
    );
}

#[cfg(unix)]
#[tokio::test]
async fn lowercase_bash_returns_one_ordered_stream() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path());
    let result = LowercaseBashTool
        .execute(
            json!({"command": "printf out-1; printf err-2 >&2; printf out-3"}),
            &context,
        )
        .await
        .expect("bash");
    assert_eq!(result.content, "out-1err-2out-3");
}

#[cfg(unix)]
#[tokio::test]
async fn lowercase_bash_keeps_raw_command_under_readonly_policy() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path())
        .with_shell_policy(crate::worker_profile::ShellPolicy::ReadOnly);
    let result = LowercaseBashTool
        .execute(json!({"command": "pwd"}), &context)
        .await
        .expect("read-only bash");
    assert_eq!(
        result.content.trim(),
        workspace
            .path()
            .canonicalize()
            .expect("canonical workspace")
            .display()
            .to_string()
    );
}

#[tokio::test]
async fn lowercase_bash_readonly_refusal_names_work_mode() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path())
        .with_shell_policy(crate::worker_profile::ShellPolicy::ReadOnly);
    let result = LowercaseBashTool
        .execute(json!({"command": "touch blocked-by-plan"}), &context)
        .await
        .expect("policy refusal is a normal tool result");

    assert!(!result.success);
    assert!(result.content.contains("Work mode (`/mode work`)"));
    assert!(!result.content.contains("Act mode"));
    assert!(!workspace.path().join("blocked-by-plan").exists());
}

#[tokio::test]
async fn lowercase_bash_timeout_uses_seconds_and_fails() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path());
    let error = LowercaseBashTool
        .execute(
            json!({"command": sleep_command(2), "timeout": 0.01}),
            &context,
        )
        .await
        .expect_err("timeout must fail");
    assert!(
        error
            .to_string()
            .contains("Command timed out after 0.01 seconds"),
        "{error}"
    );
}

fn execute_shell(
    manager: &mut ShellManager,
    command: &str,
    working_dir: Option<&str>,
    timeout_ms: u64,
    background: bool,
) -> Result<ShellResult> {
    manager.execute_with_options_env(
        command,
        working_dir,
        timeout_ms,
        background,
        None,
        false,
        None,
        HashMap::new(),
    )
}

#[test]
fn deleted_saved_workspace_reports_path_and_recovery_before_spawn() {
    let workspace = tempdir().expect("workspace");
    let stale = workspace.path().join("deleted-session-workspace");
    let mut manager = ShellManager::new(stale.clone());

    let error = execute_shell(&mut manager, "echo should-not-run", None, 1_000, false)
        .expect_err("missing saved workspace must fail before shell spawn");
    let message = error.to_string();
    assert!(message.contains("saved session workspace is unavailable"));
    assert!(message.contains(&stale.display().to_string()));
    assert!(message.contains("working_dir") || message.contains("cwd"));
    assert!(message.contains("resume/fork"));
}

#[test]
fn explicit_missing_working_dir_is_not_misreported_as_session_corruption() {
    let workspace = tempdir().expect("workspace");
    let missing = workspace.path().join("explicit-missing");
    let mut manager = ShellManager::new(workspace.path().to_path_buf());

    let error = execute_shell(
        &mut manager,
        "echo should-not-run",
        missing.to_str(),
        1_000,
        false,
    )
    .expect_err("missing explicit cwd must fail before shell spawn");
    let message = error.to_string();
    assert!(message.contains("requested working directory is unavailable"));
    assert!(message.contains(&missing.display().to_string()));
    assert!(!message.contains("saved session workspace"));
}

#[cfg(not(target_env = "ohos"))]
#[test]
fn pty_exit_status_preserves_high_windows_code_losslessly() {
    let raw = 0xC000_0005;
    let status = ShellExitStatus::from_pty(portable_pty::ExitStatus::with_exit_code(raw));

    assert!(!status.success);
    assert_eq!(status.code, Some(i64::from(raw)));
    assert_eq!(
        exit_code_label(status.code),
        "exit code 3221225477 (0xC0000005)"
    );
    assert_eq!(exit_code_hex(status.code).as_deref(), Some("0xC0000005"));
}

#[cfg(not(target_env = "ohos"))]
#[test]
fn ordinary_pty_exit_status_keeps_concise_label() {
    let status = ShellExitStatus::from_pty(portable_pty::ExitStatus::with_exit_code(127));

    assert_eq!(status.code, Some(127));
    assert_eq!(exit_code_label(status.code), "exit code 127");
    assert_eq!(exit_code_hex(status.code), None);
}

#[cfg(windows)]
#[test]
fn std_windows_exit_status_reinterprets_signed_dword() {
    assert_eq!(std_exit_code_i64(0xC000_0005_u32 as i32), 0xC000_0005);
}

#[cfg(windows)]
const JOB_OBJECT_QUERY_ACCESS: u32 = 0x0004;

#[cfg(windows)]
fn duplicate_job_without_terminate_access(job: WindowsJob) -> WindowsJob {
    let process = unsafe { GetCurrentProcess() };
    let mut limited_handle = HANDLE::default();

    unsafe {
        DuplicateHandle(
            process,
            job.handle,
            process,
            &mut limited_handle,
            JOB_OBJECT_QUERY_ACCESS,
            false,
            DUPLICATE_HANDLE_OPTIONS(0),
        )
        .expect("duplicate job handle without terminate access");
    }

    drop(job);
    WindowsJob {
        handle: limited_handle,
    }
}

fn echo_command(message: &str) -> String {
    format!("echo {message}")
}

fn sleep_command(seconds: u64) -> String {
    let dispatcher = crate::shell_dispatcher::global_dispatcher();
    if dispatcher.kind().is_powershell() {
        return format!("Start-Sleep -Seconds {seconds}");
    }
    #[cfg(windows)]
    {
        let ping_count = seconds.saturating_add(1);
        format!("ping 127.0.0.1 -n {ping_count} > NUL")
    }
    #[cfg(not(windows))]
    {
        format!("sleep {seconds}")
    }
}

fn sleep_then_echo_command(seconds: u64, message: &str) -> String {
    let dispatcher = crate::shell_dispatcher::global_dispatcher();
    if dispatcher.kind().is_powershell() {
        return format!("Start-Sleep -Seconds {seconds}; echo {message}");
    }
    #[cfg(windows)]
    {
        let ping_count = seconds.saturating_add(1);
        format!("ping 127.0.0.1 -n {ping_count} > NUL && echo {message}")
    }
    #[cfg(not(windows))]
    {
        format!("sleep {seconds} && echo {message}")
    }
}

fn echo_stdin_command() -> String {
    let dispatcher = crate::shell_dispatcher::global_dispatcher();
    if dispatcher.kind().is_powershell() {
        return "[Console]::In.ReadToEnd()".to_string();
    }
    #[cfg(windows)]
    {
        "more".to_string()
    }
    #[cfg(not(windows))]
    {
        "cat".to_string()
    }
}

fn network_restricted_context(tmp: &std::path::Path) -> ToolContext {
    ToolContext::new(tmp)
        .with_elevated_sandbox_policy(ExecutionSandboxPolicy::WorkspaceWrite {
            writable_roots: vec![tmp.to_path_buf()],
            network_access: false,
            exclude_tmpdir: false,
            exclude_slash_tmp: false,
        })
        .with_shell_network_denied_hint(
            "Shell command blocked: Plan mode runs shell commands in a network-restricted sandbox.",
        )
}

fn failed_network_shell_result(stdout: &str, stderr: &str) -> ShellResult {
    ShellResult {
        task_id: None,
        status: ShellStatus::Failed,
        exit_code: Some(6),
        stdout: stdout.to_string(),
        stderr: stderr.to_string(),
        duration_ms: 25,
        stdout_len: stdout.len(),
        stderr_len: stderr.len(),
        stdout_omitted: 0,
        stderr_omitted: 0,
        stdout_truncated: false,
        stderr_truncated: false,
        sandboxed: true,
        sandbox_type: Some("seatbelt".to_string()),
        sandbox_denied: false,
    }
}

#[cfg(unix)]
const SHELL_DESCENDANT_HELPER_ENV: &str = "CODEWHALE_SHELL_DESCENDANT_HELPER";
#[cfg(unix)]
const SHELL_DESCENDANT_PID_FILE_ENV: &str = "CODEWHALE_SHELL_DESCENDANT_PID_FILE";

#[cfg(unix)]
#[test]
fn shell_descendant_helper_process() {
    if std::env::var(SHELL_DESCENDANT_HELPER_ENV).ok().as_deref() != Some("1") {
        return;
    }
    let pid_file =
        PathBuf::from(std::env::var(SHELL_DESCENDANT_PID_FILE_ENV).expect("descendant pid file"));
    let mut child = Command::new("sleep")
        .arg("30")
        .spawn()
        .expect("spawn cheap descendant");
    std::fs::write(pid_file, child.id().to_string()).expect("write descendant pid");
    std::thread::sleep(Duration::from_secs(30));
    let _ = child.wait();
}

#[cfg(unix)]
fn wait_for_shell_pid_file(path: &Path) -> libc::pid_t {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        if let Ok(raw) = std::fs::read_to_string(path)
            && let Ok(pid) = raw.trim().parse()
        {
            return pid;
        }
        assert!(
            Instant::now() < deadline,
            "descendant pid file never appeared"
        );
        std::thread::sleep(Duration::from_millis(25));
    }
}

#[cfg(unix)]
fn wait_for_shell_pid_exit(pid: libc::pid_t) -> bool {
    let deadline = Instant::now() + Duration::from_secs(2);
    loop {
        if unsafe { libc::kill(pid, 0) } != 0
            && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
        {
            return true;
        }
        if Instant::now() >= deadline {
            return false;
        }
        std::thread::sleep(Duration::from_millis(25));
    }
}

fn wait_for_completed_shell(manager: &mut ShellManager, task_id: &str) -> ShellResult {
    let deadline = Instant::now() + Duration::from_millis(BACKGROUND_COMPLETION_WAIT_MS);

    loop {
        let result = manager
            .get_output(task_id, true, 1_000)
            .expect("get_output");
        if result.status != ShellStatus::Running || Instant::now() >= deadline {
            return result;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

#[test]
fn shell_owner_registers_before_spawn_and_silent_work_stays_live() {
    let work = crate::work_graph::new_shared_work_runtime(
        crate::tools::todo::new_shared_todo_list(),
        crate::tools::plan::new_shared_plan_state(),
    );
    let lifecycle = ShellWorkLifecycle {
        work: work.clone(),
        session_id: "shell-session".to_string(),
    };

    {
        let _guard = ShellSpawnIntentGuard::new(
            Some(lifecycle.clone()),
            "shell_spawn_failure",
            "missing-program",
        )
        .expect("register spawn intent");
    }
    lifecycle
        .register("shell_silent", "sleep 30")
        .expect("register silent shell");
    lifecycle
        .observe("shell_silent", &ShellStatus::Running, 1, 0)
        .expect("live owner observation");
    lifecycle
        .observe("shell_silent", &ShellStatus::Running, 2, 512)
        .expect("growing output observation");

    let graph = work
        .capture(Some("shell-session"))
        .expect("capture")
        .expect("graph")
        .graph;
    let operation = |external: &str| {
        graph.nodes.iter().find(|node| {
            node.binding
                .as_ref()
                .is_some_and(|binding| binding.external == external)
        })
    };
    assert_eq!(
        operation("shell:shell_spawn_failure").map(|node| node.state),
        Some(crate::work_graph::NodeState::Failed),
        "dropping an armed spawn guard must terminalize pre-spawn failure"
    );
    let silent = operation("shell:shell_silent").expect("silent shell operation");
    assert_eq!(silent.state, crate::work_graph::NodeState::Active);
    let observation = silent
        .binding
        .as_ref()
        .and_then(|binding| binding.last_observation.as_ref())
        .expect("last shell observation");
    assert_eq!(observation.seq, 2);
    assert_eq!(
        observation
            .output
            .as_ref()
            .and_then(crate::work_graph::EvidenceRef::raw_bytes),
        Some(512)
    );
}

#[test]
fn exec_shell_parallel_flags_are_input_aware() {
    let tool = BashTool::new("Bash");
    let readonly = json!({"command": "git status -s"});
    assert!(tool.supports_parallel_for(&readonly));
    assert!(tool.is_read_only_for(&readonly));
    assert_eq!(
        tool.approval_requirement_for(&readonly),
        ApprovalRequirement::Auto
    );

    for input in [
        json!({"command": "fd -e rs ."}),
        json!({"command": "fd -H --type f src"}),
        json!({"command": "git grep TODO crates/tui/src/tools"}),
        json!({"action": "run", "command": "gh issue list --limit 10"}),
        json!({"action": "run", "command": "gh issue view 5287"}),
    ] {
        assert!(tool.supports_parallel_for(&input), "{input:?}");
        assert!(tool.is_read_only_for(&input), "{input:?}");
        assert_eq!(
            tool.approval_requirement_for(&input),
            ApprovalRequirement::Auto,
            "{input:?}"
        );
    }

    for input in [
        json!({"command": "git status -s", "background": true}),
        json!({"command": "git status -s", "background": "false"}),
        json!({"command": "git status -s", "stdin": ""}),
        json!({"action": "wait", "command": "pwd", "task_id": "shell_1"}),
        json!({"action": "interact", "command": "pwd", "task_id": "shell_1"}),
        json!({"action": "cancel", "command": "pwd", "task_id": "shell_1"}),
        json!({"action": 3, "command": "pwd"}),
        json!({"command": "pwd", "unexpected": true}),
        json!({"command": "cargo build"}),
        json!({"command": "bash -lc 'git status'"}),
        json!({"command": "sh -c 'rg TODO crates'"}),
        json!({"command": "PAGER=./pwn.sh git log"}),
        json!({"command": "GH_PAGER=./pwn.sh gh issue view 5287"}),
        json!({"command": "rg ${9:---pre=./repo-script} needle ."}),
        json!({"command": "rg ${9:---hostname-bin=./repo-script} needle ."}),
        json!({"command": "fd ${9:---exec} ./repo-script"}),
        json!({"command": "rg $PATTERN ."}),
        json!({"command": "rg *.rs ."}),
        json!({"command": "bash -lc 'rg TODO crates | head'"}),
        json!({"command": "fd -x ./pwn.sh"}),
        json!({"command": "fd --exec ./pwn.sh"}),
        json!({"command": "fd -uHtx ./pwn.sh"}),
        json!({"command": "rg --pre /tmp/evil.sh needle ."}),
        json!({"command": "rg --hostname-bin ./repo-script --hyperlink-format=file://{host}{path} needle ."}),
        json!({"command": "rg --search-zip needle ."}),
        json!({"command": "rg -z needle ."}),
        json!({"command": "git grep -O needle"}),
        json!({"command": "git grep -nO needle"}),
        json!({"command": "git grep --textconv needle"}),
        json!({"command": "git diff --ext-diff HEAD"}),
        json!({"command": "git diff --textconv HEAD"}),
        json!({"command": "git log --show-signature -1"}),
        json!({"command": "git show --format=%GS HEAD"}),
        json!({"command": "gh issue close 5287"}),
        json!({"command": "gh issue view 5287 > issue.txt"}),
        json!({"command": "gh pr checks 42 --watch"}),
        json!({"command": "gh issue view 5287 -R git.example.com/o/r"}),
    ] {
        assert!(!tool.supports_parallel_for(&input), "{input:?}");
        assert!(!tool.is_read_only_for(&input), "{input:?}");
        assert_eq!(
            tool.approval_requirement_for(&input),
            ApprovalRequirement::Required,
            "{input:?}"
        );
    }

    assert!(tool.starts_detached_for(&json!({
        "command": "cargo check --workspace",
        "background": true
    })));
    assert!(tool.starts_detached_for(&json!({
        "command": "cargo test -p codewhale-tui --bins",
        "tty": true
    })));
    assert!(!tool.starts_detached_for(&json!({
        "command": "cargo check --workspace"
    })));
    assert!(!tool.starts_detached_for(&json!({
        "command": "cargo check --workspace",
        "background": true,
        "interactive": true
    })));
}

#[tokio::test]
async fn readonly_shell_refuses_raw_string_external_backend() {
    struct Backend(std::sync::atomic::AtomicBool);
    #[async_trait::async_trait]
    impl crate::sandbox::backend::SandboxBackend for Backend {
        async fn exec(
            &self,
            _cmd: &str,
            _env: &std::collections::HashMap<String, String>,
        ) -> anyhow::Result<crate::sandbox::backend::SandboxOutput> {
            self.0.store(true, std::sync::atomic::Ordering::SeqCst);
            Ok(crate::sandbox::backend::SandboxOutput {
                stdout: String::new(),
                stderr: String::new(),
                exit_code: 0,
            })
        }
    }

    let tmp = tempdir().expect("tempdir");
    let backend = std::sync::Arc::new(Backend(std::sync::atomic::AtomicBool::new(false)));
    let mut context = ToolContext::new(tmp.path().to_path_buf())
        .with_shell_policy(crate::worker_profile::ShellPolicy::ReadOnly);
    context.sandbox_backend = Some(backend.clone());
    let error = BashTool::read_only("Bash")
        .execute(json!({"action": "run", "command": "pwd"}), &context)
        .await
        .expect_err("raw-string backend must not receive a classifier-approved argv")
        .to_string();
    assert!(error.contains("raw command string"), "{error}");
    assert!(!backend.0.load(std::sync::atomic::Ordering::SeqCst));
}

#[tokio::test]
async fn lowercase_bash_refuses_non_streaming_external_backend() {
    struct Backend(std::sync::atomic::AtomicBool);
    #[async_trait::async_trait]
    impl crate::sandbox::backend::SandboxBackend for Backend {
        async fn exec(
            &self,
            _cmd: &str,
            _env: &std::collections::HashMap<String, String>,
        ) -> anyhow::Result<crate::sandbox::backend::SandboxOutput> {
            self.0.store(true, std::sync::atomic::Ordering::SeqCst);
            unreachable!("lowercase bash must fail before external dispatch")
        }
    }

    let workspace = tempdir().expect("workspace");
    let backend = std::sync::Arc::new(Backend(std::sync::atomic::AtomicBool::new(false)));
    let mut context = ToolContext::new(workspace.path());
    context.sandbox_backend = Some(backend.clone());
    let error = LowercaseBashTool
        .execute(json!({"command": "pwd", "timeout": 1}), &context)
        .await
        .expect_err("non-streaming backend must be rejected");
    assert!(error.to_string().contains("combined streaming output"));
    assert!(!backend.0.load(std::sync::atomic::Ordering::SeqCst));
}

#[test]
fn readonly_argv_is_shell_free_and_disables_git_helpers() {
    let (program, args) = hardened_readonly_argv("git show HEAD").expect("argv");
    assert_eq!(program, "git");
    assert_eq!(
        &args[..4],
        [
            "show",
            "--no-ext-diff",
            "--no-textconv",
            "--no-show-signature"
        ]
    );
    assert_eq!(args.last().map(String::as_str), Some("HEAD"));

    let (program, args) = hardened_readonly_argv("rg $PATTERN .").expect("literal argv");
    assert_eq!(program, "rg");
    assert_eq!(args, ["$PATTERN", "."]);
}

#[cfg(any(unix, windows))]
#[test]
fn readonly_program_resolution_ignores_workspace_shadow_executables() {
    let workspace = tempdir().expect("workspace");
    let trusted = tempdir().expect("trusted bin");
    let path = std::env::join_paths([workspace.path(), trusted.path()]).expect("test PATH");

    for program in ["git", "gh", "rg"] {
        let file = if cfg!(windows) {
            format!("{program}.exe")
        } else {
            program.to_string()
        };
        for directory in [workspace.path(), trusted.path()] {
            let executable = directory.join(&file);
            std::fs::write(&executable, b"fixture").expect("fixture executable");
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt as _;
                let mut permissions = executable.metadata().unwrap().permissions();
                permissions.set_mode(0o755);
                std::fs::set_permissions(&executable, permissions).unwrap();
            }
        }
        let resolved =
            resolve_readonly_program_from_path(program, workspace.path(), &path).expect("resolved");
        assert_eq!(resolved, trusted.path().join(file).canonicalize().unwrap());
        assert!(resolved.is_absolute() && !resolved.starts_with(workspace.path()));
    }
}

#[test]
fn readonly_child_env_removes_git_and_github_redirects() {
    let mut command = std::process::Command::new("unused");
    let redirects = [
        "GIT_DIR",
        "GIT_COMMON_DIR",
        "GIT_EXEC_PATH",
        "GIT_OBJECT_DIRECTORY",
        "GIT_SSH_COMMAND",
        "GH_CONFIG_DIR",
        "GH_OTHER_PATH",
    ];
    for key in redirects {
        command.env(key, "outside");
    }
    command.env(READONLY_ENV_MARKER, "1");
    let env = HashMap::from([(READONLY_ENV_MARKER.to_string(), "1".to_string())]);
    remove_readonly_redirect_env(&mut command, &env);
    for key in redirects {
        assert!(
            command
                .get_envs()
                .any(|(name, value)| name == std::ffi::OsStr::new(key) && value.is_none()),
            "{key} must be removed from the child environment"
        );
    }
    assert!(
        command
            .get_envs()
            .any(|(name, value)| name == READONLY_ENV_MARKER && value.is_none())
    );
}

#[test]
fn readonly_operands_are_workspace_bounded_and_symlink_aware() {
    let workspace = tempdir().expect("workspace");
    let outside = tempdir().expect("outside");
    std::fs::write(workspace.path().join("inside.txt"), "inside").expect("inside file");
    std::fs::write(outside.path().join("secret.txt"), "secret").expect("outside file");

    enforce_readonly_workspace_operands("cat inside.txt", workspace.path(), workspace.path())
        .expect("in-workspace operand");
    for command in [
        "cat ../secret.txt",
        "cat ~/.ssh/id_rsa",
        "cat /rooted-current-drive.txt",
        "cat C:secret",
        r"cat C:\secret",
        r"cat \\server\share\secret",
    ] {
        let error =
            enforce_readonly_workspace_operands(command, workspace.path(), workspace.path())
                .expect_err("out-of-workspace operand must fail")
                .to_string();
        assert!(error.contains("inside the workspace"), "{command}: {error}");
    }

    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(
            outside.path().join("secret.txt"),
            workspace.path().join("secret-link"),
        )
        .expect("outside symlink");
        let error = enforce_readonly_workspace_operands(
            "cat secret-link",
            workspace.path(),
            workspace.path(),
        )
        .expect_err("symlink escape must fail")
        .to_string();
        assert!(error.contains("resolves outside"), "{error}");

        let subdir = workspace.path().join("subdir");
        std::fs::create_dir(&subdir).expect("subdir");
        std::os::unix::fs::symlink(
            outside.path().join("secret.txt"),
            subdir.join("secret-link"),
        )
        .expect("cwd-relative outside symlink");
        enforce_readonly_workspace_operands("cat secret-link", workspace.path(), &subdir)
            .expect_err("operands must resolve relative to the effective cwd");
    }
}

#[test]
fn readonly_github_shell_calls_obey_the_host_network_policy_before_spawn() {
    let tmp = tempdir().expect("tempdir");
    let context = |default| {
        ToolContext::new(tmp.path()).with_network_policy(
            crate::network_policy::NetworkPolicyDecider::new(
                crate::network_policy::NetworkPolicy {
                    default,
                    ..crate::network_policy::NetworkPolicy::default()
                },
                None,
            ),
        )
    };

    let allow = context(crate::network_policy::DecisionToml::Allow);
    enforce_readonly_github_network_policy("gh issue view 5287", &allow)
        .expect("allowed github.com policy");

    let deny = context(crate::network_policy::DecisionToml::Deny);
    let denied = enforce_readonly_github_network_policy("gh issue list", &deny)
        .expect_err("deny must stop before spawning gh")
        .to_string();
    assert!(denied.contains("blocked by the active network policy"));
    enforce_readonly_github_network_policy("git status", &deny)
        .expect("local reads do not consult the network policy");

    let prompt = context(crate::network_policy::DecisionToml::Prompt);
    let prompted = enforce_readonly_github_network_policy("gh issue view 5287", &prompt)
        .expect_err("headless Scout cannot prompt interactively")
        .to_string();
    assert!(prompted.contains("requires network approval"));
}

#[test]
fn exec_shell_interact_requires_approval() {
    let tool = BashTool::alias("exec_shell_interact", "interact");
    assert_eq!(tool.approval_requirement(), ApprovalRequirement::Required);
    assert!(
        tool.capabilities()
            .contains(&ToolCapability::RequiresApproval)
    );
}

#[tokio::test]
async fn read_only_shell_policy_blocks_non_readonly_commands() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path())
        .with_shell_policy(crate::worker_profile::ShellPolicy::ReadOnly);
    let tool = BashTool::new("Bash");

    let result = tool
        .execute(json!({"command": "cargo build"}), &ctx)
        .await
        .expect("execute");
    assert!(!result.success);
    assert!(result.content.contains("read-only shell policy"));

    let result = tool
        .execute(
            json!({"command": "git status -s", "background": true}),
            &ctx,
        )
        .await
        .expect("execute");
    assert!(!result.success);
    assert!(result.content.contains("read-only shell policy"));

    for command in [
        "git --config-env=core.fsmonitor=SHELL status",
        "git -cdiff.foo.textconv=./repo-script diff HEAD",
        "rg -f/etc/passwd needle .",
    ] {
        let result = tool
            .execute(json!({"command": command}), &ctx)
            .await
            .expect("classifier refusal");
        assert!(!result.success, "{command}: {}", result.content);
        assert!(
            result.content.contains("read-only shell policy"),
            "{command}"
        );
    }
}

#[cfg(unix)]
#[tokio::test]
async fn read_only_shell_resolves_operands_from_the_effective_cwd() {
    let workspace = tempdir().expect("workspace");
    let outside = tempdir().expect("outside");
    let subdir = workspace.path().join("subdir");
    std::fs::create_dir(&subdir).expect("subdir");
    std::fs::write(outside.path().join("secret"), "secret").expect("outside secret");
    std::os::unix::fs::symlink(outside.path().join("secret"), subdir.join("secret-link"))
        .expect("symlink");
    let ctx = ToolContext::new(workspace.path())
        .with_shell_policy(crate::worker_profile::ShellPolicy::ReadOnly);
    let error = BashTool::new("Bash")
        .execute(
            json!({"action": "run", "command": "cat secret-link", "cwd": "subdir"}),
            &ctx,
        )
        .await
        .expect_err("cwd-relative symlink escape must fail before spawn")
        .to_string();
    assert!(error.contains("resolves outside"), "{error}");
}

#[cfg(unix)]
#[tokio::test]
async fn read_only_shell_skips_shell_env_hooks() {
    let tmp = tempdir().expect("tempdir");
    let marker = tmp.path().join("hook-ran");
    let hook = crate::hooks::Hook::new(
        crate::hooks::HookEvent::ShellEnv,
        &format!("printf hit > '{}'", marker.display()),
    );
    let executor = crate::hooks::HookExecutor::new(
        crate::hooks::HooksConfig {
            enabled: true,
            hooks: vec![hook],
            ..crate::hooks::HooksConfig::default()
        },
        tmp.path().to_path_buf(),
    );
    let mut context = ToolContext::new(tmp.path())
        .with_shell_policy(crate::worker_profile::ShellPolicy::ReadOnly);
    context.runtime.hook_executor = Some(std::sync::Arc::new(executor));

    let result = BashTool::read_only("Bash")
        .execute(json!({"command": "pwd"}), &context)
        .await
        .expect("read-only inspection");
    assert!(result.success, "{}", result.content);
    assert!(!marker.exists(), "shell_env hook must not run for ReadOnly");
}

#[tokio::test]
async fn read_only_shell_policy_allows_readonly_inspection() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path())
        .with_shell_policy(crate::worker_profile::ShellPolicy::ReadOnly);

    let result = BashTool::new("Bash")
        .execute(json!({"command": "pwd"}), &ctx)
        .await
        .expect("execute");

    assert!(
        result.success,
        "unexpected shell failure: {}",
        result.content
    );
    assert_eq!(
        result
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.get("status"))
            .and_then(Value::as_str),
        Some("Completed")
    );
}

#[tokio::test]
async fn exec_shell_multiline_block_explains_allow_shell_boundary() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());

    let result = BashTool::new("Bash")
        .execute(
            json!({"command": "python3 -c \"print(1)\nprint(2)\""}),
            &ctx,
        )
        .await
        .expect("execute");

    assert!(!result.success);
    assert!(result.content.contains("Command contains multiple lines"));
    assert!(
        result
            .content
            .contains("allow_shell=true exposes shell tools"),
        "{}",
        result.content
    );
    assert!(
        result
            .content
            .contains("Write multiline scripts to a file first"),
        "{}",
        result.content
    );
    assert!(
        result.content.contains("task_shell_start"),
        "{}",
        result.content
    );
}

#[test]
fn exec_shell_wait_schema_defaults_to_blocking() {
    let schema = BashTool::alias("exec_shell_wait", "wait").input_schema();
    assert!(
        schema["properties"]["wait"]["description"]
            .as_str()
            .is_some_and(|description| description.contains("default: true"))
    );
    assert!(
        BashTool::alias("exec_shell_wait", "wait")
            .description()
            .contains("wait")
    );
}

#[tokio::test]
async fn exec_shell_wait_without_wait_arg_blocks_until_completion() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let start_result = BashTool::new("Bash")
        .execute(
            json!({"command": sleep_command(1), "background": true}),
            &ctx,
        )
        .await
        .expect("start background");
    let task_id = start_result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("task_id"))
        .and_then(Value::as_str)
        .expect("task id")
        .to_string();

    let wait_result = BashTool::new("Bash")
        .execute(
            json!({"action": "wait", "task_id": task_id, "timeout_ms": 5_000}),
            &ctx,
        )
        .await
        .expect("wait for completion");

    assert_eq!(
        wait_result
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.get("status"))
            .and_then(Value::as_str),
        Some("Completed")
    );
}

#[tokio::test]
async fn exec_shell_wait_false_returns_nonblocking_snapshot() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let start_result = BashTool::new("Bash")
        .execute(
            json!({"command": sleep_command(2), "background": true}),
            &ctx,
        )
        .await
        .expect("start background");
    let task_id = start_result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("task_id"))
        .and_then(Value::as_str)
        .expect("task id")
        .to_string();

    let started = Instant::now();
    let wait_result = BashTool::new("Bash")
        .execute(
            json!({"action": "wait", "task_id": task_id, "timeout_ms": 5_000, "wait": false}),
            &ctx,
        )
        .await
        .expect("poll snapshot");

    assert!(
        started.elapsed() < Duration::from_millis(1_000),
        "wait=false should return a snapshot without blocking"
    );
    assert_eq!(
        wait_result
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.get("status"))
            .and_then(Value::as_str),
        Some("Running")
    );
}

#[tokio::test]
async fn exec_shell_wait_without_wait_arg_returns_running_at_timeout() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let start_result = BashTool::new("Bash")
        .execute(
            json!({"command": sleep_command(5), "background": true}),
            &ctx,
        )
        .await
        .expect("start background");
    let task_id = start_result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("task_id"))
        .and_then(Value::as_str)
        .expect("task id")
        .to_string();

    let started = Instant::now();
    let result = BashTool::new("Bash")
        .execute(
            json!({"action": "wait", "task_id": task_id, "timeout_ms": 1_000}),
            &ctx,
        )
        .await
        .expect("bounded wait");
    assert!(started.elapsed() >= Duration::from_millis(900));
    assert!(started.elapsed() < Duration::from_secs(3));
    assert_eq!(
        result
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.get("status"))
            .and_then(Value::as_str),
        Some("Running")
    );

    BashTool::new("Bash")
        .execute(json!({"action": "cancel", "task_id": task_id}), &ctx)
        .await
        .expect("cancel background");
}

#[tokio::test]
async fn background_start_advertises_task_status_completion() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let result = BashTool::new("Bash")
        .execute(
            json!({"command": sleep_command(1), "background": true}),
            &ctx,
        )
        .await
        .expect("start background");
    assert!(result.content.contains("completion is delivered"));
    assert!(result.content.contains("session exits") && result.content.contains("persist=true"));
    let metadata = result.metadata.as_ref().expect("metadata");
    assert_eq!(
        metadata
            .get("auto_resume_on_completion")
            .and_then(Value::as_bool),
        Some(true)
    );
    assert_eq!(
        metadata.get("completion_surface").and_then(Value::as_str),
        Some("runtime_event_and_task_status")
    );
    assert_eq!(
        metadata.get("background_policy").and_then(Value::as_str),
        Some("nonblocking")
    );
}

#[tokio::test]
async fn background_shell_job_carries_subagent_owner() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path()).with_owner_agent("agent_owner", "verifier");
    let result = BashTool::new("Bash")
        .execute(
            json!({"command": sleep_command(2), "background": true}),
            &ctx,
        )
        .await
        .expect("start owned background shell");

    let metadata = result.metadata.as_ref().expect("metadata");
    assert_eq!(
        metadata.get("owner_agent_id").and_then(Value::as_str),
        Some("agent_owner")
    );
    assert_eq!(
        metadata.get("owner_agent_name").and_then(Value::as_str),
        Some("verifier")
    );
    assert!(
        result
            .content
            .contains("not injected into the parent model"),
        "owned background work must describe its real completion route: {}",
        result.content
    );
    assert!(result.content.contains("Bash action=\"wait\""));
    assert_eq!(
        metadata
            .get("auto_resume_on_completion")
            .and_then(Value::as_bool),
        Some(false)
    );
    assert_eq!(
        metadata.get("completion_surface").and_then(Value::as_str),
        Some("task_status_and_explicit_wait")
    );
    let task_id = metadata
        .get("task_id")
        .and_then(Value::as_str)
        .expect("task id")
        .to_string();

    {
        let mut manager = ctx.shell_manager.lock().expect("shell manager");
        let snapshot = manager
            .list_jobs()
            .into_iter()
            .find(|job| job.id == task_id)
            .expect("owned shell job snapshot");
        assert_eq!(snapshot.owner_agent_id.as_deref(), Some("agent_owner"));
        assert_eq!(snapshot.owner_agent_name.as_deref(), Some("verifier"));
        let owners = manager.running_owner_agent_ids();
        assert_eq!(owners, vec!["agent_owner".to_string()]);
    }

    BashTool::alias("exec_shell_cancel", "cancel")
        .execute(json!({"task_id": task_id}), &ctx)
        .await
        .expect("cancel owned background shell");
}

#[tokio::test]
async fn drain_finished_jobs_reports_once() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let result = BashTool::new("Bash")
        .execute(
            json!({"command": echo_command("drain-finished-once"), "background": true}),
            &ctx,
        )
        .await
        .expect("start background");
    let task_id = result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("task_id"))
        .and_then(Value::as_str)
        .expect("task id")
        .to_string();

    let mut manager = ctx.shell_manager.lock().expect("shell manager");
    assert!(manager.may_have_undelivered_completion());
    assert!(
        manager.may_have_undelivered_completion(),
        "read-only detection must not consume the pending completion"
    );
    let completed = wait_for_completed_shell(&mut manager, &task_id);
    assert_ne!(completed.status, ShellStatus::Running);
    assert!(manager.may_have_undelivered_completion());

    let first = manager
        .drain_finished_jobs_with_evidence()
        .into_iter()
        .map(|completion| completion.event)
        .collect::<Vec<_>>();
    assert_eq!(first.len(), 1);
    assert_eq!(first[0].task_id, task_id);
    assert_eq!(first[0].status, ShellStatus::Completed);
    assert!(first[0].stdout_tail.contains("drain-finished-once"));

    let second = manager.drain_finished_jobs_with_evidence();
    assert!(second.is_empty(), "completion should be reported only once");
    assert!(!manager.may_have_undelivered_completion());
}

#[test]
fn completion_evidence_preserves_arbitrary_stream_bytes() {
    use base64::Engine as _;

    let stdout = vec![b'o', 0, 0xff, b'k'];
    let stderr = vec![0xfe, b'e', b'r', b'r'];
    let evidence = ShellCompletionEvidence {
        event: ShellCompletionEvent {
            task_id: "shell_binary".to_string(),
            command: "binary-output".to_string(),
            status: ShellStatus::Completed,
            exit_code: Some(0),
            duration_ms: 17,
            stdout_tail: String::new(),
            stderr_tail: String::new(),
            stdout_len: stdout.len(),
            stderr_len: stderr.len(),
            evidence_ref: None,
            linked_task_id: None,
            owner_agent_id: None,
            owner_agent_name: None,
        },
        stdout: stdout.clone(),
        stderr: stderr.clone(),
    };

    let payload: serde_json::Value =
        serde_json::from_slice(&evidence.artifact_bytes()).expect("evidence JSON");
    assert_eq!(payload["stdout"]["encoding"], "base64");
    assert_eq!(payload["stderr"]["encoding"], "base64");
    let decoded_stdout = base64::engine::general_purpose::STANDARD
        .decode(payload["stdout"]["content"].as_str().expect("stdout data"))
        .expect("decode stdout");
    let decoded_stderr = base64::engine::general_purpose::STANDARD
        .decode(payload["stderr"]["content"].as_str().expect("stderr data"))
        .expect("decode stderr");
    assert_eq!(decoded_stdout, stdout);
    assert_eq!(decoded_stderr, stderr);
}

#[test]
#[cfg(unix)]
fn shell_execution_scrubs_parent_env_and_keeps_explicit_env() {
    let _guard = env_lock().lock().expect("env lock");
    let previous = std::env::var_os("DEEPSEEK_CHILD_ENV_SHELL_SECRET");
    unsafe {
        std::env::set_var("DEEPSEEK_CHILD_ENV_SHELL_SECRET", "parent-secret");
    }

    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());
    let mut extra = std::collections::HashMap::new();
    extra.insert(
        "DEEPSEEK_CHILD_ENV_EXPLICIT".to_string(),
        "explicit-value".to_string(),
    );

    let result = manager
        .execute_with_options_env(
            "sh -c 'printf \"%s\\n%s\\n\" \"${DEEPSEEK_CHILD_ENV_SHELL_SECRET-unset}\" \"${DEEPSEEK_CHILD_ENV_EXPLICIT-unset}\"'",
            None,
            5000,
            false,
            None,
            false,
            None,
            extra,
        )
        .expect("execute");

    match previous {
        Some(value) => unsafe {
            std::env::set_var("DEEPSEEK_CHILD_ENV_SHELL_SECRET", value);
        },
        None => unsafe {
            std::env::remove_var("DEEPSEEK_CHILD_ENV_SHELL_SECRET");
        },
    }

    assert_eq!(result.status, ShellStatus::Completed);
    assert_eq!(result.stdout, "unset\nexplicit-value\n");
}

#[test]
#[cfg(windows)]
fn shell_execution_preserves_custom_windows_sdk_root_env() {
    let _guard = env_lock().lock().expect("env lock");
    let previous_sdk = std::env::var_os("BIMRV_SDK_ROOT");
    let previous_secret = std::env::var_os("MY_SECRET_ROOT");
    unsafe {
        std::env::set_var("BIMRV_SDK_ROOT", r"F:\Lib\BimRv27.5");
        std::env::set_var("MY_SECRET_ROOT", r"F:\Secrets");
    }

    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());
    let command = if crate::shell_dispatcher::global_dispatcher()
        .kind()
        .is_powershell()
    {
        r#"[Console]::WriteLine($env:BIMRV_SDK_ROOT); if ($null -eq $env:MY_SECRET_ROOT) { [Console]::WriteLine("secret-unset") } else { [Console]::WriteLine("secret-set") }"#
            .to_string()
    } else {
        r#"echo %BIMRV_SDK_ROOT% & if defined MY_SECRET_ROOT (echo secret-set) else (echo secret-unset)"#
            .to_string()
    };

    let result = execute_shell(&mut manager, &command, None, 5000, false).expect("execute");

    unsafe {
        match previous_sdk {
            Some(value) => std::env::set_var("BIMRV_SDK_ROOT", value),
            None => std::env::remove_var("BIMRV_SDK_ROOT"),
        }
        match previous_secret {
            Some(value) => std::env::set_var("MY_SECRET_ROOT", value),
            None => std::env::remove_var("MY_SECRET_ROOT"),
        }
    }

    assert_eq!(result.status, ShellStatus::Completed);
    assert!(
        result.stdout.contains(r"F:\Lib\BimRv27.5"),
        "custom SDK root should reach exec_shell stdout: {:?}",
        result
    );
    assert!(
        result.stdout.contains("secret-unset"),
        "secret-like env should stay scrubbed: {:?}",
        result
    );
}

#[test]
fn test_sync_execution() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let result =
        execute_shell(&mut manager, &echo_command("hello"), None, 5000, false).expect("execute");

    assert_eq!(result.status, ShellStatus::Completed);
    assert!(result.stdout.contains("hello"));
    assert!(result.task_id.is_none());
}

#[test]
fn test_background_execution() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let result = execute_shell(
        &mut manager,
        &sleep_then_echo_command(1, "done"),
        None,
        5000,
        true,
    )
    .expect("execute");

    assert_eq!(result.status, ShellStatus::Running);
    assert!(result.task_id.is_some());

    let task_id = result
        .task_id
        .expect("background execution should return task_id");

    let final_result = wait_for_completed_shell(&mut manager, &task_id);

    assert_eq!(final_result.status, ShellStatus::Completed);
    assert!(final_result.stdout.contains("done"));
}

#[test]
fn test_timeout() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let result =
        execute_shell(&mut manager, &sleep_command(10), None, 1000, false).expect("execute");

    assert_eq!(result.status, ShellStatus::TimedOut);
}

#[test]
fn test_kill() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let result =
        execute_shell(&mut manager, &sleep_command(60), None, 5000, true).expect("execute");

    let task_id = result
        .task_id
        .expect("background execution should return task_id");

    // Kill it
    let killed = manager.kill(&task_id).expect("kill");
    assert_eq!(killed.status, ShellStatus::Killed);
}

#[test]
fn test_write_stdin_streams_output() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let result = manager
        .execute_with_options_env(
            &echo_stdin_command(),
            None,
            5000,
            true,
            None,
            false,
            None,
            HashMap::new(),
        )
        .expect("execute");

    let task_id = result
        .task_id
        .expect("background execution should return task_id");

    manager
        .write_stdin(&task_id, "hello\n", true)
        .expect("write stdin");

    let delta = manager
        .get_output_delta(&task_id, true, 5000)
        .expect("get_output_delta");

    assert!(delta.result.stdout.contains("hello"));

    let delta2 = manager
        .get_output_delta(&task_id, false, 0)
        .expect("get_output_delta");
    assert!(delta2.result.stdout.is_empty());
}

#[test]
#[cfg(all(unix, not(target_env = "ohos")))]
fn background_tty_command_has_controlling_terminal() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let result = manager
        .execute_with_options_env(
            "sh -c 'exec 3<>/dev/tty && printf tty-ok && exec 3>&-'",
            None,
            5000,
            true,
            None,
            true,
            Some(ExecutionSandboxPolicy::DangerFullAccess),
            HashMap::new(),
        )
        .expect("execute tty command");

    let task_id = result
        .task_id
        .expect("background tty execution should return task_id");

    let done = manager
        .get_output(&task_id, true, 10_000)
        .expect("get tty command output");

    assert_eq!(done.status, ShellStatus::Completed);
    assert_eq!(done.exit_code, Some(0));
    assert!(
        done.stdout.contains("tty-ok"),
        "tty output should confirm /dev/tty opened; got {done:?}"
    );
}

#[test]
fn test_job_list_poll_cancel_and_stale_snapshot() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let started = execute_shell(
        &mut manager,
        &sleep_then_echo_command(1, "done"),
        None,
        5000,
        true,
    )
    .expect("execute");
    let task_id = started.task_id.expect("task id");
    manager
        .tag_linked_task(&task_id, Some("task_123".to_string()))
        .expect("tag linked task");

    let running = manager.list_jobs();
    let job = running
        .iter()
        .find(|job| job.id == task_id)
        .expect("running job");
    assert_eq!(job.status, ShellStatus::Running);
    assert_eq!(job.linked_task_id.as_deref(), Some("task_123"));
    assert!(job.command.contains("done"));
    assert_eq!(job.cwd, tmp.path());

    let completed = manager
        .poll_delta(&task_id, true, 5000)
        .expect("poll delta");
    assert_eq!(completed.result.status, ShellStatus::Completed);
    assert!(completed.result.stdout.contains("done"));

    let detail = manager.inspect_job(&task_id).expect("inspect");
    assert!(detail.stdout.contains("done"));
    assert_eq!(detail.snapshot.status, ShellStatus::Completed);

    manager.remember_stale_job(
        "shell_stale",
        "cargo test",
        tmp.path().to_path_buf(),
        Some("task_old".to_string()),
    );
    let stale = manager
        .list_jobs()
        .into_iter()
        .find(|job| job.id == "shell_stale")
        .expect("stale job");
    assert!(stale.stale);
    assert_eq!(stale.linked_task_id.as_deref(), Some("task_old"));
}

#[test]
fn running_job_snapshot_marks_no_output_stale_after_threshold() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let started =
        execute_shell(&mut manager, &sleep_command(5), None, 5000, true).expect("execute");
    let task_id = started.task_id.expect("task id");

    {
        let shell = manager.processes.get_mut(&task_id).expect("live shell");
        shell.last_output_at = Instant::now() - STALE_NO_OUTPUT_AFTER - Duration::from_millis(1);
    }

    let job = manager
        .list_jobs()
        .into_iter()
        .find(|job| job.id == task_id)
        .expect("running job");

    assert_eq!(job.status, ShellStatus::Running);
    assert!(job.stale, "silent running job should be marked stale");
    assert!(
        job.elapsed_since_output_ms
            .is_some_and(|elapsed| elapsed >= STALE_NO_OUTPUT_AFTER.as_millis() as u64),
        "elapsed no-output time should be exposed: {job:?}"
    );
}

#[test]
fn running_job_snapshot_keeps_recent_no_output_fresh() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let started =
        execute_shell(&mut manager, &sleep_command(5), None, 5000, true).expect("execute");
    let task_id = started.task_id.expect("task id");

    let job = manager
        .list_jobs()
        .into_iter()
        .find(|job| job.id == task_id)
        .expect("running job");

    assert_eq!(job.status, ShellStatus::Running);
    assert!(!job.stale, "fresh running job should not start stale");
    assert!(job.elapsed_since_output_ms.is_some());
}

#[test]
fn test_job_cancel_updates_completion_state() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let started =
        execute_shell(&mut manager, &sleep_command(60), None, 5000, true).expect("execute");
    let task_id = started.task_id.expect("task id");

    let killed = manager.kill(&task_id).expect("kill");
    assert_eq!(killed.status, ShellStatus::Killed);
    let job = manager.inspect_job(&task_id).expect("inspect");
    assert_eq!(job.snapshot.status, ShellStatus::Killed);
    assert!(!job.snapshot.stdin_available);
}

#[test]
fn test_output_truncation() {
    let long_output = "x".repeat(50_000);
    let (truncated, _meta) = truncate_with_meta(&long_output);

    assert!(truncated.len() < long_output.len());
    assert!(truncated.contains("truncated"));
}

#[test]
fn test_truncate_with_meta_reports_omission_counts() {
    let long_output = format!("line1\nline2\n{}", "x".repeat(60_000));
    let (truncated, meta) = truncate_with_meta(&long_output);

    assert!(meta.truncated);
    assert!(meta.original_len >= long_output.len());
    assert!(meta.omitted > 0);
    assert!(truncated.contains("bytes omitted"));
}

#[test]
fn network_restricted_hint_detects_silent_curl_failure() {
    let tmp = tempdir().expect("tempdir");
    let ctx = network_restricted_context(tmp.path());
    let result = failed_network_shell_result("000", "");

    let hint = shell_network_restricted_hint(
        &ctx,
        "curl -s -o /dev/null -w '%{http_code}' https://api.github.com",
        &result,
    )
    .expect("network-restricted hint");

    assert!(hint.contains("Plan mode"));
}

#[test]
fn sandbox_denied_hint_names_the_effective_posture() {
    // DGF-02: an approved write blocked by a read-only sandbox must come
    // back naming the sandbox as the blocker, never as a bare failure.
    let tmp = tempdir().expect("tempdir");
    let ctx =
        ToolContext::new(tmp.path()).with_elevated_sandbox_policy(ExecutionSandboxPolicy::ReadOnly);
    let mut result =
        failed_network_shell_result("", "sh: cannot create out.txt: Operation not permitted");
    result.sandbox_denied = true;

    let hint = shell_sandbox_denied_hint(&ctx, &result).expect("sandbox-denied hint");

    assert!(hint.contains("read-only"), "{hint}");
    assert!(hint.contains("Ask-only escalation"), "{hint}");
    assert!(
        hint.contains("retry this exact command once with sandbox_permissions"),
        "{hint}"
    );
    assert!(hint.contains("justification"), "{hint}");
}

#[test]
fn contract_bash_denial_surfaces_the_escalation_shape() {
    let tmp = tempdir().expect("tempdir");
    let ctx =
        ToolContext::new(tmp.path()).with_elevated_sandbox_policy(ExecutionSandboxPolicy::ReadOnly);
    let mut result = failed_network_shell_result("", "Operation not permitted");
    result.sandbox_denied = true;

    let error = finish_contract_bash_result(result, None, &ctx)
        .expect_err("sandbox denial is a failed call");

    assert!(
        error
            .to_string()
            .contains("retry this exact command once with sandbox_permissions"),
        "{error}"
    );
}

#[test]
fn sandbox_denied_hint_absent_without_denial_or_policy() {
    let tmp = tempdir().expect("tempdir");
    let ctx =
        ToolContext::new(tmp.path()).with_elevated_sandbox_policy(ExecutionSandboxPolicy::ReadOnly);
    let undenied = failed_network_shell_result("", "No such file or directory");
    assert!(shell_sandbox_denied_hint(&ctx, &undenied).is_none());

    let mut denied = failed_network_shell_result("", "");
    denied.sandbox_denied = true;
    let no_policy_ctx = ToolContext::new(tmp.path());
    assert!(shell_sandbox_denied_hint(&no_policy_ctx, &denied).is_none());
}

#[test]
fn shell_delta_result_surfaces_sandbox_denied_hint() {
    let tmp = tempdir().expect("tempdir");
    let ctx =
        ToolContext::new(tmp.path()).with_elevated_sandbox_policy(ExecutionSandboxPolicy::ReadOnly);
    let mut result = failed_network_shell_result("", "Operation not permitted");
    result.sandbox_denied = true;

    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "touch out.txt".to_string(),
            result,
            stdout_total_len: 0,
            stderr_total_len: 0,
        },
        &ctx,
    );

    assert!(
        tool_result
            .content
            .contains("The execution sandbox blocked this command"),
        "{}",
        tool_result.content
    );
    let metadata = tool_result.metadata.expect("metadata");
    assert!(metadata.get("sandbox_denied_hint").is_some());
}

#[test]
fn network_restricted_hint_ignores_local_failures() {
    let tmp = tempdir().expect("tempdir");
    let ctx = network_restricted_context(tmp.path());
    let result = failed_network_shell_result("", "No such file or directory");

    assert!(shell_network_restricted_hint(&ctx, "cat missing.txt", &result).is_none());
}

#[test]
fn shell_delta_result_surfaces_network_restricted_hint() {
    let tmp = tempdir().expect("tempdir");
    let ctx = network_restricted_context(tmp.path());
    let result = failed_network_shell_result("000", "");

    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "gh issue list".to_string(),
            result,
            stdout_total_len: 3,
            stderr_total_len: 0,
        },
        &ctx,
    );

    assert!(!tool_result.success);
    assert!(tool_result.content.starts_with("Shell command blocked"));
    let metadata = tool_result.metadata.expect("metadata");
    assert_eq!(
        metadata
            .get("sandbox_network_restricted")
            .and_then(Value::as_bool),
        Some(true)
    );
}

#[test]
fn shell_delta_result_exposes_lossless_high_exit_code_and_hex() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let mut result = failed_network_shell_result("", "");
    result.exit_code = Some(0xC000_0005);

    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "echo probe".to_string(),
            result,
            stdout_total_len: 0,
            stderr_total_len: 0,
        },
        &ctx,
    );

    assert!(
        tool_result
            .content
            .contains("exit code 3221225477 (0xC0000005)"),
        "{}",
        tool_result.content
    );
    let metadata = tool_result.metadata.expect("metadata");
    assert_eq!(metadata["exit_code"], json!(3221225477_i64));
    assert_eq!(metadata["exit_code_hex"], json!("0xC0000005"));
}

#[test]
fn shell_delta_result_surfaces_elapsed_time_in_content() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let mut result = failed_network_shell_result("", "");
    result.status = ShellStatus::Running;
    result.duration_ms = 42_500;
    result.task_id = Some("shell-7".to_string());

    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "cargo test --workspace".to_string(),
            result,
            stdout_total_len: 0,
            stderr_total_len: 0,
        },
        &ctx,
    );

    assert!(
        tool_result
            .content
            .starts_with("Task shell-7 still running after 42.5 s."),
        "{}",
        tool_result.content
    );
}

#[test]
fn shell_delta_timing_line_omits_task_id_when_unknown() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    // failed_network_shell_result: ShellStatus::Failed, duration_ms: 25, task_id: None.
    let result = failed_network_shell_result("", "");

    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "echo probe".to_string(),
            result,
            stdout_total_len: 0,
            stderr_total_len: 0,
        },
        &ctx,
    );

    assert!(
        tool_result.content.starts_with("Task failed after 25 ms."),
        "{}",
        tool_result.content
    );
}

#[test]
fn shell_delta_timing_line_phrases_cover_terminal_statuses() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    for (status, phrase) in [
        (ShellStatus::Completed, "completed"),
        (ShellStatus::Killed, "killed"),
        (ShellStatus::TimedOut, "timed out"),
    ] {
        let mut result = failed_network_shell_result("", "");
        result.status = status;
        result.duration_ms = 5_000;
        let tool_result = build_shell_delta_tool_result(
            ShellDeltaResult {
                command: "echo probe".to_string(),
                result,
                stdout_total_len: 0,
                stderr_total_len: 0,
            },
            &ctx,
        );
        assert!(
            tool_result
                .content
                .starts_with(&format!("Task {phrase} after 5 s.")),
            "{}",
            tool_result.content
        );
    }
}

#[test]
fn shell_delta_timing_line_handles_zero_duration() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let mut result = failed_network_shell_result("", "");
    result.status = ShellStatus::Completed;
    result.duration_ms = 0;
    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "echo probe".to_string(),
            result,
            stdout_total_len: 0,
            stderr_total_len: 0,
        },
        &ctx,
    );
    assert!(
        tool_result
            .content
            .starts_with("Task completed after 0 ms."),
        "{}",
        tool_result.content
    );
}

#[test]
fn shell_delta_timing_line_sits_below_network_hint() {
    let tmp = tempdir().expect("tempdir");
    let ctx = network_restricted_context(tmp.path());
    let result = failed_network_shell_result("000", "");
    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "gh issue list".to_string(),
            result,
            stdout_total_len: 3,
            stderr_total_len: 0,
        },
        &ctx,
    );
    let content = tool_result.content;
    let hint_pos = content.find("Shell command blocked").expect("hint present");
    let timing_pos = content
        .find("failed after 25 ms")
        .expect("timing line present");
    assert!(
        hint_pos < timing_pos,
        "hint must precede timing line: {content}"
    );
}

#[test]
fn shell_delta_result_includes_cargo_failure_summary() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let result = ShellResult {
        task_id: None,
        status: ShellStatus::Failed,
        exit_code: Some(101),
        stdout: "running 1 test\ntest tests::fails ... FAILED\n\nfailures:\n\n---- tests::fails stdout ----\nthread 'tests::fails' panicked at src/lib.rs:7:9:\nboom\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; finished in 0.00s\n".to_string(),
        stderr: "error: test failed, to rerun pass `--lib`".to_string(),
        duration_ms: 12,
        stdout_len: 0,
        stderr_len: 0,
        stdout_omitted: 0,
        stderr_omitted: 0,
        stdout_truncated: false,
        stderr_truncated: false,
        sandboxed: false,
        sandbox_type: None,
        sandbox_denied: false,
    };

    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "cargo test".to_string(),
            result,
            stdout_total_len: 0,
            stderr_total_len: 0,
        },
        &ctx,
    );

    let metadata = tool_result.metadata.expect("metadata");
    assert_eq!(
        metadata["cargo_failure_summary"]["kind"],
        json!("test_failure")
    );
    assert!(
        metadata["cargo_failure_summary"]["summary"]
            .as_str()
            .unwrap()
            .contains("Failing tests: tests::fails")
    );
    assert!(
        metadata["summary"]
            .as_str()
            .unwrap()
            .contains("error: test failed")
    );
}

#[test]
fn shell_delta_result_keeps_existing_summary_for_generic_cargo_failure() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let result = ShellResult {
        task_id: None,
        status: ShellStatus::Failed,
        exit_code: Some(1),
        stdout: "build failed".to_string(),
        stderr: "command failed without structured cargo diagnostics".to_string(),
        duration_ms: 12,
        stdout_len: 0,
        stderr_len: 0,
        stdout_omitted: 0,
        stderr_omitted: 0,
        stdout_truncated: false,
        stderr_truncated: false,
        sandboxed: false,
        sandbox_type: None,
        sandbox_denied: false,
    };

    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "cargo test".to_string(),
            result,
            stdout_total_len: 0,
            stderr_total_len: 0,
        },
        &ctx,
    );

    let metadata = tool_result.metadata.expect("metadata");
    assert!(metadata.get("cargo_failure_summary").is_none());
    assert_eq!(
        metadata["summary"],
        json!("command failed without structured cargo diagnostics")
    );
}

#[test]
fn shell_delta_result_surfaces_python_build_dependency_hint() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let result = ShellResult {
        task_id: None,
        status: ShellStatus::Failed,
        exit_code: Some(1),
        stdout: String::new(),
        stderr: "running build_ext\nModuleNotFoundError: No module named 'setuptools'\n"
            .to_string(),
        duration_ms: 12,
        stdout_len: 0,
        stderr_len: 72,
        stdout_omitted: 0,
        stderr_omitted: 0,
        stdout_truncated: false,
        stderr_truncated: false,
        sandboxed: false,
        sandbox_type: None,
        sandbox_denied: false,
    };

    let tool_result = build_shell_delta_tool_result(
        ShellDeltaResult {
            command: "python setup.py build_ext --inplace".to_string(),
            result,
            stdout_total_len: 0,
            stderr_total_len: 72,
        },
        &ctx,
    );

    assert!(!tool_result.success);
    assert!(
        tool_result
            .content
            .starts_with("Python build dependency missing")
    );
    let metadata = tool_result.metadata.expect("metadata");
    assert_eq!(
        metadata["python_build_dependency_hint"]["kind"],
        json!("missing_setuptools")
    );
    assert!(
        metadata["python_build_dependency_hint"]["hint"]
            .as_str()
            .unwrap()
            .contains("setuptools")
    );
}

#[test]
fn test_summarize_output_strips_truncation_note() {
    let long_output = "x".repeat(60_000);
    let (truncated, _meta) = truncate_with_meta(&long_output);
    let summary = summarize_output(&truncated);
    assert!(!summary.contains("Output truncated at"));
}

#[tokio::test]
async fn test_exec_shell_metadata_includes_summaries() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let tool = BashTool::new("Bash");

    let result = tool
        .execute(json!({"command": echo_command("hello")}), &ctx)
        .await
        .expect("execute");
    assert!(result.success);

    let meta = result.metadata.expect("metadata");
    let summary = meta
        .get("summary")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();
    assert!(summary.contains("hello"));
    assert!(meta.get("stdout_len").is_some());
    assert!(meta.get("stdout_truncated").is_some());
}

#[cfg(not(windows))]
#[tokio::test]
async fn test_exec_shell_combined_output_uses_single_stream() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let tool = BashTool::new("Bash");
    let command = "printf 'out\\n'; printf 'err\\n' >&2";

    let result = tool
        .execute(json!({"command": command, "combined_output": true}), &ctx)
        .await
        .expect("execute");
    assert!(result.success, "{}", result.content);
    assert!(result.content.contains("out"), "{}", result.content);
    assert!(result.content.contains("err"), "{}", result.content);

    let meta = result.metadata.expect("metadata");
    assert_eq!(
        meta.get("combined_output").and_then(Value::as_bool),
        Some(true)
    );
}

#[tokio::test]
async fn test_exec_shell_foreground_timeout_guides_background_rerun() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let tool = BashTool::new("Bash");

    let result = tool
        .execute(
            json!({
                "command": sleep_command(10),
                "timeout_ms": 1000
            }),
            &ctx,
        )
        .await
        .expect("execute");

    assert!(!result.success);
    // The rerun instruction has to be spelled in the canonical action form:
    // `exec_shell` / `task_shell_start` are not both dispatchable, and the
    // model can only reach the shell through `Bash`.
    assert!(
        result
            .content
            .contains("Bash action=\"run\" background=true")
    );
    assert!(result.content.contains("Bash action=\"wait\""));
    assert!(!result.content.contains("exec_shell"));
    assert!(result.content.contains("process killed"));
    let meta = result.metadata.expect("metadata");
    assert_eq!(meta.get("status").and_then(Value::as_str), Some("TimedOut"));
    let recovery = meta
        .get("foreground_timeout_recovery")
        .expect("timeout recovery metadata");
    assert_eq!(
        recovery
            .get("rerun_as")
            .and_then(|rerun| rerun.get("background"))
            .and_then(Value::as_bool),
        Some(true)
    );
    assert_eq!(
        recovery
            .get("rerun_as")
            .and_then(|rerun| rerun.get("tool"))
            .and_then(Value::as_str),
        Some("Bash")
    );
    let hint = recovery
        .get("hint")
        .and_then(Value::as_str)
        .unwrap_or_default();
    assert!(hint.contains("Bash action=\"wait\""), "{hint}");
    assert!(!hint.contains("exec_shell"), "{hint}");
    // The structured tool list is read by the model too; it must not hand
    // over names the registry does not resolve.
    let recommended = recovery.to_string();
    assert!(!recommended.contains("exec_shell"), "{recommended}");
}

#[test]
fn background_schema_distinguishes_temporary_jobs_from_persistent_services() {
    let schema = BashTool::new("Bash").input_schema();
    let d = schema["properties"]["background"]["description"]
        .as_str()
        .expect("background description");
    assert!(d.contains("killed") && d.contains("background:true") && d.contains("persist:true"));
}

#[tokio::test]
async fn test_exec_shell_foreground_cancel_kills_process() {
    let tmp = tempdir().expect("tempdir");
    let cancel_token = tokio_util::sync::CancellationToken::new();
    let ctx = ToolContext::new(tmp.path()).with_cancel_token(cancel_token.clone());
    let command = sleep_command(30);

    let task = tokio::spawn(async move {
        BashTool::new("Bash")
            .execute(
                json!({
                    "command": command,
                    "timeout_ms": 600_000
                }),
                &ctx,
            )
            .await
            .expect("execute")
    });

    tokio::time::sleep(Duration::from_millis(150)).await;
    cancel_token.cancel();

    let result = tokio::time::timeout(Duration::from_secs(5), task)
        .await
        .expect("foreground shell should observe cancellation")
        .expect("task should not panic");

    assert!(!result.success);
    assert!(result.content.contains("Command canceled"));
    let meta = result.metadata.expect("metadata");
    assert_eq!(meta.get("status").and_then(Value::as_str), Some("Killed"));
    assert_eq!(meta.get("canceled").and_then(Value::as_bool), Some(true));
}

#[tokio::test]
async fn test_exec_shell_foreground_can_move_to_background() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let shell_manager = ctx.shell_manager.clone();
    let command = sleep_command(30);
    let task_ctx = ctx.clone();

    let task = tokio::spawn(async move {
        BashTool::new("Bash")
            .execute(
                json!({
                    "command": command,
                    "timeout_ms": 600_000
                }),
                &task_ctx,
            )
            .await
            .expect("execute")
    });

    tokio::time::sleep(Duration::from_millis(150)).await;
    shell_manager
        .lock()
        .expect("shell manager lock")
        .request_foreground_background();

    let result = tokio::time::timeout(Duration::from_secs(5), task)
        .await
        .expect("foreground shell should detach")
        .expect("task should not panic");

    assert!(result.success);
    assert!(
        result
            .content
            .contains("Foreground shell wait moved to /jobs")
    );
    // The detach message points the model at the wait action for early
    // output, and hands over the task_id it needs to make that call.
    assert!(
        result.content.contains("Bash action=\"wait\""),
        "{}",
        result.content
    );
    assert!(result.content.contains("task_id="), "{}", result.content);
    assert!(!result.content.contains("exec_shell"), "{}", result.content);

    let meta = result.metadata.expect("metadata");
    assert_eq!(meta.get("status").and_then(Value::as_str), Some("Running"));
    assert_eq!(
        meta.get("backgrounded").and_then(Value::as_bool),
        Some(true)
    );
    let task_id = meta
        .get("task_id")
        .and_then(Value::as_str)
        .expect("task id")
        .to_string();

    let mut manager = shell_manager.lock().expect("shell manager lock");
    let job = manager.inspect_job(&task_id).expect("inspect job");
    assert_eq!(job.snapshot.status, ShellStatus::Running);
    let killed = manager.kill(&task_id).expect("kill");
    assert_eq!(killed.status, ShellStatus::Killed);
}

#[tokio::test]
async fn lowercase_bash_foreground_detach_is_a_successful_running_receipt() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let shell_manager = ctx.shell_manager.clone();
    let command = sleep_command(30);
    let task_ctx = ctx.clone();

    let task = tokio::spawn(async move {
        LowercaseBashTool
            .execute(json!({"command": command}), &task_ctx)
            .await
            .expect("execute")
    });

    tokio::time::sleep(Duration::from_millis(150)).await;
    shell_manager
        .lock()
        .expect("shell manager lock")
        .request_foreground_background();

    let result = tokio::time::timeout(Duration::from_secs(5), task)
        .await
        .expect("foreground shell should detach")
        .expect("task should not panic");

    assert!(result.success, "{}", result.content);
    assert!(
        result.content.contains("moved to /jobs"),
        "{}",
        result.content
    );
    assert!(!result.content.contains("code -1"), "{}", result.content);
    let metadata = result.metadata.expect("metadata");
    assert_eq!(metadata["status"], "Running");
    assert_eq!(metadata["backgrounded"], true);
    let task_id = metadata["task_id"].as_str().expect("task id");

    let mut manager = shell_manager.lock().expect("shell manager lock");
    let job = manager.inspect_job(task_id).expect("inspect job");
    assert_eq!(job.snapshot.status, ShellStatus::Running);
    manager.kill(task_id).expect("kill test job");
}

#[tokio::test]
async fn test_exec_shell_wait_cancel_leaves_background_process_running() {
    let tmp = tempdir().expect("tempdir");
    let cancel_token = tokio_util::sync::CancellationToken::new();
    let ctx = ToolContext::new(tmp.path()).with_cancel_token(cancel_token.clone());
    let shell_manager = ctx.shell_manager.clone();
    let started = execute_shell(
        &mut shell_manager.lock().expect("shell manager lock"),
        &sleep_command(30),
        None,
        600_000,
        true,
    )
    .expect("execute");
    let task_id = started.task_id.expect("task id");
    let wait_task_id = task_id.clone();
    let task_ctx = ctx.clone();

    let task = tokio::spawn(async move {
        BashTool::new("Bash")
            .execute(
                json!({
                    "action": "wait",
                    "task_id": wait_task_id,
                    "timeout_ms": 600_000
                }),
                &task_ctx,
            )
            .await
            .expect("wait")
    });

    tokio::time::sleep(Duration::from_millis(150)).await;
    cancel_token.cancel();

    let result = tokio::time::timeout(Duration::from_secs(5), task)
        .await
        .expect("wait should observe cancellation")
        .expect("task should not panic");

    assert!(result.success);
    assert!(result.content.contains("still running"));
    let meta = result.metadata.expect("metadata");
    assert_eq!(meta.get("status").and_then(Value::as_str), Some("Running"));
    assert_eq!(
        meta.get("wait_canceled").and_then(Value::as_bool),
        Some(true)
    );

    let mut manager = shell_manager.lock().expect("shell manager lock");
    let job = manager.inspect_job(&task_id).expect("inspect job");
    assert_eq!(job.snapshot.status, ShellStatus::Running);
    let killed = manager.kill(&task_id).expect("kill");
    assert_eq!(killed.status, ShellStatus::Killed);
}

#[tokio::test]
async fn test_completed_background_shell_releases_process_handles() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let shell_manager = ctx.shell_manager.clone();
    let started = execute_shell(
        &mut shell_manager.lock().expect("shell manager lock"),
        &echo_command("done"),
        None,
        600_000,
        true,
    )
    .expect("execute");
    let task_id = started.task_id.expect("task id");

    let result = BashTool::alias("exec_shell_wait", "wait")
        .execute(
            json!({
                "task_id": task_id.clone(),
                "wait": true,
                "timeout_ms": BACKGROUND_COMPLETION_WAIT_MS
            }),
            &ctx,
        )
        .await
        .expect("wait");

    assert!(result.success);
    let mut manager = shell_manager.lock().expect("shell manager lock");
    let result = wait_for_completed_shell(&mut manager, &task_id);
    assert_eq!(result.status, ShellStatus::Completed);
    let shell = manager.processes.get_mut(&task_id).expect("tracked shell");
    shell.poll();
    assert_eq!(shell.status, ShellStatus::Completed);
    assert!(shell.stdin.is_none());
    assert!(shell.child.is_none());
    assert!(shell.stdout_thread.is_none());
    assert!(shell.stderr_thread.is_none());
}

#[cfg(unix)]
#[tokio::test]
async fn exec_shell_cancel_kills_descendant_process_group() {
    let tmp = tempdir().expect("tempdir");
    let pid_file = tmp.path().join("descendant.pid");
    let test_binary = std::env::current_exe().expect("current test binary");
    let command = format!(
        "{} --exact {} --nocapture",
        shell_words::quote(&test_binary.display().to_string()),
        shell_words::quote("tools::shell::tests::shell_descendant_helper_process"),
    );
    let ctx = ToolContext::new(tmp.path());
    let mut env = std::collections::HashMap::new();
    env.insert(SHELL_DESCENDANT_HELPER_ENV.to_string(), "1".to_string());
    env.insert(
        SHELL_DESCENDANT_PID_FILE_ENV.to_string(),
        pid_file.display().to_string(),
    );
    let started = ctx
        .shell_manager
        .lock()
        .expect("shell manager")
        .execute_with_options_env(&command, None, 60_000, true, None, false, None, env)
        .expect("start descendant tree");
    let task_id = started.task_id.expect("task id");
    let descendant = wait_for_shell_pid_file(&pid_file);

    let result = BashTool::alias("exec_shell_cancel", "cancel")
        .execute(json!({"task_id": task_id}), &ctx)
        .await
        .expect("cancel process group");
    assert!(result.success);
    assert!(
        wait_for_shell_pid_exit(descendant),
        "descendant {descendant} survived shell process-group cancellation"
    );
}

#[tokio::test]
async fn test_exec_shell_cancel_tool_kills_background_process() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let shell_manager = ctx.shell_manager.clone();
    let started = execute_shell(
        &mut shell_manager.lock().expect("shell manager lock"),
        &sleep_command(30),
        None,
        600_000,
        true,
    )
    .expect("execute");
    let task_id = started.task_id.expect("task id");

    let result = BashTool::alias("exec_shell_cancel", "cancel")
        .execute(json!({ "task_id": task_id }), &ctx)
        .await
        .expect("cancel");

    assert!(result.success);
    assert!(result.content.contains("Canceled background command"));
    let meta = result.metadata.expect("metadata");
    assert_eq!(meta.get("status").and_then(Value::as_str), Some("Killed"));

    let task_id = meta
        .get("task_id")
        .and_then(Value::as_str)
        .expect("task id");
    let mut manager = shell_manager.lock().expect("shell manager lock");
    let job = manager.inspect_job(task_id).expect("inspect job");
    assert_eq!(job.snapshot.status, ShellStatus::Killed);
}

#[tokio::test]
async fn test_exec_shell_cancel_tool_can_kill_all_running_processes() {
    let tmp = tempdir().expect("tempdir");
    let ctx = ToolContext::new(tmp.path());
    let shell_manager = ctx.shell_manager.clone();
    let first = execute_shell(
        &mut shell_manager.lock().expect("shell manager lock"),
        &sleep_command(30),
        None,
        600_000,
        true,
    )
    .expect("execute first")
    .task_id
    .expect("first task id");
    let second = execute_shell(
        &mut shell_manager.lock().expect("shell manager lock"),
        &sleep_command(30),
        None,
        600_000,
        true,
    )
    .expect("execute second")
    .task_id
    .expect("second task id");

    let result = BashTool::alias("exec_shell_cancel", "cancel")
        .execute(json!({ "all": true }), &ctx)
        .await
        .expect("cancel all");

    assert!(result.success);
    let meta = result.metadata.expect("metadata");
    assert_eq!(meta.get("status").and_then(Value::as_str), Some("Killed"));
    assert_eq!(meta.get("canceled").and_then(Value::as_u64), Some(2));

    let mut manager = shell_manager.lock().expect("shell manager lock");
    let first_job = manager.inspect_job(&first).expect("inspect first");
    let second_job = manager.inspect_job(&second).expect("inspect second");
    assert_eq!(first_job.snapshot.status, ShellStatus::Killed);
    assert_eq!(second_job.snapshot.status, ShellStatus::Killed);
}

fn make_failed_result(stderr: &str) -> ShellResult {
    ShellResult {
        task_id: None,
        status: ShellStatus::Failed,
        exit_code: Some(1),
        stdout: String::new(),
        stderr: stderr.to_string(),
        duration_ms: 0,
        stdout_len: 0,
        stderr_len: stderr.len(),
        stdout_omitted: 0,
        stderr_omitted: 0,
        stdout_truncated: false,
        sandboxed: false,
        sandbox_type: None,
        sandbox_denied: false,
        stderr_truncated: false,
    }
}

#[test]
fn test_macos_provenance_detected_by_activity_time_message() {
    let result = make_failed_result(
        "failed to update builder last activity time: open \
         /Users/user/.docker/buildx/activity/.tmp-abc: operation not permitted",
    );
    assert!(looks_like_macos_provenance_failure(&result));
}

#[test]
fn test_macos_provenance_detected_by_activity_path_and_eperm() {
    let result = make_failed_result(
        "error: open /home/user/.docker/buildx/activity/foo: operation not permitted",
    );
    assert!(looks_like_macos_provenance_failure(&result));
}

#[test]
fn test_macos_provenance_not_triggered_on_success() {
    let mut result = make_failed_result(
        "failed to update builder last activity time: open \
         /Users/user/.docker/buildx/activity/.tmp-abc: operation not permitted",
    );
    result.status = ShellStatus::Completed;
    result.exit_code = Some(0);
    assert!(!looks_like_macos_provenance_failure(&result));
}

#[test]
fn test_macos_provenance_not_triggered_on_unrelated_eperm() {
    let result = make_failed_result("open /some/other/path: operation not permitted");
    assert!(!looks_like_macos_provenance_failure(&result));
}

// Regression test for #828: shell spawns an orphaned background subprocess
// (simulating `nohup curl`) that keeps the pipe write-end open after the shell
// exits. collect_output() must not block indefinitely — it kills the whole
// process group first, allowing reader threads to get EOF and exit.
#[cfg(unix)]
#[test]
fn test_orphaned_subprocess_does_not_block_collect_output() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    // sh spawns `sleep 100 &` and exits; the sleep subprocess inherits the
    // pipe write-ends and would keep reader threads blocked without the fix.
    let result =
        execute_shell(&mut manager, "sh -c 'sleep 100 &'", None, 5000, true).expect("execute");
    let task_id = result.task_id.expect("task id");

    // Drive to completion with a tight timeout — must not hang.
    let done = manager
        .get_output(&task_id, true, 3000)
        .expect("get_output must complete, not hang");
    assert_eq!(done.status, ShellStatus::Completed);
}

#[cfg(unix)]
#[test]
fn foreground_shell_does_not_block_on_orphaned_subprocess_pipe() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let started = std::time::Instant::now();
    let result = execute_shell(&mut manager, "sh -c 'sleep 100 &'", None, 5000, false)
        .expect("foreground execute must complete, not hang");

    assert!(
        started.elapsed() < std::time::Duration::from_secs(4),
        "foreground execute blocked on descendant pipe handles"
    );
    assert_eq!(result.status, ShellStatus::Completed);
}

// Windows equivalent of the orphaned pipe-handle regression. `cmd /c start /b`
// launches a descendant process that inherits stdout/stderr and outlives the
// shell. Job-object cleanup must terminate that descendant before reader-thread
// joins, otherwise get_output() blocks until ping exits.
#[cfg(windows)]
#[test]
fn background_collection_does_not_block_on_detached_descendant_pipe() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let result = execute_shell(
        &mut manager,
        r#"cmd /c start "" /b ping 127.0.0.1 -n 4"#,
        None,
        5000,
        true,
    )
    .expect("execute");
    let task_id = result.task_id.expect("task id");

    let started = std::time::Instant::now();
    let done = manager
        .get_output(&task_id, true, 3000)
        .expect("get_output must complete, not hang");

    assert!(
        started.elapsed() < std::time::Duration::from_secs(6),
        "get_output blocked on descendant pipe handles"
    );
    assert_eq!(done.status, ShellStatus::Completed);
}

#[cfg(windows)]
#[test]
fn windows_job_terminate_denied_falls_back_to_child_kill() {
    let mut child = Command::new("ping")
        .args(["127.0.0.1", "-n", "20"])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn ping");

    let job = WindowsJob::attach_to_child(&child).expect("attach job");
    let limited_job = duplicate_job_without_terminate_access(job);

    assert!(
        limited_job.terminate().is_err(),
        "limited job handle should not allow TerminateJobObject"
    );

    terminate_child_and_close_windows_job(Some(limited_job), &mut child)
        .expect("fallback child kill");

    let status = child
        .wait_timeout(std::time::Duration::from_secs(3))
        .expect("wait after fallback kill");
    assert!(
        status.is_some(),
        "fallback child kill should terminate child"
    );
}

#[cfg(windows)]
#[test]
fn windows_job_close_releases_foreground_reader_threads_when_terminate_denied() {
    let mut child = Command::new("ping")
        .args(["127.0.0.1", "-n", "8"])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn ping");

    let job = WindowsJob::attach_to_child(&child).expect("attach job");
    let limited_job = duplicate_job_without_terminate_access(job);
    assert!(
        limited_job.terminate().is_err(),
        "limited job handle should not allow TerminateJobObject"
    );

    let stdout_handle = child.stdout.take().expect("stdout pipe");
    let stderr_handle = child.stderr.take().expect("stderr pipe");
    let stdout_thread = std::thread::spawn(move || {
        let mut reader = stdout_handle;
        let mut buf = Vec::new();
        let _ = reader.read_to_end(&mut buf);
        buf
    });
    let stderr_thread = std::thread::spawn(move || {
        let mut reader = stderr_handle;
        let mut buf = Vec::new();
        let _ = reader.read_to_end(&mut buf);
        buf
    });

    let started = std::time::Instant::now();
    terminate_and_close_windows_job(Some(limited_job));
    let _ = stdout_thread.join().unwrap_or_default();
    let _ = stderr_thread.join().unwrap_or_default();
    let status = child
        .wait_timeout(std::time::Duration::from_secs(3))
        .expect("wait after kill-on-close");

    assert!(
        started.elapsed() < std::time::Duration::from_secs(4),
        "reader joins waited for natural descendant exit instead of kill-on-close"
    );
    assert!(status.is_some(), "kill-on-close should terminate child");
}

#[cfg(windows)]
#[test]
fn windows_job_kill_on_close_releases_reader_threads_when_terminate_denied() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let result = execute_shell(
        &mut manager,
        r#"cmd /c start "" /b ping 127.0.0.1 -n 8"#,
        None,
        5000,
        true,
    )
    .expect("execute");
    let task_id = result.task_id.expect("task id");

    {
        let shell = manager
            .processes
            .get_mut(&task_id)
            .expect("background shell");
        let job = shell.windows_job.take().expect("windows job attached");
        let limited_job = duplicate_job_without_terminate_access(job);
        assert!(
            limited_job.terminate().is_err(),
            "limited job handle should not allow TerminateJobObject"
        );
        shell.windows_job = Some(limited_job);
    }

    let started = std::time::Instant::now();
    let done = manager
        .get_output(&task_id, true, 3000)
        .expect("get_output must complete via kill-on-close fallback");

    assert!(
        started.elapsed() < std::time::Duration::from_secs(4),
        "get_output waited for natural descendant exit instead of kill-on-close"
    );
    assert_eq!(done.status, ShellStatus::Completed);
}

#[cfg(windows)]
#[test]
fn killed_shell_does_not_wait_for_blocked_reader_threads() {
    let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
    let stdout_thread = std::thread::spawn(move || {
        let _ = release_rx.recv();
    });
    let now = std::time::Instant::now();
    let mut shell = BackgroundShell {
        id: "killed-reader".to_string(),
        command: "test".to_string(),
        working_dir: std::path::PathBuf::from("."),
        status: ShellStatus::Killed,
        exit_code: None,
        started_at: now,
        last_output_at: now,
        last_observed_output_len: 0,
        sandbox_type: SandboxType::None,
        ownership: ShellOwnership::Managed,
        linked_task_id: None,
        owner_agent: None,
        stdout_buffer: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        stderr_buffer: None,
        heavy_permit: None,
        stdout_cursor: 0,
        stderr_cursor: 0,
        completion_reported: false,
        bounded_output: None,
        stdin: None,
        child: None,
        windows_job: None,
        stdout_thread: Some(stdout_thread),
        stderr_thread: None,
        work_lifecycle: None,
        lifecycle_seq: 0,
        last_lifecycle_status: None,
        last_lifecycle_bytes: 0,
    };

    let started = std::time::Instant::now();
    shell.collect_output();

    assert!(
        started.elapsed() < std::time::Duration::from_secs(1),
        "killed shell must not synchronously join a blocked reader"
    );
    release_tx.send(()).expect("release detached reader");
}

#[test]
fn test_list_jobs_cleans_up_completed_old_processes() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = ShellManager::new(tmp.path().to_path_buf());

    let bg =
        execute_shell(&mut manager, &echo_command("bg"), None, 5000, true).expect("execute bg");
    let bg_id = bg.task_id.expect("bg task id");
    manager.get_output(&bg_id, true, 3000).expect("bg done");

    // Both the completed job and any tracking state should be present.
    assert!(!manager.processes.is_empty());

    // cleanup(ZERO) removes all completed processes immediately.
    manager.cleanup(Duration::ZERO);
    assert!(
        manager.processes.is_empty(),
        "completed processes should be evicted by cleanup"
    );
}

/// Regression for #1691: a `git commit -m "feat: complete sub-pages"` shell
/// command must reach the OS shell with its quoted message intact (one argv
/// slot), never split into `feat:` / `complete` / `sub-pages"`.
#[test]
fn issue_1691_quoted_commit_message_round_trips() {
    let cmd = r#"git commit -m "feat: complete sub-pages""#;
    let spec = CommandSpec::shell(
        cmd,
        std::path::PathBuf::from("/tmp"),
        Duration::from_secs(5),
    );

    let dispatcher = crate::shell_dispatcher::global_dispatcher();
    // The whole command (with quotes) is a single argv entry. The actual
    // shell binary can vary by platform — and the dispatcher may wrap the
    // payload (encoding prefix, exit-code capture) — but the payload itself
    // must stay intact in ONE shell arg. We never split the command string
    // ourselves. This single-line ASCII command never takes the PowerShell
    // temp `-File` path, so the payload stays on the argv.
    assert_eq!(spec.program, dispatcher.kind().binary());
    let carriers = spec
        .args
        .iter()
        .filter(|arg| arg.contains(r#""feat: complete sub-pages""#))
        .count();
    assert_eq!(carriers, 1, "args: {:?}", spec.args);
    assert!(
        !spec
            .args
            .iter()
            .any(|arg| arg == "feat:" || arg == "complete" || arg == "sub-pages\""),
        "args: {:?}",
        spec.args
    );
    assert_eq!(spec.display_command(), cmd);

    let mut built = Command::new(&spec.program);
    push_shell_args(&mut built, &spec.program, &spec.args);
    let got: Vec<String> = built
        .get_args()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    assert_eq!(got, spec.args);
}

/// When no `cwd` is provided, the shell should run in `context.workspace`,
/// not in the ShellManager's default_workspace. This ensures sub-agents in
/// worktrees run commands in the worktree directory rather than the parent.
///
/// Without the `context.workspace` default (stashed): runs in sm_dir → FAILS
/// With the `context.workspace` default (unstashed): runs in ctx_dir → PASSES
#[tokio::test]
async fn default_cwd_uses_context_workspace_not_shell_manager_default() {
    let ctx_dir = tempdir().expect("ctx tempdir");
    let sm_dir = tempdir().expect("sm tempdir");

    // Create distinct dirs — write a marker in each so we can tell them apart.
    std::fs::write(ctx_dir.path().join("I_AM_CTX_DIR"), "").unwrap();
    std::fs::write(sm_dir.path().join("I_AM_SM_DIR"), "").unwrap();

    // ToolContext whose workspace is ctx_dir...
    let ctx = ToolContext::new(ctx_dir.path())
        // ...but whose ShellManager's default_workspace is sm_dir.
        .with_shell_manager(new_shared_shell_manager(sm_dir.path().to_path_buf()));

    // Assert directory identity through marker files instead of comparing the
    // shell's printed path. PowerShell and `canonicalize` can spell the same
    // Windows path differently (for example, with a verbatim-path prefix).
    let command = if cfg!(windows) {
        "if (Test-Path -LiteralPath 'I_AM_CTX_DIR') { Write-Output 'context-workspace' } elseif (Test-Path -LiteralPath 'I_AM_SM_DIR') { Write-Output 'manager-workspace' } else { Write-Output 'missing-workspace' }"
    } else {
        "if [ -f I_AM_CTX_DIR ]; then printf 'context-workspace'; elif [ -f I_AM_SM_DIR ]; then printf 'manager-workspace'; else printf 'missing-workspace'; fi"
    };
    let result = BashTool::new("Bash")
        .execute(json!({"command": command}), &ctx)
        .await
        .expect("shell execute");
    assert!(result.success, "command failed: {:?}", result.content);

    assert!(
        result
            .content
            .lines()
            .any(|line| line.trim() == "context-workspace"),
        "expected context.workspace marker, but shell reported: {:?}",
        result.content
    );
}

// ── Kill-path overshoot regression tests (FINISH-0.9.4 #52 multiplier 2) ─────
//
// The foreground Bash kill path must return at ~timeout + a small bounded
// grace, even when the command ignores SIGTERM or a descendant escapes the
// process group while holding the output pipe open. Before the fix, an
// escaped descendant wedged the blocking reader-thread join inside kill()
// until the descendant exited on its own (observed: ~180s past a 120s
// timeout in the wild).

#[cfg(unix)]
const SHELL_SIGTERM_HELPER_ENV: &str = "CODEWHALE_SHELL_SIGTERM_HELPER";
#[cfg(unix)]
const SHELL_ESCAPE_HELPER_ENV: &str = "CODEWHALE_SHELL_ESCAPE_HELPER";
#[cfg(unix)]
const SHELL_ESCAPED_GRANDCHILD_ENV: &str = "CODEWHALE_SHELL_ESCAPED_GRANDCHILD";

/// Helper role: ignore SIGTERM and idle. Runs as the shell's direct child
/// (same process group), so only the SIGKILL escalation can stop it.
#[cfg(unix)]
#[test]
fn shell_sigterm_ignoring_helper_process() {
    if std::env::var(SHELL_SIGTERM_HELPER_ENV).ok().as_deref() != Some("1") {
        return;
    }
    unsafe {
        libc::signal(libc::SIGTERM, libc::SIG_IGN);
    }
    let pid_file = PathBuf::from(
        std::env::var(SHELL_DESCENDANT_PID_FILE_ENV).expect("sigterm helper pid file"),
    );
    std::fs::write(pid_file, std::process::id().to_string()).expect("write sigterm helper pid");
    loop {
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// Helper role: spawn a grandchild in its OWN process group (escaping the
/// shell's group) that inherits the output pipe, then exit immediately. The
/// wrapper shell keeps running (`sleep` after `&`), so the job stays Running
/// while the escaped grandchild holds the reader thread's pipe open.
#[cfg(unix)]
// The grandchild deliberately outlives this helper and is never wait()ed on —
// escaping reaping is exactly what the regression exercises; the test reaps
// it directly via SIGKILL at the end.
#[allow(clippy::zombie_processes)]
#[test]
fn shell_group_escape_helper_process() {
    if std::env::var(SHELL_ESCAPE_HELPER_ENV).ok().as_deref() != Some("1") {
        return;
    }
    let test_binary = std::env::current_exe().expect("current test binary");
    let pid_file = std::env::var(SHELL_DESCENDANT_PID_FILE_ENV).expect("escape pid file");
    let mut cmd = Command::new(test_binary);
    cmd.arg("--exact")
        .arg("tools::shell::tests::shell_escaped_grandchild_helper_process")
        .arg("--nocapture")
        .env(SHELL_ESCAPED_GRANDCHILD_ENV, "1")
        .env(SHELL_DESCENDANT_PID_FILE_ENV, pid_file);
    // A distinct process group is enough to escape `kill(-wrapper_pgid)`;
    // stdout/stderr are inherited, so the grandchild keeps the pipe open.
    #[cfg(unix)]
    cmd.process_group(0);
    let _child = cmd.spawn().expect("spawn escaped grandchild");
}

/// Helper role: the escaped grandchild — ignores SIGTERM, reports its pid,
/// then idles (holding the inherited output pipe open the whole time).
#[cfg(unix)]
#[test]
fn shell_escaped_grandchild_helper_process() {
    if std::env::var(SHELL_ESCAPED_GRANDCHILD_ENV).ok().as_deref() != Some("1") {
        return;
    }
    unsafe {
        libc::signal(libc::SIGTERM, libc::SIG_IGN);
    }
    let pid_file =
        PathBuf::from(std::env::var(SHELL_DESCENDANT_PID_FILE_ENV).expect("grandchild pid file"));
    std::fs::write(pid_file, std::process::id().to_string()).expect("write grandchild pid");
    std::thread::sleep(Duration::from_secs(30));
}

/// Required regression: a foreground command that ignores SIGTERM must be
/// dead and the tool must have returned within timeout + a small grace
/// (2s timeout, assert wall < 10s).
#[cfg(unix)]
#[tokio::test]
async fn foreground_timeout_kills_sigterm_ignoring_command_within_grace() {
    let tmp = tempdir().expect("tempdir");
    let pid_file = tmp.path().join("sigterm-helper.pid");
    let test_binary = std::env::current_exe().expect("current test binary");
    let command = format!(
        "{SHELL_SIGTERM_HELPER_ENV}=1 {SHELL_DESCENDANT_PID_FILE_ENV}={} exec {} --exact {} --nocapture",
        shell_words::quote(&pid_file.display().to_string()),
        shell_words::quote(&test_binary.display().to_string()),
        shell_words::quote("tools::shell::tests::shell_sigterm_ignoring_helper_process"),
    );
    let ctx = ToolContext::new(tmp.path());

    let started = Instant::now();
    let result = BashTool::new("Bash")
        .execute(json!({"command": command, "timeout_ms": 2_000}), &ctx)
        .await
        .expect("execute");
    let wall = started.elapsed();

    assert!(!result.success);
    let meta = result.metadata.expect("metadata");
    assert_eq!(meta.get("status").and_then(Value::as_str), Some("TimedOut"));
    assert!(
        wall < Duration::from_secs(10),
        "kill path overshot the 2s timeout: wall {wall:?}"
    );
    let helper_pid = wait_for_shell_pid_file(&pid_file);
    assert!(
        wait_for_shell_pid_exit(helper_pid),
        "SIGTERM-ignoring helper {helper_pid} survived the timeout kill"
    );
}

/// Regression for the ~180s kill-path overshoot: a descendant that escaped
/// the process group keeps the output pipe open after the group is killed.
/// kill() must still return within a bounded grace instead of blocking on
/// the reader-thread join until the descendant exits on its own.
#[cfg(unix)]
#[tokio::test]
async fn kill_returns_promptly_when_escaped_descendant_holds_pipe_open() {
    let tmp = tempdir().expect("tempdir");
    let pid_file = tmp.path().join("escaped-grandchild.pid");
    let test_binary = std::env::current_exe().expect("current test binary");
    let command = format!(
        "{SHELL_ESCAPE_HELPER_ENV}=1 {SHELL_DESCENDANT_PID_FILE_ENV}={} {} --exact {} --nocapture & sleep 60",
        shell_words::quote(&pid_file.display().to_string()),
        shell_words::quote(&test_binary.display().to_string()),
        shell_words::quote("tools::shell::tests::shell_group_escape_helper_process"),
    );
    let mut manager = ShellManager::new(tmp.path().to_path_buf());
    let started_bg =
        execute_shell(&mut manager, &command, None, 600_000, true).expect("start wrapper");
    let task_id = started_bg.task_id.expect("task id");
    let grandchild = wait_for_shell_pid_file(&pid_file);

    let started = Instant::now();
    let killed = manager.kill(&task_id).expect("kill");
    let wall = started.elapsed();

    assert_eq!(killed.status, ShellStatus::Killed);
    assert!(
        wall < Duration::from_secs(10),
        "kill blocked {wall:?} on a reader wedged by an escaped descendant"
    );

    // Cleanup: the escaped grandchild is out of reach of the group kill by
    // construction; reap it directly so the test does not leak a sleeper.
    unsafe {
        libc::kill(grandchild, libc::SIGKILL);
    }
    assert!(wait_for_shell_pid_exit(grandchild));
}

/// `Bash` was the only action wrapper whose catch-all fell through to its most
/// dangerous branch: an unrecognised action ran the command instead.
#[tokio::test]
async fn unknown_bash_action_is_refused_instead_of_running_the_command() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path().to_path_buf());
    let marker = workspace.path().join("should-not-exist");

    let error = BashTool::new("Bash")
        .execute(
            json!({
                "action": "kill",
                "command": format!("touch {}", marker.display()),
            }),
            &context,
        )
        .await
        .expect_err("unknown action must be refused");

    let message = error.to_string();
    assert!(message.contains("Unknown Bash action"), "{message}");
    assert!(message.contains("kill"), "{message}");
    assert!(
        message.contains("run, wait, interact, cancel"),
        "must name the actions that dispatch: {message}"
    );
    assert!(!marker.exists(), "the command must not have run");
}

/// The same hole one type down. `and_then(as_str).unwrap_or("run")` read a
/// non-string `action` as absent and fell through to the branch that executes
/// arbitrary code, so `Bash{action: 3, command: "…"}` ran the command. `File`,
/// `Git`, `Web`, and `Run` all refuse a non-string action; the tool that runs
/// shell commands must not be the lenient one.
#[tokio::test]
async fn non_string_bash_action_is_refused_instead_of_running_the_command() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path().to_path_buf());

    for action in [json!(3), json!(true), json!(["run"]), json!({"run": true})] {
        let marker = workspace.path().join(format!("marker-{action}"));
        let error = BashTool::new("Bash")
            .execute(
                json!({
                    "action": action,
                    "command": format!("touch {}", marker.display()),
                }),
                &context,
            )
            .await
            .expect_err("a non-string action must be refused");

        let message = error.to_string();
        assert!(
            message.contains("'action'"),
            "must name the parameter: {message}"
        );
        assert!(
            message.contains("must be a string"),
            "must name the expected type: {message}"
        );
        assert!(!marker.exists(), "the command must not have run: {action}");
    }
}

/// The same hole for the data fields (2026-08-04 review). A non-string
/// `stdin` was silently dropped — the command ran with NO stdin and reported
/// success, the silent-drop failure this lane exists to close. A non-string
/// `cwd` silently ran in the workspace default. And a numeric `task_id` was
/// reported as "missing", steering the model's retry the wrong way.
#[tokio::test]
async fn wrongly_typed_stdin_cwd_and_task_id_are_refused_not_dropped() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path().to_path_buf());

    let marker = workspace.path().join("stdin-marker");
    let error = BashTool::new("Bash")
        .execute(
            json!({
                "command": format!("touch {}", marker.display()),
                "stdin": 12345,
            }),
            &context,
        )
        .await
        .expect_err("non-string stdin must be refused, never silently dropped");
    let message = error.to_string();
    assert!(message.contains("'stdin'"), "names the field: {message}");
    assert!(
        message.contains("must be a string"),
        "names the expected type: {message}"
    );
    assert!(!marker.exists(), "the command must not have run");

    let error = BashTool::new("Bash")
        .execute(json!({ "command": "pwd", "cwd": 123 }), &context)
        .await
        .expect_err("non-string cwd must be refused, never defaulted");
    assert!(error.to_string().contains("'cwd'"), "{error}");

    let error = BashTool::new("Bash")
        .execute(json!({ "action": "wait", "task_id": 42 }), &context)
        .await
        .expect_err("non-string task_id is a type error");
    let message = error.to_string();
    assert!(
        message.contains("'task_id'") && message.contains("must be a string"),
        "a supplied-but-mistyped task_id must not read as missing: {message}"
    );
}

/// `null` is the wire spelling of absence, and `action` documents a `run`
/// default — so the strictness above must not swallow the default.
#[tokio::test]
async fn absent_or_null_bash_action_still_defaults_to_run() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path().to_path_buf());

    for input in [
        json!({"command": "echo defaulted"}),
        json!({"action": null, "command": "echo defaulted"}),
    ] {
        let result = BashTool::new("Bash")
            .execute(input.clone(), &context)
            .await
            .unwrap_or_else(|err| panic!("{input} must still run: {err}"));
        assert!(result.success, "{input}: {}", result.content);
        assert!(result.content.contains("defaulted"), "{}", result.content);
    }
}

/// Negative case for the strictness above: every legitimate action still
/// dispatches to its own handler rather than the action refusal. `wait`,
/// `interact`, and `cancel` are checked by the error they raise *after*
/// dispatch (a missing/unknown task), which only their own handlers produce.
#[tokio::test]
async fn every_valid_bash_action_still_dispatches() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path().to_path_buf());
    let tool = BashTool::new("Bash");

    let ran = tool
        .execute(
            json!({"action": "run", "command": "echo dispatched"}),
            &context,
        )
        .await
        .expect("action=run must dispatch");
    assert!(ran.success, "{}", ran.content);

    for input in [
        json!({"action": "wait", "task_id": "no-such-task"}),
        json!({"action": "interact", "task_id": "no-such-task", "stdin": "y\n"}),
        json!({"action": "cancel", "task_id": "no-such-task"}),
    ] {
        let outcome = tool.execute(input.clone(), &context).await;
        let message = match outcome {
            Ok(result) => result.content,
            Err(err) => err.to_string(),
        };
        assert!(
            !message.contains("Unknown Bash action") && !message.contains("must be a string"),
            "{input} must reach its own handler, got: {message}"
        );
    }

    // `cancel` with `all` needs no task at all and must stay a success.
    let cancelled = tool
        .execute(json!({"action": "cancel", "all": true}), &context)
        .await
        .expect("action=cancel all=true must dispatch");
    assert!(cancelled.success, "{}", cancelled.content);
}

/// The stdin aliases were real but undocumented: a model that wrote `input`
/// or `data` got them honoured with nothing in the schema saying so, and a
/// maintainer reading the schema would have removed them as dead. Advertise
/// them, and hold every spelling to the same behavior.
#[tokio::test]
async fn every_advertised_stdin_spelling_reaches_the_command() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path().to_path_buf());
    let schema = BashTool::new("Bash").input_schema();

    // `cat` is Unix-only; the dispatcher runs PowerShell or `cmd` on Windows,
    // where it is either absent or an alias for `Get-Content`, which reads a
    // file and not stdin. Ask for this platform's echo-stdin spelling — the
    // same helper `test_write_stdin_streams_output` uses.
    let echo_stdin = echo_stdin_command();
    for spelling in ["stdin", "input", "data"] {
        assert!(
            schema["properties"][spelling].is_object(),
            "`{spelling}` is honoured at runtime and must be advertised"
        );
        let result = BashTool::new("Bash")
            .execute(
                json!({"command": echo_stdin, spelling: "PIPED_THROUGH_ALIAS\n"}),
                &context,
            )
            .await
            .unwrap_or_else(|err| panic!("`{spelling}` must deliver stdin: {err}"));
        assert!(
            result.content.contains("PIPED_THROUGH_ALIAS"),
            "`{spelling}` did not reach the command: {}",
            result.content
        );
    }

    // `id` is the same undocumented shape one parameter over.
    assert!(
        schema["properties"]["id"].is_object(),
        "`id` is accepted for `task_id` at runtime and must be advertised"
    );
    assert!(
        schema["properties"]["task_id"]["description"]
            .as_str()
            .is_some_and(|text| text.contains("`id`")),
        "task_id must name its alias"
    );
}

/// The schema declared no `required` key at all, so `Bash{}` — no command, no
/// task — was schema-valid for the tool that runs shell commands. What is
/// required is per-action, so it is spelled as root `anyOf` required groups,
/// the same shape `finance` and `apply_patch` already use.
#[test]
fn bash_schema_declares_what_each_action_requires() {
    let schema = BashTool::new("Bash").input_schema();
    let groups: Vec<Vec<String>> = schema["anyOf"]
        .as_array()
        .expect("root anyOf required groups")
        .iter()
        .map(|group| {
            group["required"]
                .as_array()
                .expect("required group")
                .iter()
                .map(|name| name.as_str().expect("required name").to_string())
                .collect()
        })
        .collect();

    for expected in [["command"], ["task_id"], ["id"], ["all"]] {
        assert!(
            groups.iter().any(|group| group.as_slice() == expected),
            "missing required group {expected:?} in {groups:?}"
        );
    }
    // A required name the same schema does not advertise would be
    // unsatisfiable: the model could not learn what to send.
    for group in &groups {
        for name in group {
            assert!(
                schema["properties"][name].is_object(),
                "`{name}` is required but not advertised"
            );
        }
    }
}

/// A root `anyOf` is not portable to every provider, so prove the fallback
/// the sanitizer promises: Responses/xAI drop root composition, and the
/// constraint has to survive as a description note rather than vanishing.
#[test]
fn bash_required_groups_survive_a_provider_that_drops_root_composition() {
    let mut schema = BashTool::new("Bash").input_schema();
    let note = crate::tools::schema_sanitize::sanitize_for_responses(&mut schema)
        .expect("dropped required groups must be restated for the model");

    assert!(note.contains("At least one"), "{note}");
    for name in ["`command`", "`task_id`", "`id`", "`all`"] {
        assert!(note.contains(name), "note must name {name}: {note}");
    }
    assert_eq!(schema["type"], "object");
    assert!(schema.get("anyOf").is_none(), "root anyOf must be removed");
    assert!(schema["properties"]["command"].is_object());
}

/// Every hint in this file has to name a tool the model can actually call.
/// `exec_shell` / `exec_shell_wait` were retired in v0.9.3.
#[test]
fn shell_recovery_hints_name_only_dispatchable_tools() {
    assert!(!FOREGROUND_TIMEOUT_RECOVERY_HINT.contains("exec_shell"));
    assert!(FOREGROUND_TIMEOUT_RECOVERY_HINT.contains("Bash"));
    assert!(FOREGROUND_TIMEOUT_RECOVERY_HINT.contains("action=\"wait\""));
}

/// One documented default hid three real ones: `wait` uses 30s and
/// `interact` 1s, so a model omitting `timeout_ms` on `wait` got a quarter of
/// the timeout the schema promised.
#[test]
fn timeout_ms_description_covers_every_action_default() {
    let schema = BashTool::new("Bash").input_schema();
    let description = schema["properties"]["timeout_ms"]["description"]
        .as_str()
        .expect("timeout_ms description");

    for expected in ["120000", "600000", "30000", "1000"] {
        assert!(
            description.contains(expected),
            "missing {expected}: {description}"
        );
    }
}

#[cfg(unix)]
fn authorized_persistent_service_context(workspace: &Path) -> ToolContext {
    let mut context = ToolContext::new(workspace.to_path_buf())
        .with_elevated_sandbox_policy(ExecutionSandboxPolicy::DangerFullAccess);
    context.persist_services_enabled = true;
    context.tool_authority = None;
    context.shell_policy = ShellPolicy::Full;
    context.auto_approve = true;
    context
}

#[cfg(unix)]
fn persistent_service_test_lock() -> &'static tokio::sync::Mutex<()> {
    static LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
}

#[cfg(unix)]
#[tokio::test]
async fn persistent_service_requires_explicit_headless_exec_authority() {
    let workspace = tempdir().expect("workspace");
    let context = ToolContext::new(workspace.path().to_path_buf());

    let error = BashTool::new("Bash")
        .execute(
            json!({
                "action": "run",
                "command": "sleep 30",
                "background": true,
                "persist": true,
            }),
            &context,
        )
        .await
        .expect_err("ordinary tool contexts must reject ownership transfer");

    assert!(error.to_string().contains("real headless `codewhale exec`"));
}

#[cfg(unix)]
#[tokio::test]
async fn committed_persistent_service_survives_manager_drop_and_reports_identity() {
    let _guard = persistent_service_test_lock().lock().await;
    let workspace = tempdir().expect("workspace");
    let marker = workspace.path().join("persistent-service-finished");
    let context = authorized_persistent_service_context(workspace.path());

    let result = BashTool::new("Bash")
        .execute(
            json!({
                "action": "run",
                "command": format!("sleep 1; printf released > '{}'", marker.display()),
                "background": true,
                "persist": true,
            }),
            &context,
        )
        .await
        .expect("stage persistent service");
    assert!(result.success, "{result:?}");
    assert_eq!(
        result
            .metadata
            .as_ref()
            .and_then(|metadata| metadata["ownership"].as_str()),
        Some("managed_pending_exec_success")
    );
    let task_id = result.metadata.as_ref().unwrap()["task_id"]
        .as_str()
        .expect("task id")
        .to_string();

    let receipts = context
        .shell_manager
        .lock()
        .expect("shell manager")
        .commit_persistent_services()
        .expect("commit persistent service");
    assert_eq!(receipts.len(), 1);
    assert_eq!(receipts[0].task_id, task_id);
    assert_eq!(receipts[0].process_group_id, receipts[0].pid);
    assert_eq!(receipts[0].ownership, "external");

    drop(context);
    let deadline = Instant::now() + Duration::from_secs(5);
    while !marker.exists() && Instant::now() < deadline {
        std::thread::sleep(Duration::from_millis(25));
    }
    assert!(
        marker.exists(),
        "released service must survive Codewhale manager teardown"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn signal_cleanup_kills_staged_persistent_service_group() {
    let _guard = persistent_service_test_lock().lock().await;
    let workspace = tempdir().expect("workspace");
    let context = authorized_persistent_service_context(workspace.path());

    let result = BashTool::new("Bash")
        .execute(
            json!({
                "action": "run",
                "command": "sleep 30",
                "background": true,
                "persist": true,
            }),
            &context,
        )
        .await
        .expect("stage persistent service");
    let task_id = result.metadata.as_ref().unwrap()["task_id"]
        .as_str()
        .expect("task id")
        .to_string();
    let pid = context
        .shell_manager
        .lock()
        .expect("shell manager")
        .processes[&task_id]
        .child
        .as_ref()
        .and_then(ShellChild::process_id)
        .expect("persistent process id");

    abort_pending_persistent_process_groups_for_exit();
    let pid = i32::try_from(pid).expect("pid fits pid_t");
    let deadline = Instant::now() + Duration::from_secs(2);
    let status = loop {
        let mut status = 0;
        // SAFETY: `pid` is the direct child owned by this test's manager; the
        // nonblocking wait only reaps that exact process.
        let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
        if waited == pid {
            break status;
        }
        assert!(
            Instant::now() < deadline,
            "signal cleanup must kill the staged service process group"
        );
        std::thread::sleep(Duration::from_millis(25));
    };
    assert!(libc::WIFSIGNALED(status));
    assert_eq!(libc::WTERMSIG(status), libc::SIGKILL);
}