mahbot 0.7.3

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
//! The shell tool: a command string run by the platform's shell, with its output
//! captured, its process tree contained, and its bounds enforced.
//!
//! Two modes ([`ShellMode`]) share everything below: `Full` is an agent's own
//! shell, while `ReadOnly` only lets through the commands the guard ([`readonly`])
//! allows. A third, deliberately separate surface — the background session
//! ([`bg`]) — is how a `Full` agent starts a command meant to keep running after
//! the tool call returns.
//!
//! # What decides a call
//!
//! The command's own EXIT STATUS decides the call, never the fate of the pipe
//! readers: a command that exited 0 is a success and one that exited non-zero is
//! its own failure, and its output is what its pipes delivered. Two bounds frame
//! that output — the per-stream capture cap ([`SHELL_PIPE_READ_CAP`]) and the
//! post-exit drain ([`DEFAULT_OUTPUT_DRAIN_TIMEOUT_SECS`]) — and neither turns a
//! finished command into an error.
//!
//! A process the command left behind can keep a capture pipe open past the drain
//! bound, so EOF never arrives. What happens then is the run's
//! [`LeftoverPolicy`], chosen by the caller: an agent's command (`Keep`) reports
//! the command's own exit status and the output collected so far, and leaves the
//! leftover RUNNING with its output channel still held open on our side — it was
//! started on purpose — reporting it in the result, and where its containment can
//! be named, how to stop it ([`format_leftover_note`]). That "left running" is
//! what the product provides while it RETAINS the channel; releasing it (past the
//! retained-channel cap) ends the guarantee
//! ([`crate::util::leftover_channels`]). A program this product
//! runs for itself (a user's alarm, a custom tool's script, the document kit)
//! uses `End`: the run's tree is ended and the run is reported as a failure
//! ([`ShellRunResult::EndedWithLeftovers`]).
//!
//! # The runner's own steps
//!
//! On Windows a line that runs this product's own image cannot be waited for by
//! cmd.exe ([`plan`]), so such a line is decomposed and run by the runner itself;
//! its result is the same [`ShellRunResult`] a shell run produces. The grep engine
//! ([`grep_engine`]) rewrites searches the same way. The plan runner and the
//! single-child runner share the capture ([`Readers`]), the containment
//! ([`tree`]) and the bounds ([`Watchdog`]) below, so a change to any of them is a
//! change to both.
//!
//! [`tree`]: self::tree
//! [`bg`]: self::bg
//! [`readonly`]: self::readonly
//! [`plan`]: self::plan
//! [`grep_engine`]: self::grep_engine

use crate::{Tool, Workspace};
use async_trait::async_trait;
use directories::UserDirs;
use futures_util::stream::{FuturesUnordered, StreamExt};
use regex::RegexSet;
use serde_json::json;
use std::collections::HashSet;
use std::ffi::OsString;
use std::fmt::Write;
use std::path::{Path, PathBuf};
use std::process::Stdio;
#[cfg(windows)]
use std::sync::OnceLock;
use std::time::Duration;

use super::listing::{ListingEntry, format_listing, human_readable_size};
use super::with_note;
use crate::util::TOOL_OUTPUT_BUDGET_BYTES;
use crate::util::UnwrapPoison;
use crate::util::scrub_credentials;
use crate::util::strip_ansi_escapes;

mod bg;
pub(crate) mod grep_engine;
mod mem;
mod plan;
mod profiles;
mod readonly;
mod scan;
mod tree;
mod windows_line;
mod windows_text;

pub(crate) use self::bg::BackgroundSessions;
use self::profiles::{CARGO_COMPILE_PREFIXES, GEN_FALLBACK, PROFILES, Profile};
pub use self::readonly::ShellMode;
use self::readonly::check_command;
use self::tree::{RunOwner, Tree};

/// The shell that runs a validated command string (`sh -c` on unix, `cmd.exe`
/// with its own settings pinned — [`WINDOWS_COMMAND_SWITCHES`] — and `/C` on
/// Windows). Every platform rule in this module tree reads
/// this one value — the spawn side ([`build_shell_command`]), the reading of a
/// command's line breaks ([`windows_line`], which decides the text the spawn
/// hands over), the read-only guard's tables and the grep engine's command
/// model — as a runtime value
/// rather than a `cfg` branch, so both platforms' behaviour is drivable from
/// any host's unit-test lane. Only the value's own definition branches on the
/// target ([`SHELL_PLATFORM`] is one `if cfg!(windows)` constant); every
/// consumer takes it as data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ShellPlatform {
    Unix,
    Windows,
}

/// The running process's [`ShellPlatform`]; its spawn side is
/// [`build_shell_command`] — the two must not drift.
pub(super) const SHELL_PLATFORM: ShellPlatform = if cfg!(windows) {
    ShellPlatform::Windows
} else {
    ShellPlatform::Unix
};

/// The Windows command interpreter, named once so the spawn side
/// ([`build_shell_command`]) and the GUI Shell page's terminal
/// (`gui::shell::terminal_program`) cannot start different programs.
pub(crate) const WINDOWS_COMMAND_INTERPRETER: &str = "cmd.exe";

/// The switches the Windows command interpreter is always started with, ahead of
/// `/C`: `/D` disables the machine's AutoRun scripts, `/E:ON` fixes command
/// extensions on and `/V:OFF` fixes delayed expansion off. Those three are
/// otherwise read from the machine's registry, where any of them would make the
/// same command text behave differently; pinned here, this interpreter's own
/// behaviour is the product's rather than the machine's. Two consequences are
/// deliberate: the machine's AutoRun scripts no longer run for the commands this
/// shell starts, and an interpreter a command starts for itself (`cmd`,
/// `powershell`) keeps the machine's own settings, because only this one is
/// pinned.
const WINDOWS_COMMAND_SWITCHES: &str = "/D /E:ON /V:OFF";

/// The frame every refusal of a run opens with — the cause follows, then the
/// consequence that belongs to the entry point that refused. Spelled once here so
/// the four renderers of it ([`grep_engine::unserved_failure`], the plan runner's
/// [`plan::refusal_message`], [`windows_line::refusal`], and the read-only guard's
/// own [`readonly::windows::refusal`]) cannot word one cause two ways.
pub(super) const REFUSAL_FRAME: &str = "Command not run: ";

/// The shared rendering of a refusal: the frame that names the refusing reader —
/// the shared [`REFUSAL_FRAME`] above, or the read-only guard's own — the cause,
/// the command itself and what to write instead. Both frames go through here so
/// their tail cannot drift apart.
pub(super) fn framed_refusal(frame: &str, cmd: &str, why: &str, suggestion: &str) -> String {
    format!("{frame}{why}\nCommand: `{cmd}`\nSuggestion: {suggestion}")
}

/// Shell builtins/prefixes to skip when extracting the primary command.
/// NOTE: `su` is intentionally NOT in this list. It can be used to run
/// commands as another user (e.g., `su -c "rm -rf /"`), which would bypass
/// the read-only validation. This is an accepted gap — adding `su` would be
/// a half-measure since there are countless other privilege-escalation
/// vectors, and the read-only shell is a best-effort safety layer, not a
/// sandbox.
pub(super) const SHELL_PREFIXES: &[&str] = &[
    "cd",
    "pushd",
    "popd",
    "export",
    "source",
    ".",
    "sudo",
    "time",
    // `!` negation: needed so the raw first-command-word scan skips it
    // (`time ! rm -rf ./x` must dispatch `rm` to the blocklist). Side effect
    // on shared consumers: `canonical_command` routes `! ls` to the ls
    // profile — safe direction, profile selection only.
    "!",
    "command",
    "builtin",
    "env",
    "nohup",
    "exec",
    "nice",
    "noglob",
    "nocorrect",
    "eval",
    "npx",
];

/// Corresponding entries in [`SHELL_PREFIXES`] that do NOT forward their
/// arguments as a command — they change shell state internally. These are
/// excluded from delegation-based tests because they don't execute their
/// arguments.
#[cfg(test)]
pub(super) const NON_DELEGATING_PREFIXES: &[&str] =
    &["cd", "pushd", "popd", "export", "source", "."];

/// Git global flags that may appear between `git` and its subcommand.
///
/// **IMPORTANT**: Only include flags that take a space-separated value argument.
/// Boolean flags like `--bare` MUST NOT be listed here — `find_first_non_flag_index`
/// skips 2 words (flag + value) for each entry, causing boolean flags to consume
/// the subcommand as their "value" and bypass read-only validation entirely.
const GIT_GLOBAL_FLAGS: &[&str] = &["-C", "--git-dir", "--work-tree", "-c"];

/// Default maximum shell command execution time before kill.
const DEFAULT_SHELL_TIMEOUT_SECS: u64 = 600;
/// Absolute maximum allowed shell command timeout (1 hour).
/// Prevents agents from setting absurdly long timeouts.
const MAX_SHELL_TIMEOUT_SECS: u64 = 3600;
/// Default bound on the post-exit output drain (seconds). After the main
/// command exited, remaining output must drain within this bound — a leftover
/// backgrounded process holding the pipes open otherwise blocks EOF forever.
/// How the bound is resolved is the run's [`LeftoverPolicy`]: an agent's command
/// reports its own exit status and leaves the leftover running
/// ([`ShellRunResult::ExitedWithLeftovers`]); a program run ends its tree and is
/// reported as a failure ([`ShellRunResult::EndedWithLeftovers`]).
const DEFAULT_OUTPUT_DRAIN_TIMEOUT_SECS: u64 = 10;
/// Grace window given to pipe readers to notice cancellation and return
/// buffered partial output after a process-group kill.
const DRAIN_CANCEL_GRACE: Duration = Duration::from_secs(2);
/// How often a running command's whole process tree is sampled for resident
/// memory ([`mem`]) — modest, since every sample walks the tree and reads
/// each process in it. A run always takes at least one sample: the interval's
/// first tick is immediate.
const MEMORY_SAMPLE_INTERVAL: Duration = Duration::from_millis(250);
/// Cap bytes collected from a run's pipes during command execution (including
/// timeouts): what each stream of a run's capture gets ([`CaptureBudget`]).
///
/// # Truncation safety
///
/// This cap (256 KB) is well below 1 MB, so the [`decode_and_strip_ansi`]
/// output never reaches a size where truncation would be necessary. If this
/// cap is ever raised above 1 MB, re-add truncation safeguards (e.g.,
/// [`truncate_sandwich`](crate::util::truncate_sandwich) after ANSI stripping)
/// to prevent unbounded output.
const SHELL_PIPE_READ_CAP: usize = 256 * 1024;
/// Max chars of partial output included in timeout error messages.
const TIMEOUT_OUTPUT_TAIL_CHARS: usize = 2_000;
/// Max chars of the engine's own stderr line quoted as the cause of a refused
/// Windows search (see [`engine_cause`]).
const ENGINE_FAILURE_DETAIL_CHARS: usize = 200;

/// The reduced environment the product uses for its own internal work and as the
/// fallback for the agent's commands until a read of the owner's environment
/// succeeds (see [`crate::shell_env`]).
///
/// Only functional variables are included — never API keys or secrets. The
/// platform's temp variables are NOT listed here: they are bound to the daemon's
/// private temp root by [`crate::temp::shell_temp_vars`].
#[cfg(not(target_os = "windows"))]
const FALLBACK_ENV_VARS: &[&str] = &[
    "PATH", "HOME", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "USER", "SHELL",
];

/// The reduced environment, as [`FALLBACK_ENV_VARS`] on every other platform,
/// carrying in addition the Windows-specific variables program resolution and
/// cmd.exe need. The temp variables are not listed here either: they are bound to
/// the daemon's private temp root.
#[cfg(target_os = "windows")]
const FALLBACK_ENV_VARS: &[&str] = &[
    "PATH",
    "PATHEXT",
    "HOME",
    "USERPROFILE",
    "HOMEDRIVE",
    "HOMEPATH",
    "SYSTEMROOT",
    "SYSTEMDRIVE",
    "WINDIR",
    "COMSPEC",
    "TERM",
    "LANG",
    "USERNAME",
];

/// The environment the product's own work runs in — git (see
/// [`crate::git::commands::git_command`]) and the document kit — and the one an
/// agent's command falls back to until the owner's environment has been read
/// ([`agent_env_pairs`]): every name in [`FALLBACK_ENV_VARS`] with its baseline
/// value, then the platform's temp variables bound to the daemon's private temp
/// root.
///
/// The temp names and value come from [`crate::temp::shell_temp_vars`] — the same
/// pair the read-only guard's temp model reads — so the scratch location a child
/// actually writes to and the location the guard accepts for a write cannot drift
/// apart, and a new temp name reaches both at once.
///
/// A child's environment is cleared and re-populated from this list (see
/// [`program_command`]): the product's own work must not be affected by the
/// owner's personal environment, and must not leak credentials anywhere. Internal
/// work that is not given an environment at all — self-update's cargo child, the
/// chrome CLI and the browser, the GUI Shell page's terminal — inherits this
/// process's environment, as documented where each is spawned.
#[must_use]
pub(crate) fn internal_env_pairs() -> Vec<(OsString, OsString)> {
    let mut pairs = Vec::new();
    for &name in FALLBACK_ENV_VARS {
        if let Some(value) = baseline_env_value(name) {
            pairs.push((OsString::from(name), OsString::from(value)));
        }
    }
    for (name, value) in crate::temp::shell_temp_vars() {
        pairs.push((OsString::from(name), OsString::from(value)));
    }
    pairs
}

/// The environment an agent's command runs in: the owner's own environment
/// ([`crate::shell_env::snapshot`]) once a read has succeeded, with the
/// data-location home and the pinned temp names applied last, otherwise the
/// reduced [`internal_env_pairs`].
///
/// Nothing read from the owner's environment is filtered — his secrets and
/// tokens are handed over as they are, by design: these are his own commands
/// doing his own work. The two overrides keep winning, which is what the
/// documented "test instance from another folder" workflow relies on: `HOME`
/// stays the data-location home and the temp names stay the private temp root,
/// so a command cannot write into the owner's real home or temp area by
/// accident. On Windows the home that wins is the profile the OS reports for the
/// owner — not `$HOME`, so an install relocated through it is not reflected — and
/// the OS-assembled `USERPROFILE` stays as the owner's profile; the temp names
/// are pinned there like everywhere else.
#[must_use]
pub(crate) fn agent_env_pairs() -> Vec<(OsString, OsString)> {
    crate::shell_env::snapshot()
        .map_or_else(internal_env_pairs, |owner| agent_env_pairs_from(&owner))
}

/// [`agent_env_pairs`] for a read that is not the published one: the same
/// application, so a caller can ask what commands *will* get before the read is in
/// place (the environment reader drops the parity verdict for exactly that
/// environment, in the step before it publishes).
#[must_use]
pub(crate) fn agent_env_pairs_from(
    owner: &crate::shell_env::OwnerEnv,
) -> Vec<(OsString, OsString)> {
    let mut pairs = owner.vars().to_vec();
    let mut overrides: Vec<(OsString, OsString)> = Vec::new();
    if let Some(home) = baseline_env_value("HOME") {
        overrides.push((OsString::from("HOME"), OsString::from(home)));
    }
    for (name, value) in crate::temp::shell_temp_vars() {
        overrides.push((OsString::from(name), OsString::from(value)));
    }
    // The product's own values replace the owner's rather than shadowing them, so
    // the list is exactly the environment a command gets: nothing in it that the
    // child will not see, and the parity key — which is compared on this list —
    // moves only when what commands get moves.
    for (name, value) in overrides {
        match pairs.iter().position(|(existing, _)| *existing == name) {
            Some(index) => pairs[index].1 = value,
            None => pairs.push((name, value)),
        }
    }
    pairs
}

/// Apply `pairs` to a child's environment, from nothing: the one definition of
/// a clear-and-fill spawn environment, used by [`program_command`] and by the
/// async builders [`apply_agent_env`] and [`program_command_with`].
fn apply_env_pairs(cmd: &mut std::process::Command, pairs: &[(OsString, OsString)]) {
    cmd.env_clear();
    cmd.envs(pairs.iter().map(|(name, value)| (name, value)));
}

/// Clear the child's environment and re-populate it from [`agent_env_pairs`].
pub(crate) fn apply_agent_env(cmd: &mut tokio::process::Command) {
    apply_env_pairs(cmd.as_std_mut(), &agent_env_pairs());
}

/// The command that starts `program` with `env` as the child's whole environment
/// and `dir` as its working directory. On macOS `program` is named by the absolute
/// path that environment's own search list resolves it to ([`resolve_program_path`]),
/// so that [`std`](std::process::Command) takes its non-forking start: it forks for a
/// bare program name whenever the command sets `PATH` (it must — the search belongs to
/// the child), and a forked child of this process makes macOS print a line about memory
/// tooling to the terminal the daemon was started from, once per command started.
/// `argv[0]` keeps the bare name, so the program sees exactly what
/// `Command::new(program)` would have handed it; environment, directory, streams,
/// process group and exit status stay the caller's. Only `Command::new` can name a
/// program, so the name is chosen here rather than on a command already built.
///
/// `env` is applied here ([`apply_env_pairs`]): the list that names the program and
/// the environment the child gets must be one, so a site that sets the child's
/// directory afterwards passes an absolute list (the product's own internal one is) or
/// nothing. A name carrying a separator is the caller's own program, passed through as
/// it is, and the classes where a resolved path would change what runs keep the bare
/// name ([`resolve_program_path`], [`is_mach_o`]) — those fork exactly as they do
/// today.
///
/// Only macOS resolves anything: elsewhere `program` is named exactly as given, the
/// Windows `cmd.exe` site included, where the platform's own start call does the
/// search with its own extension rules. The command carries `CREATE_NO_WINDOW` on
/// Windows, like every spawn in this tree ([`tree`]).
///
/// The two starts that need a session of their own are deliberately not served here
/// ([`crate::shell_env`], [`crate::gui::shell`]): `std` has no session control, so no
/// naming can spare them the fork — a hand-written start call could, and is not
/// attempted.
#[must_use]
pub(crate) fn program_command(
    program: &str,
    env: &[(OsString, OsString)],
    dir: Option<&Path>,
) -> std::process::Command {
    // macOS only: otherwise every name is left as it was given. `None` is also the
    // answer for the classes the doc lists as left alone.
    #[cfg(target_os = "macos")]
    let resolved = if program.contains('/') {
        None
    } else {
        resolve_program_path(program, env, dir).filter(|path| is_mach_o(path))
    };
    #[cfg(not(target_os = "macos"))]
    let resolved: Option<PathBuf> = None;
    let mut cmd =
        std::process::Command::new(resolved.as_deref().unwrap_or_else(|| Path::new(program)));
    if resolved.is_some() {
        // The resolved path is only the spelling: `argv[0]` stays as it would be.
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;
            cmd.arg0(program);
        }
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
    }
    if let Some(dir) = dir {
        cmd.current_dir(dir);
    }
    apply_env_pairs(&mut cmd, env);
    cmd
}

/// `/usr/bin:/bin` — Darwin's `_PATH_DEFPATH`, the list `execvp` falls back to when
/// the child's environment carries no `PATH`.
#[cfg(target_os = "macos")]
const DEFAULT_SEARCH_PATH: &str = "/usr/bin:/bin";

/// The path [`program_command`] names `program` by: the first entry of `env`'s
/// search list ([`DEFAULT_SEARCH_PATH`] when the environment carries none) that
/// holds an executable regular file by that name.
///
/// The rules are `execvp`'s, because the point is to name the program that same
/// call would have started: entries in order, an empty or relative entry resolved
/// against the child's own directory (`None`: the daemon's working directory, which
/// is where a child with no directory of its own looks), an absolute one joined
/// directly, and a directory, or a file the effective user may not execute, skipped
/// with the search going on. The result is absolute, so a leftover relative path
/// ([`std::path::absolute`]) carries no dependence on the daemon's own working
/// directory.
///
/// Two residues, both of them on the way to the start rather than in it. The
/// permission test happens once, here, where `execvp` repeats it in the child and
/// goes on to the next entry when it fails there: a permission that changes between
/// this look and the start makes the start fail where today the search would have
/// continued. And the look is a few `stat`s and one `access` on the caller's own
/// thread, where `execvp` did that work in the forked child.
#[cfg(target_os = "macos")]
fn resolve_program_path(
    program: &str,
    env: &[(OsString, OsString)],
    base_dir: Option<&Path>,
) -> Option<PathBuf> {
    let search = env.iter().find(|(name, _)| name == "PATH").map_or_else(
        || OsString::from(DEFAULT_SEARCH_PATH),
        |(_, value)| value.clone(),
    );
    // Resolved only if a relative or empty entry needs it: an absolute entry — every
    // entry of the product's own list — never asks. A directory that cannot be read
    // leaves the candidate relative, and the absolute step below then gives up and
    // leaves the bare name, as before.
    let mut search_dir: Option<PathBuf> = base_dir.map(Path::to_path_buf);
    std::env::split_paths(&search)
        .map(|entry| {
            if entry.is_absolute() {
                entry.join(program)
            } else {
                search_dir
                    .get_or_insert_with(|| std::env::current_dir().unwrap_or_default())
                    .join(&entry)
                    .join(program)
            }
        })
        .find(|candidate| is_executable_file(candidate))
        .and_then(|candidate| std::path::absolute(candidate).ok())
}

/// Whether `path` is a regular file the effective user may execute — `execvp`'s own
/// test, `access(X_OK)` included: mode bits alone would name a file that is
/// executable for someone else and then fail the start, where the search should
/// have continued.
#[cfg(target_os = "macos")]
fn is_executable_file(path: &Path) -> bool {
    use std::os::unix::ffi::OsStrExt;
    if !path.is_file() {
        return false;
    }
    let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
        return false;
    };
    // SAFETY: `c_path` is a valid NUL-terminated path and `access` only reads it.
    unsafe { libc::access(c_path.as_ptr(), libc::X_OK) == 0 }
}

/// Whether `path` begins with a Mach-O header: thin (`MH_MAGIC`/`MH_MAGIC_64`) or
/// universal (`FAT_MAGIC`/`FAT_MAGIC_64`), each in both byte orders — the images the
/// kernel starts directly, which is the whole of what the naming rule acts on.
/// (`CAFEBABE` also heads a Java class file, which would then be handed to the
/// platform's own validation rather than re-run under `/bin/sh`; accepted, like every
/// other head here.)
///
/// Anything else with an execute bit keeps the bare name and forks, the conservative
/// direction twice over. A text file with no interpreter line is what `execvp` re-runs
/// under `/bin/sh`; and a script *with* one is reached by the kernel through its
/// interpreter under rules this deliberately does not model — an interpreter that does
/// not exist, a relative one, a line longer than the kernel reads — so naming the
/// script here would turn a search that today moves on to the next entry into a start
/// that fails. Any read error (a file shorter than the four bytes read here included)
/// answers `false` for the same reason.
///
/// That is also where the line this exists to stop still comes back: a program that is
/// a script — a version manager's shim standing in for `git`, say — is started the
/// forking way and prints it. Behaviour is unchanged there; the programs the product
/// names itself (`sh`, `git`, the search tools its battery asks about) are Mach-O
/// images on this platform, so what the product starts is covered.
#[cfg(target_os = "macos")]
fn is_mach_o(path: &Path) -> bool {
    use std::io::Read;
    let Ok(mut file) = std::fs::File::open(path) else {
        return false;
    };
    let mut head = [0u8; 4];
    if file.read_exact(&mut head).is_err() {
        return false;
    }
    matches!(
        &head,
        b"\xCF\xFA\xED\xFE"
            | b"\xFE\xED\xFA\xCF"
            | b"\xCE\xFA\xED\xFE"
            | b"\xFE\xED\xFA\xCE"
            | b"\xCA\xFE\xBA\xBE"
            | b"\xBE\xBA\xFE\xCA"
            | b"\xCA\xFE\xBA\xBF"
            | b"\xBF\xBA\xFE\xCA"
    )
}

/// Build a [`tokio::process::Command`] for executing a shell command in the
/// workspace root.
///
/// The environment is [`agent_env_pairs`]: once the owner's environment has been
/// read, the command runs in exactly that — secrets and all, by design, since
/// these are the owner's own commands. Until the first read succeeds, and
/// whenever one cannot be obtained, the reduced [`internal_env_pairs`] is used
/// instead. The data-location home and the private temp root always win (see
/// [`agent_env_pairs`]).
///
/// On Unix the child is made a process group leader (via
/// [`process_group(0)`](tokio::process::Command::process_group)), so that the
/// timeout handler in [`run_command_with_timeout`] can kill the entire
/// subprocess tree (child + grandchildren) with a single PGID signal.
/// Grandchildren (e.g., `cargo test` or long-running `sleep`) inherit the new
/// PGID from `sh`, preventing orphaned CPU-consuming process trees when a
/// shell command times out.
///
/// The interpreter is still the one the child's own search list resolves to —
/// the product's own baseline until a read succeeds, the owner's own afterwards —
/// but [`program_command`] names it by the path that search finds rather than by
/// the bare `sh`, so macOS takes its non-forking start. That resolution is a real
/// consequence of running the owner's environment, not a fault to repair: on a
/// machine whose own search path holds no `sh`, or whose `sh` is a wrapper of its
/// own, commands start that program or fail to start at all, exactly as they would
/// for the owner. Nothing here compensates for the owner's search path, and
/// nothing about which program is started changes. Windows keeps its bare
/// `cmd.exe` name (see [`program_command`]), and hands it the settings every
/// command of this shell runs under ([`WINDOWS_COMMAND_SWITCHES`]) rather than
/// whichever ones that machine's registry happens to carry.
///
/// On Windows the child is what the runner puts under a job object right after
/// the spawn — the platform's own whole-tree mechanism ([`tree`]).
fn build_shell_command(command: &str, workspace_root: &Path) -> tokio::process::Command {
    // The interpreter is named under the very environment the child is handed, so
    // the pairs are the ones [`program_command`] applies.
    let env = agent_env_pairs();

    // The spawn side of [`SHELL_PLATFORM`]; the two must not drift.
    #[cfg(not(target_os = "windows"))]
    let process = {
        let mut p: tokio::process::Command =
            program_command("sh", &env, Some(workspace_root)).into();
        p.arg("-c").arg(command);
        // Make this child a process group leader so grandchildren inherit the
        // PGID and can be killed together on timeout (see run_command_with_timeout).
        #[cfg(unix)]
        {
            p.process_group(0);
        }
        p
    };

    #[cfg(target_os = "windows")]
    let process = {
        let mut p: tokio::process::Command =
            program_command(WINDOWS_COMMAND_INTERPRETER, &env, Some(workspace_root)).into();
        // `raw_arg`, not `arg`: std's argument escaping belongs to the
        // `CommandLineToArgvW` convention `cmd.exe` does not follow (see
        // `Command::raw_arg`'s own doc). It would re-escape the command's quotes
        // to `\"`, which cmd.exe keeps literally — it has no backslash escape —
        // so a command whose first word is a quoted path (every engine rewrite
        // is, and an install under `C:\Program Files\…` needs it) would name a
        // program cmd.exe cannot resolve.
        //
        // The command goes inside the extra quote pair cmd.exe documents for
        // this hand-off (`cmd /?`, "the remainder of the command line after the
        // switch"): its quote processing strips that pair, so the command
        // arrives verbatim — whatever quotes it carries of its own. The
        // settings the interpreter is started with lead the switch, so the text
        // arrives under them and not under this machine's registry
        // ([`WINDOWS_COMMAND_SWITCHES`]).
        // What arrives is the platform's reading of the agent's command
        // ([`windows_line`]): every plain break is already respelled as `&`, and a
        // line this reader would swallow at such a break — a comment or a label, a
        // statement whose own text runs to the line's end — is refused whole, so the
        // lines after the first are never lost silently. Only the shapes cmd.exe
        // itself continues across — a caret's break, a break inside a group it opened
        // — still carry a line break here, and they are the platform's own reading,
        // not a raw text.
        p.raw_arg(format!("{WINDOWS_COMMAND_SWITCHES} /C \"{command}\""));
        p
    };

    process
}

/// The shared setup of a direct program run: argv, the working directory, the
/// child leading its own process group (Unix) or running under the runner's job
/// (Windows), and `apply_env` as the last word on the child's environment — the
/// clear-and-fill spawn environment belongs to whoever the run is for. Nothing
/// here resolves a name: `program` is already an absolute path by the time it
/// arrives (the managed bun runtime, this service's own image).
///
/// `cwd` is the caller's choice, not necessarily a workspace: the program paths
/// take a workspace root, while the document kit runs inside its own materialized
/// directory so bun cannot load a config from a workspace (see
/// [`crate::docgen`]).
fn program_command_with(
    program: &Path,
    args: &[String],
    cwd: &Path,
    apply_env: impl FnOnce(&mut tokio::process::Command),
) -> tokio::process::Command {
    let mut process = tokio::process::Command::new(program);
    process.args(args);
    #[cfg(unix)]
    {
        process.process_group(0);
    }
    #[cfg(target_os = "windows")]
    process.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
    process.current_dir(cwd);
    apply_env(&mut process);
    process
}

/// Build a [`tokio::process::Command`] that runs `program` with `args` as
/// argv — no shell in between, so no argument can ever be reinterpreted as
/// shell syntax (unlike [`build_shell_command`], whose string is parsed by
/// `sh -c`). Containment is otherwise identical: `cwd` as the working
/// directory, the OWNER's environment — his own once a read has succeeded (the
/// reduced fallback until then, see [`agent_env_pairs`]) — and (Unix) the child
/// leading its own process group; on Windows the runner's job is the platform's
/// side of that containment ([`tree`]).
///
/// These are the owner's own commands doing his own work — an alarm's program, a
/// custom tool, a plan step — so his environment is handed over whole. The
/// product's own work goes through [`build_internal_program_command`] instead.
fn build_program_command(program: &Path, args: &[String], cwd: &Path) -> tokio::process::Command {
    program_command_with(program, args, cwd, apply_agent_env)
}

/// [`build_program_command`] for the product's OWN work — the document kit: the
/// reduced [`internal_env_pairs`] environment, which holds none of the owner's
/// secrets. The separate entry point means no caller has to name an environment,
/// so a product run can never inherit the owner's by mistake.
fn build_internal_program_command(
    program: &Path,
    args: &[String],
    cwd: &Path,
) -> tokio::process::Command {
    program_command_with(program, args, cwd, |process| {
        apply_env_pairs(process.as_std_mut(), &internal_env_pairs());
    })
}

/// Outcome of a timed shell subprocess run.
#[derive(Debug)]
enum ShellRunResult {
    Completed {
        stdout: Vec<u8>,
        stderr: Vec<u8>,
        status: std::process::ExitStatus,
        elapsed: Duration,
    },
    /// The main process exited, and its OWN exit status and the output collected
    /// up to the drain bound are the run's result; a process it left behind still
    /// holds a capture pipe open, so EOF never arrived. Only
    /// [`LeftoverPolicy::Keep`] produces it (an agent's command, the rewritten-line
    /// plan run): the leftover was started deliberately and is left RUNNING — the
    /// capture readers are detached so the channel stays open — and `scope` names the
    /// containment the leftover is reached through, which differs per platform. On
    /// unix it is the child's process group id, and the group still
    /// exists while any member lives, so the note can offer `kill -TERM -<pgid>`. On
    /// Windows it is the pid of the run's root process, which `child.wait()` has
    /// already reaped by the time this path is reached — so the note lists the tree
    /// by parent (`tasklist /FI "PPID eq <pid>"`) and stops each listed process
    /// instead of addressing the released pid. `None` when it could not be
    /// identified.
    ExitedWithLeftovers {
        stdout: Vec<u8>,
        stderr: Vec<u8>,
        status: std::process::ExitStatus,
        scope: Option<u32>,
        elapsed: Duration,
    },
    /// The main process exited but a process it left behind held a capture pipe open
    /// past the drain bound, so the run's tree was ended ([`LeftoverPolicy::End`] —
    /// the program paths, [`run_program_outcome`] and [`run_program_with_timeout`]).
    /// The partial output the readers had collected is carried for the failure prose,
    /// but no exit status: a run this product ended for a leftover is not described
    /// by the status of the process that happened to exit first.
    EndedWithLeftovers {
        stdout: Vec<u8>,
        stderr: Vec<u8>,
        elapsed: Duration,
    },
    TimedOut {
        stdout: Vec<u8>,
        stderr: Vec<u8>,
        pid: Option<u32>,
        elapsed: Duration,
    },
    /// The run's whole process tree grew past the memory ceiling and was
    /// ended like a timeout — `used` is the sample that tripped the watchdog
    /// and `limit` the ceiling it crossed. A variant of its own rather than a
    /// `TimedOut` with a reason: a run ended for memory must be impossible to
    /// mistake for one that ran out of time.
    MemoryExceeded {
        stdout: Vec<u8>,
        stderr: Vec<u8>,
        pid: Option<u32>,
        elapsed: Duration,
        used: u64,
        limit: u64,
    },
    SpawnFailed(std::io::Error),
}

/// What a run does when its main process exited but a leftover process still holds
/// a capture pipe past the drain bound — one policy per run, so the two behaviours
/// cannot drift apart.
///
/// `Keep` is the agent-facing behaviour (the shell tool's commands in both modes,
/// and the rewritten-line plan runner): the command's own exit status and output are
/// the result, and the leftover is left running because it was started on purpose
/// ([`ShellRunResult::ExitedWithLeftovers`]). `End` is the program paths' behaviour
/// (`run_program_outcome` — a user's alarm — and the `run_program_with_timeout` /
/// `run_internal_program_with_timeout` pair — a custom tool's script, the document
/// kit): the run's tree is ended and the run is reported as a failure
/// ([`ShellRunResult::EndedWithLeftovers`]).
#[derive(Clone, Copy)]
pub(super) enum LeftoverPolicy {
    /// Keep the leftover: the run's own status is the answer.
    Keep,
    /// End the tree holding a leftover and report a failure.
    End,
}

/// How the wait inside [`run_command_with_timeout`] ended — the three bounds
/// it watches at once.
enum WaitOutcome {
    /// The child exited (or the wait itself failed): the result is handed on
    /// exactly as `child.wait()` produced it.
    Exited(std::io::Result<std::process::ExitStatus>),
    /// The timeout expired — a stop.
    TimedOut,
    /// A memory sample crossed the ceiling — a stop, carrying the sample and
    /// the ceiling so the failure can report both.
    MemoryExceeded { used: u64, limit: u64 },
}

/// One memory sample that crossed the ceiling: what it measured and the ceiling.
struct MemorySample {
    used: u64,
    limit: u64,
}

/// The bounds every runner watches over the command tree it spawned: one
/// deadline, one memory cadence, and the warn-once flag for a watchdog that
/// cannot measure. Shared by [`run_command_with_timeout`] and the plan runner
/// ([`plan::run`]) so the two cannot drift on the bounds they enforce.
struct Watchdog {
    deadline: std::pin::Pin<Box<tokio::time::Sleep>>,
    sample: tokio::time::Interval,
    measure_failed: bool,
}

impl Watchdog {
    /// `timeout` is the run's whole-run deadline; the memory cadence is
    /// [`MEMORY_SAMPLE_INTERVAL`] for every run.
    pub(in crate::tools::shell) fn new(timeout: Duration) -> Self {
        let mut sample = tokio::time::interval(MEMORY_SAMPLE_INTERVAL);
        sample.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        Self {
            deadline: Box::pin(tokio::time::sleep(timeout)),
            sample,
            measure_failed: false,
        }
    }

    /// Sample the trees of the run's live members (`pids`, empty for a reaped
    /// one) and report the first total over `limit`.
    ///
    /// A run with no live pid has nothing to sample: that is not a failure to
    /// measure, so it is silent. Fail open, loudly once: a watchdog that killed
    /// a command it could not measure would be worse than the unbounded command
    /// it exists to stop. A pid that does not answer is left out of the sum
    /// rather than failing the whole sample — the run's next cadence reads it
    /// again if it is still there — so the warning stands for a tree nothing
    /// could be read from at all. It names the first pid, one process: the
    /// field's shape for the single-child run as well.
    pub(in crate::tools::shell) fn measure(
        &mut self,
        pids: &[u32],
        limit: u64,
    ) -> Option<MemorySample> {
        if pids.is_empty() {
            return None;
        }
        let mut used = 0_u64;
        let mut measured = false;
        for pid in pids {
            if let Some(rss) = mem::tree_rss(*pid) {
                measured = true;
                used = used.saturating_add(rss);
            }
        }
        if !measured {
            if !self.measure_failed {
                self.measure_failed = true;
                tracing::warn!(
                    pid = pids[0],
                    "memory watchdog cannot measure the command's tree; the run continues \
                     without a memory bound"
                );
            }
            return None;
        }
        (used > limit).then_some(MemorySample { used, limit })
    }
}

/// The three standard streams of a run: what a member's redirect spelling names,
/// and what [`AppliedRedirects::streams`] reports back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stream {
    Stdin,
    Stdout,
    Stderr,
}

/// How many bytes one stream of a run's capture may keep.
///
/// Every runner gives each stream a budget of its own — the cap each pipe was
/// always read up to ([`SHELL_PIPE_READ_CAP`]): the single-child runner one per
/// pipe it reads, a plan one per *stream*, shared by every member that writes it
/// ([`plan`]), because a plan's stdout is one stream where the shell's was one pipe
/// and a member's stderr one channel however many members filled it. A member that
/// floods stdout therefore cannot truncate a later member's stderr, and per-member
/// budgets would keep more than the shell ever did — the unsafe direction.
///
/// The budget is drawn on by the readers of its stream, which run concurrently, so
/// the split between two of them is decided by which reads first; what is guaranteed
/// is the total (the cap), which is the truncation-safety property
/// [`SHELL_PIPE_READ_CAP`] documents.
#[derive(Clone)]
struct CaptureBudget(std::sync::Arc<std::sync::atomic::AtomicUsize>);

impl CaptureBudget {
    fn new(cap: usize) -> Self {
        Self(std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(
            cap,
        )))
    }

    /// Charge `bytes` kept bytes against the budget, returning how many the
    /// reader may keep: a reader that finds the budget spent keeps nothing, and
    /// keeps reading (a full pipe must never stall the member it belongs to —
    /// the cap is a capture bound, never back-pressure).
    fn claim(&self, bytes: usize) -> usize {
        use std::sync::atomic::Ordering;

        let mut remaining = self.0.load(Ordering::Relaxed);
        loop {
            let take = bytes.min(remaining);
            if take == 0 {
                return 0;
            }
            match self.0.compare_exchange_weak(
                remaining,
                remaining - take,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => return take,
                Err(actual) => remaining = actual,
            }
        }
    }
}

/// Read from an async stream up to what `budget` still allows, appending what is
/// kept to `buf` — the stream's shared live buffer — and continuing to read and
/// discard any remaining data to drain the pipe (preventing back-pressure on the
/// child process from a full pipe buffer).
///
/// `buf` is what lets a run take a snapshot of a still-reading stream without
/// cancelling its reader ([`Readers::snapshot_and_detach`]): the reader appends as
/// it reads, under the lock, so whatever has arrived is visible at any moment. The
/// budget is the same one that caps a finished reader's output, so the buffer can
/// never grow past [`SHELL_PIPE_READ_CAP`] however long a leftover keeps writing.
///
/// Returns when `cancel` is signalled or the stream reaches EOF. The timeout path
/// still collects partial output even when grandchild processes inherited the pipe
/// write end and prevent EOF.
async fn read_stream_limited(
    reader: &mut (impl tokio::io::AsyncRead + Unpin),
    budget: &CaptureBudget,
    cancel: tokio_util::sync::CancellationToken,
    buf: &std::sync::Mutex<Vec<u8>>,
) {
    use tokio::io::AsyncReadExt;

    let mut chunk = [0u8; 8192];
    loop {
        tokio::select! {
            biased;
            result = reader.read(&mut chunk) => {
                match result {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        // Whatever the budget still allows is kept; the rest is
                        // read and discarded, so a spent budget never stops the
                        // member from writing (the drain half of the original
                        // per-pipe cap).
                        let keep = budget.claim(n);
                        if keep > 0 {
                            buf.lock().unwrap_poison().extend_from_slice(&chunk[..keep]);
                        }
                    }
                }
            }
            () = cancel.cancelled() => break,
        }
    }
}

/// Spawn a background task that reads from a pipe into `buf`.
/// The task stops early when `cancel` is signalled; otherwise it runs to EOF.
/// Its handles are detached rather than awaited on the leftover path, so it must
/// never be the thing that decides a run (see [`Readers`]).
fn spawn_pipe_reader(
    pipe: impl tokio::io::AsyncRead + Unpin + Send + 'static,
    budget: CaptureBudget,
    cancel: tokio_util::sync::CancellationToken,
    buf: std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut pipe = pipe;
        read_stream_limited(&mut pipe, &budget, cancel, &buf).await;
    })
}

/// One capture reader of a run: the live buffer it fills, and the reading task or
/// its end once it finished. A completed [`tokio::task::JoinHandle`] must never be
/// awaited again (tokio panics on a re-poll), so its state is recorded in its place.
///
/// The bytes live in [`Reader::buf`], not in the task's return value: the task
/// appends as it reads, which is what lets the leftover path take what has arrived
/// without cancelling the reader ([`Readers::snapshot_and_detach`]).
struct Reader {
    stream: Captured,
    /// The live buffer this reader fills, bounded by the reader's
    /// [`CaptureBudget`]: the reader appends under the lock as it reads, and the
    /// collector takes (and so drains) it, so a leftover that keeps writing can
    /// never grow it past the cap.
    buf: std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
    task: ReaderTask,
}

/// The two streams a run captures. A reader exists for each of a run's output
/// streams and for nothing else: a member's stdin is never a capture pipe, so the
/// plumbing cannot name it, and what each reader fills is decided by this — the
/// label a stalled reader warns with included.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Captured {
    Stdout,
    Stderr,
}

impl Captured {
    fn label(self) -> &'static str {
        match self {
            Captured::Stdout => "stdout",
            Captured::Stderr => "stderr",
        }
    }
}

enum ReaderTask {
    Reading(tokio::task::JoinHandle<()>),
    Done,
}

/// The capture readers of one run, in the order their bytes belong in the run's
/// output.
///
/// One home for the three things every run shape does with them: drain them under
/// the output bound ([`Readers::drain`]), collect what they hold after a cancel
/// ([`Readers::collect`]), and take what has arrived without cancelling them when a
/// leftover keeps a pipe open ([`Readers::snapshot_and_detach`]). The single-child
/// runner has one reader per stream; the plan runner one per captured member
/// stream ([`plan`]), all those of one stream charged to that stream's budget.
#[derive(Default)]
struct Readers {
    readers: Vec<Reader>,
}

impl Readers {
    /// Start a reader for one captured output stream of one member.
    fn push(
        &mut self,
        stream: Captured,
        pipe: impl tokio::io::AsyncRead + Unpin + Send + 'static,
        budget: CaptureBudget,
        cancel: tokio_util::sync::CancellationToken,
    ) {
        let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        self.readers.push(Reader {
            stream,
            buf: std::sync::Arc::clone(&buf),
            task: ReaderTask::Reading(spawn_pipe_reader(pipe, budget, cancel, buf)),
        });
    }

    /// Drain every reader within `drain_limit`, taking the bytes of each that
    /// finishes in time. `true` when they all did — the run's output is complete;
    /// `false` when the bound expired with a reader still pending, which means a
    /// leftover process still holds a capture pipe open. What the caller does next
    /// is its [`LeftoverPolicy`]'s: `Keep` snapshots and detaches
    /// ([`Readers::snapshot_and_detach`]), `End` cancels and collects
    /// ([`Readers::collect`]).
    async fn drain(&mut self, drain_limit: Duration) -> bool {
        let limit = tokio::time::sleep(drain_limit);
        tokio::pin!(limit);
        loop {
            if self
                .readers
                .iter()
                .all(|reader| matches!(reader.task, ReaderTask::Done))
            {
                return true;
            }
            // One poll of the reading handles per round: `pending` borrows them,
            // so the round's outcome is stored only after it is dropped.
            let finished = {
                let mut pending = FuturesUnordered::new();
                for (index, reader) in self.readers.iter_mut().enumerate() {
                    if let ReaderTask::Reading(handle) = &mut reader.task {
                        pending.push(async move { (index, handle.await) });
                    }
                }
                tokio::select! {
                    biased;
                    next = pending.next() => next,
                    () = &mut limit => None,
                }
            };
            let Some((index, result)) = finished else {
                return false;
            };
            self.readers[index].store(result);
        }
    }

    /// The run's output: every reader's bytes, in the order the readers were
    /// created. A reader that has not finished is given the cancellation grace
    /// ([`DRAIN_CANCEL_GRACE`]): the run's processes are gone by the time this is
    /// called, so the bound is for whatever leftover holder still has a pipe.
    async fn collect(&mut self) -> (Vec<u8>, Vec<u8>) {
        futures_util::future::join_all(self.readers.iter_mut().map(Reader::finish)).await;
        self.take()
    }

    /// Take what the readers hold right now, leaving any still-running reader
    /// detached: the bytes are the live buffers' contents, no await and no cancel.
    /// A pending reading task is handed to [`crate::util::leftover_channels`]
    /// rather than dropped, so it keeps draining its pipe to EOF, and the leftover
    /// holding it is neither blocked by a full pipe nor killed by a closed read end
    /// (on unix a closed read end turns its next write into SIGPIPE/EPIPE). Past
    /// that set's shared cap of 16 channels the OLDEST is released, and its leftover
    /// faults on its next write.
    ///
    /// This is the leftover path's collection: what the command wrote before the
    /// bound is the run's result, and the leftover keeps its channel
    /// ([`LeftoverPolicy::Keep`]).
    fn snapshot_and_detach(&mut self) -> (Vec<u8>, Vec<u8>) {
        // A completed handle is already `Done`; a pending one is retained (not
        // dropped) so its task keeps draining within the shared bound.
        for reader in &mut self.readers {
            if let ReaderTask::Reading(handle) =
                std::mem::replace(&mut reader.task, ReaderTask::Done)
            {
                crate::util::leftover_channels::retain_channel(handle);
            }
        }
        self.take()
    }

    /// Every reader's kept bytes, in the order the readers were created,
    /// separated by stream. Each buffer is emptied by the take, and a detached
    /// reader that keeps reading grows nothing further once its (shared, already
    /// charged) budget is spent — the bound is the reader's, not this call's.
    fn take(&mut self) -> (Vec<u8>, Vec<u8>) {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        for reader in &mut self.readers {
            let bytes = std::mem::take(&mut *reader.buf.lock().unwrap_poison());
            match reader.stream {
                Captured::Stdout => stdout.extend_from_slice(&bytes),
                Captured::Stderr => stderr.extend_from_slice(&bytes),
            }
        }
        (stdout, stderr)
    }
}

impl Reader {
    /// Fold a finished task's outcome in: the reader is done, and whatever it kept
    /// is in its live buffer.
    fn store(&mut self, result: std::result::Result<(), tokio::task::JoinError>) {
        if let Err(e) = result {
            tracing::warn!(%e, "{} reader task panicked", self.stream.label());
        }
        self.task = ReaderTask::Done;
    }

    /// Wait for whatever the reader still holds — immediately when it already
    /// finished, else the cancellation grace for one whose pipe a leftover process
    /// still keeps open.
    async fn finish(&mut self) {
        match std::mem::replace(&mut self.task, ReaderTask::Done) {
            ReaderTask::Done => {}
            ReaderTask::Reading(handle) => {
                await_pipe_reader_with_cancellation_timeout(
                    handle,
                    self.stream.label(),
                    DRAIN_CANCEL_GRACE,
                )
                .await;
            }
        }
    }
}

/// Await a pipe reader task with a grace timeout, used after killing a child
/// process — the reader is given `cancellation_timeout` to notice cancellation and
/// stop. A reader that misses the grace is handed to
/// [`crate::util::leftover_channels`] instead of being dropped: it keeps draining
/// its pipe to EOF, so nothing it belongs to stalls on a full pipe — until the
/// shared cap of 16 channels is reached, past which the OLDEST is released and its
/// leftover faults on its next write.
async fn await_pipe_reader_with_cancellation_timeout(
    mut handle: tokio::task::JoinHandle<()>,
    label: &str,
    cancellation_timeout: Duration,
) {
    if tokio::time::timeout(cancellation_timeout, &mut handle)
        .await
        .is_err()
    {
        tracing::warn!(
            "{label} reader did not respond to cancellation within {cancellation_timeout:?} — \
             it stays detached and keeps draining its pipe"
        );
        crate::util::leftover_channels::retain_channel(handle);
    }
}

/// Output-drain bound for [`run_command_with_timeout`]: after the main command
/// exits, remaining output must drain within this bound. Overridable via env
/// for tuning; tests pass explicit durations.
fn output_drain_timeout() -> Duration {
    crate::util::env_duration_secs(
        "MAHBOT_SHELL_DRAIN_TIMEOUT_SECS",
        DEFAULT_OUTPUT_DRAIN_TIMEOUT_SECS,
    )
}

/// Signal the process group of a spawned shell (PGID == the child PID after
/// `process_group(0)` in [`build_shell_command`]). Used to terminate the whole
/// subprocess tree when a stop ends a run — the command timeout or memory
/// ceiling, or the drain bound under [`LeftoverPolicy::End`], where a leftover
/// backgrounded process keeps the output pipes open after the main process
/// exited — so orphaned strays cannot accumulate.
///
/// Also used by [`self::bg`] for the two-stage background-session stop
/// (SIGTERM then SIGKILL) and the teardown kill; there the target is the
/// background watcher's PID (the group leader), which stays alive for the
/// whole session, so the group always exists when the signal is sent. The unix
/// arm of [`tree`]'s containment is this same call.
///
/// Note on ordering: the timeout path deliberately kills before reaping the
/// child (see [`run_command_with_timeout`]) to avoid a PID-reuse race; the
/// drain path kills after `child.wait()` already reaped it, so the PID could
/// in theory be recycled as a new group leader within the drain window —
/// accepted risk, the kill is best-effort.
#[cfg(unix)]
fn kill_process_group(pid: u32, signal: libc::c_int) {
    let pid_signed: libc::pid_t = pid.try_into().expect("PID fits in pid_t");
    // SAFETY: kill(-pgid, sig) is the standard POSIX way to signal an entire
    // process group. The target PGID is our own child's PID (also its
    // PGID after process_group(0)), so we own every process in the group.
    let ret = unsafe { libc::kill(-pid_signed, signal) };
    if ret != 0 {
        let err = std::io::Error::last_os_error();
        tracing::warn!(
            pid = pid,
            signal,
            err = %err,
            "kill(-pgid) failed — leftover processes may survive"
        );
    }
}

/// The lifecycle point of the grep engine's scratch spec files: Windows serves a
/// member's spec through a file (cmd.exe cannot carry the payload on its command
/// line), and every exit path from the serve decision — including the validation
/// `bail!`s and a cancellation drop — must clean it up. The removal itself, and
/// its best-effort policy, are the engine's ([`grep_engine::discard_spec_files`],
/// which the engine also calls inline when a hand-off abandons a rewrite); this
/// guard owns only the point. A killed daemon still leaves a file behind; the
/// temp cleaner is the backstop.
struct SpecFiles(Vec<PathBuf>);

impl Drop for SpecFiles {
    fn drop(&mut self) {
        grep_engine::discard_spec_files(&self.0);
    }
}

/// The refusal this shell call must fail with, if any: the serve decision's own
/// refusal ([`grep_engine::GrepServe::refusal`] — a Windows-only value), or a
/// produced-but-unapplied rewrite, i.e. one the read-only guard rejected.
/// Returns the short cause; the agent-facing message is rendered from it by
/// [`grep_engine::unserved_failure`] at the bail site, the way the engine's own
/// cause is.
///
/// `applied` is whether the rewrite reached the shell (`exec_str !=` the
/// platform's own reading of the line, [`windows_line::executable`] — the text
/// the shell would run had the engine not rewritten it). The platform is tested
/// first: on unix neither case refuses — the original command runs and its `grep`
/// is the real one — while on Windows an unserved search must not come back
/// looking like an empty result (see [`grep_engine::unserved_failure`]).
fn unserved_refusal(
    platform: ShellPlatform,
    grep_serve: &grep_engine::GrepServe,
    applied: bool,
) -> Option<String> {
    if platform != ShellPlatform::Windows {
        return None;
    }
    grep_serve.refusal.clone().or_else(|| {
        (!applied && grep_serve.rewritten.is_some()).then(|| GUARD_REJECTED_REASON.to_string())
    })
}

/// The grep telemetry cause for a rewrite that was produced but never applied
/// (the read-only guard rejected it), spelled once so the refusal's cause and
/// the stored row's reason cannot drift apart.
const GUARD_REJECTED_REASON: &str = "read-only guard rejected rewrite";

/// What a completed run's engine failure means to this platform.
enum EngineFailure {
    /// The engine could not serve and reported no account to render: the
    /// original command is re-run, so the agent gets the authentic answer (the
    /// platform with a real `grep` to re-run).
    ReRun,
    /// The engine's own short account of the failure (the platform that refuses
    /// the call instead of re-running it).
    Refused(String),
}

/// Classify a completed run: `Some` when it is the engine failing to serve —
/// the sentinel exit code, the stale-binary lock message, or, on the platform
/// that refuses rather than re-runs, the engine's refusal marker on a line of
/// its own, which survives a pipeline tail masking the exit status. `None` when
/// the run is not an engine failure.
///
/// The marker is recognised by line equality, never as a substring: a served
/// run's stderr may echo the token inside a matched line, and a result is not a
/// refusal. Only the refusing platform carries a cause; on the other one the
/// marker is not even scanned and [`EngineFailure::ReRun`] says all that
/// platform's caller needs.
fn engine_failure(
    status_code: Option<i32>,
    stderr: &[u8],
    platform: ShellPlatform,
) -> Option<EngineFailure> {
    // The engine child is a program this product started, and on one path it
    // re-execs the platform's real `grep` in place, whose own stderr reaches this
    // same stream — so it is read the way a program's output is read here, not as
    // UTF-8 ([`windows_text::decode`]). The markers matched below are this
    // product's own ASCII lines, which every code page agrees on.
    let text = windows_text::decode(stderr);
    let marked = platform == ShellPlatform::Windows
        && text
            .lines()
            .any(|line| line.trim() == grep_engine::ENGINE_REFUSAL_MARKER);
    if status_code != Some(grep_engine::ENGINE_FAILED_EXIT)
        && !text.contains(grep_engine::STALE_BINARY_LOCK_MSG)
        && !marked
    {
        return None;
    }
    if platform != ShellPlatform::Windows {
        return Some(EngineFailure::ReRun);
    }
    Some(EngineFailure::Refused(engine_cause(&text, marked)))
}

/// The engine's own short account of a failure it reported: the detail it wrote
/// after the refusal marker, which it emits first — so this is the engine's own
/// line and never a served member's stderr earlier in the stream — else the line
/// carrying the stale-binary lock message
/// ([`grep_engine::STALE_BINARY_LOCK_MSG`]), else the run's first non-blank line,
/// else a generic cause for a failure that carried none. Trimmed and length-capped;
/// [`grep_engine::unserved_failure`] renders the agent-facing message from it.
///
/// The lock message is looked up by its text rather than taken as the first line,
/// because it is not always the first: a launch that meets the instance lock files
/// its durable record before it prints the lock error, so the failure-record
/// pointer ([`crate::boot::record_launch_failure`]'s) comes first. An own-image
/// member whose command word is outside the hidden subcommands (`mahbot version`)
/// is a launch like any other and prints both to the same stderr this reads.
fn engine_cause(text: &str, marked: bool) -> String {
    // The marked branch is one forward scan; only the two-scan branch below needs
    // the lines materialised.
    let detail = if marked {
        text.lines()
            .map(str::trim)
            .skip_while(|line| *line != grep_engine::ENGINE_REFUSAL_MARKER)
            .nth(1)
    } else {
        let lines: Vec<&str> = text.lines().map(str::trim).collect();
        lines
            .iter()
            .find(|line| line.contains(grep_engine::STALE_BINARY_LOCK_MSG))
            .or_else(|| lines.iter().find(|line| !line.is_empty()))
            .copied()
    };
    detail.map_or_else(
        || "engine could not serve the search".to_string(),
        |line| crate::util::truncate(line, ENGINE_FAILURE_DETAIL_CHARS),
    )
}

/// Ends a run's whole process tree if the run is dropped before a stop path or
/// the successful-completion path has taken responsibility for it — its tool call's
/// future dropped (an abandoned call, runtime teardown), a panic in a sibling tool.
/// The tree is the platform's ([`Tree`]): the child's process group on unix, the job
/// on Windows.
///
/// It must be disarmed on every path where the child is reaped or the tree is
/// handed on: after a unix child is reaped a group kill risks PID reuse, a Windows
/// job retained for the process lifetime must not be ended by this guard, and the
/// leftover-keeping path ([`LeftoverPolicy::Keep`]) has deliberately left the tree
/// alone — the leftover was started on purpose and must survive this guard.
///
/// It holds only the tree, never the child, so it has no fallback when
/// [`Tree::terminate`] reports `false` — a Windows run with no job (fail-open,
/// see [`tree`]) kills nothing here, just as it did before this guard existed.
struct KillOnDrop {
    tree: Tree,
    armed: bool,
}

impl KillOnDrop {
    fn new(tree: Tree) -> Self {
        Self { tree, armed: true }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl Drop for KillOnDrop {
    fn drop(&mut self) {
        if self.armed {
            self.tree.terminate();
        }
    }
}

/// Spawn `cmd`, read stdout/stderr concurrently, and enforce `timeout`.
/// After the main process exits, remaining output must drain within
/// `drain_limit` — a leftover backgrounded process holding the pipes open
/// turns the drain into a bounded leftover result instead of an indefinite
/// hang, resolved by `leftovers`: an agent's command (`Keep`) reports the
/// command's own exit status with the leftover left running
/// ([`ShellRunResult::ExitedWithLeftovers`]), a program run (`End`) ends the
/// tree and is reported as a failure ([`ShellRunResult::EndedWithLeftovers`]).
///
/// While the child runs, its whole process tree is also sampled for resident
/// memory ([`mem`]); a sample over `memory_limit` ends the run the way the
/// timeout does and reports [`ShellRunResult::MemoryExceeded`].
///
/// `owner` decides the run's whole-tree containment ([`tree`]): unix contains
/// every run the same way — the process group the child leads — while Windows
/// gives a job object only to an agent's run. A plan run's members get the same
/// containment through [`plan::run`], which spawns them the same way.
async fn run_command_with_timeout(
    cmd: &mut tokio::process::Command,
    timeout: Duration,
    drain_limit: Duration,
    memory_limit: Option<u64>,
    owner: RunOwner,
    leftovers: LeftoverPolicy,
) -> ShellRunResult {
    let start = std::time::Instant::now();

    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());

    // The run's containment, created before the spawn so the child can be put
    // under it the moment it exists; the window between the two is the accepted
    // limitation `tree` documents.
    let mut tree = Tree::new(owner);

    let mut child = match cmd.spawn() {
        Ok(c) => c,
        Err(e) => return ShellRunResult::SpawnFailed(e),
    };

    let pid = child.id();
    if let Some(pid) = pid {
        tree.attach(pid);
    }
    // Kill-on-drop: an aborted task (drain-cap force-cancel, panic, runtime
    // teardown) must not orphan the run's tree. Disarmed on every path where
    // the child is reaped or the tree is handed on.
    let mut kill_guard = KillOnDrop::new(tree.clone());
    // Stdio::piped() was set above, so the handles are always present.
    let stdout_pipe = child.stdout.take().expect("stdout piped");
    let stderr_pipe = child.stderr.take().expect("stderr piped");

    let cancel = tokio_util::sync::CancellationToken::new();
    // One budget per stream here: each pipe is read up to `SHELL_PIPE_READ_CAP`,
    // the cap it always had — the split a plan run gives its two streams too
    // ([`CaptureBudget`]).
    let mut readers = Readers::default();
    readers.push(
        Captured::Stdout,
        stdout_pipe,
        CaptureBudget::new(SHELL_PIPE_READ_CAP),
        cancel.clone(),
    );
    readers.push(
        Captured::Stderr,
        stderr_pipe,
        CaptureBudget::new(SHELL_PIPE_READ_CAP),
        cancel.clone(),
    );

    match await_run_end(&mut child, timeout, memory_limit, pid).await {
        WaitOutcome::Exited(Ok(status)) => {
            // Child reaped — the guard must not fire: on unix the group leader
            // is gone and a post-reap kill would risk PID reuse, while a Windows
            // job retained for the process lifetime must not be ended here.
            kill_guard.disarm();
            // Child exited naturally — drain remaining output with a bound.
            // A leftover backgrounded process that inherited the pipes prevents
            // EOF; without the bound the drain would hang the tool forever.
            if readers.drain(drain_limit).await {
                // The run ended on its own — not a stop, so nothing is killed
                // here and the job is kept rather than closed (`tree`).
                tree.retain_after_completion();
                let (stdout, stderr) = readers.collect().await;
                ShellRunResult::Completed {
                    stdout,
                    stderr,
                    status,
                    elapsed: start.elapsed(),
                }
            } else {
                match leftovers {
                    // An agent's command: the leftover was started on purpose,
                    // so it is left RUNNING and the command's own exit status and
                    // the output collected up to the bound are the result. The
                    // readers are detached, not cancelled (`snapshot_and_detach`),
                    // so the leftover's write end stays open — a full pipe never
                    // blocks it and a closed read end never turns its next write
                    // into SIGPIPE/EPIPE. Past the shared cap of retained channels
                    // the oldest is released instead, and its leftover faults on
                    // its next write (see [`crate::util::leftover_channels`]). The
                    // containment stays alive too: on
                    // Windows the job's handle must not be closed, because that
                    // would kill the very process this path must leave running
                    // (`Tree::retain_after_completion`).
                    LeftoverPolicy::Keep => {
                        tree.retain_after_completion();
                        let (stdout, stderr) = readers.snapshot_and_detach();
                        ShellRunResult::ExitedWithLeftovers {
                            stdout,
                            stderr,
                            status,
                            scope: pid,
                            elapsed: start.elapsed(),
                        }
                    }
                    // A program run (an alarm, a custom tool): end the tree the
                    // run is contained in — the process group on unix, the job on
                    // Windows — mirroring the timeout path, then cancel the readers
                    // and collect partial output so the caller gets a visible,
                    // recoverable failure instead of a hang. Readers that already
                    // completed keep their output (a completed JoinHandle must not
                    // be re-awaited). The ended run carries no exit status: what the
                    // program paths report is the failure, not the status of the
                    // process that happened to exit first.
                    LeftoverPolicy::End => {
                        tree.terminate();
                        cancel.cancel();
                        let (stdout, stderr) = readers.collect().await;
                        ShellRunResult::EndedWithLeftovers {
                            stdout,
                            stderr,
                            elapsed: start.elapsed(),
                        }
                    }
                }
            }
        }
        WaitOutcome::Exited(Err(e)) => ShellRunResult::SpawnFailed(e),
        WaitOutcome::TimedOut => {
            let (stdout, stderr) =
                stop_and_collect(&mut child, &tree, &mut kill_guard, &cancel, &mut readers).await;
            ShellRunResult::TimedOut {
                stdout,
                stderr,
                pid,
                elapsed: start.elapsed(),
            }
        }
        WaitOutcome::MemoryExceeded { used, limit } => {
            let (stdout, stderr) =
                stop_and_collect(&mut child, &tree, &mut kill_guard, &cancel, &mut readers).await;
            ShellRunResult::MemoryExceeded {
                stdout,
                stderr,
                pid,
                elapsed: start.elapsed(),
                used,
                limit,
            }
        }
    }
}

/// Wait for the run to end on the first of its three bounds — the child
/// exiting, `timeout`, or the resident memory its whole tree has grown to
/// above `memory_limit` — and say which one fired. The memory sample rides
/// the runtime path the wait already occupies: a sample is a handful of
/// syscalls, no thread of its own.
async fn await_run_end(
    child: &mut tokio::process::Child,
    timeout: Duration,
    memory_limit: Option<u64>,
    pid: Option<u32>,
) -> WaitOutcome {
    let wait = child.wait();
    tokio::pin!(wait);
    let mut watchdog = Watchdog::new(timeout);
    loop {
        tokio::select! {
            biased;
            status = &mut wait => return WaitOutcome::Exited(status),
            () = &mut watchdog.deadline => return WaitOutcome::TimedOut,
            _ = watchdog.sample.tick() => {
                if let Some(limit) = memory_limit
                    && let Some(sample) = watchdog.measure(pid.as_slice(), limit)
                {
                    return WaitOutcome::MemoryExceeded {
                        used: sample.used,
                        limit: sample.limit,
                    };
                }
            }
        }
    }
}

/// End a run's tree the way the timeout does and collect the output the pipe
/// readers still hold — the one stop path the timeout and the memory watchdog
/// share, so the watchdog cannot grow a second kill mechanism.
///
/// The direct child is signalled first, then the containment: on unix
/// `start_kill` (fire-and-forget SIGKILL) precedes the group kill, because
/// `child.kill().await` — which includes `wait()` — would let the child's pid
/// be reused before the group it leads could be signalled (`process_group(0)`
/// in [`build_shell_command`]). On Windows the direct kill is the fallback for
/// a run whose containment could not be established (see `tree`) and for a job
/// termination that failed. The plan runner's stop path does the same for each
/// of its members ([`plan::run`]'s `end_group`).
async fn stop_and_collect(
    child: &mut tokio::process::Child,
    tree: &Tree,
    kill_guard: &mut KillOnDrop,
    cancel: &tokio_util::sync::CancellationToken,
    readers: &mut Readers,
) -> (Vec<u8>, Vec<u8>) {
    let _ = child.start_kill();
    tree.terminate();
    let _ = child.wait().await;
    // Reaped — disarm the guard (the explicit kill already ran).
    kill_guard.disarm();
    cancel.cancel();

    // Give readers a grace window to notice cancellation and return their
    // buffers. If a reader takes longer than the grace (e.g. because a grandchild
    // keeps the pipe open), we still get partial data from the buffer it
    // returns after noticing cancellation.
    readers.collect().await
}

/// Outcome of a direct program run (argv — never a shell command string), used
/// by trigger-armed alarms to decide whether a check reported anything.
///
/// `output` is the combined stdout+stderr AFTER ANSI stripping, but WITHOUT
/// credential scrubbing and WITHOUT the shell pipeline's annotations (the
/// exit-status note, timing, spill hints). `has_output` is the wake/no-wake
/// signal and reads the streams themselves: output that is nothing but
/// whitespace or escape sequences is still output.
pub(crate) struct ProgramOutcome {
    /// Whether the program exited with status 0.
    pub success: bool,
    /// How the run ended, e.g. `exit status 2` or `timed out after 600s`.
    pub detail: String,
    /// Combined stdout+stderr, ANSI-stripped, unscrubbed.
    pub output: String,
    /// Whether the program emitted anything at all.
    pub has_output: bool,
}

/// Build the outcome for a run that produced (possibly partial) raw streams.
/// A run with no streams at all (spawn failure) yields empty, no-output.
fn program_outcome(success: bool, detail: String, stdout: &[u8], stderr: &[u8]) -> ProgramOutcome {
    ProgramOutcome {
        success,
        detail,
        output: decode_raw_streams(stdout, stderr),
        // The raw streams decide: only a run that emitted nothing at all
        // reported nothing.
        has_output: !stdout.is_empty() || !stderr.is_empty(),
    }
}

/// Run `program` with `args` (argv — never a shell command string) in `cwd` and
/// return the raw run result, under the OWNER's environment: his own commands
/// doing his own work. The bounds a direct run is held to live in [`run_bounded`].
///
/// A direct run is never an agent's own command, so a leftover it leaves behind is
/// ended rather than kept ([`LeftoverPolicy::End`]): an alarm or a custom tool must
/// not be able to leave a process holding its output open.
async fn run_program(
    cwd: &Path,
    program: &Path,
    args: &[String],
    owner: RunOwner,
) -> ShellRunResult {
    run_bounded(build_program_command(program, args, cwd), owner).await
}

/// Perform one [`run_command_with_timeout`] call with the bounds every direct
/// run is held to: [`DEFAULT_SHELL_TIMEOUT_SECS`], the per-pipe output cap and
/// the post-exit drain bound. `owner` decides the run's containment.
async fn run_bounded(mut cmd: tokio::process::Command, owner: RunOwner) -> ShellRunResult {
    run_command_with_timeout(
        &mut cmd,
        Duration::from_secs(DEFAULT_SHELL_TIMEOUT_SECS),
        output_drain_timeout(),
        mem::default_limit(),
        owner,
        LeftoverPolicy::End,
    )
    .await
}

/// Run `program` with `args` in `cwd` and report the run as an outcome instead
/// of folding a non-zero exit into an error: a run that did not complete is a
/// failed outcome, never an `Err`, because the caller's rule is about what the
/// run reported rather than about this layer's error type.
///
/// The run is a service launch rather than an agent's work, so Windows gives it
/// no job ([`RunOwner::Service`] — see [`tree`]).
pub(crate) async fn run_program_outcome(
    cwd: &Path,
    program: &Path,
    args: &[String],
) -> ProgramOutcome {
    match run_program(cwd, program, args, RunOwner::Service).await {
        ShellRunResult::Completed {
            stdout,
            stderr,
            status,
            ..
        } => {
            let code = status.code();
            program_outcome(
                code == Some(0),
                match code {
                    Some(n) => format!("exit status {n}"),
                    None => "terminated by signal".to_string(),
                },
                &stdout,
                &stderr,
            )
        }
        ShellRunResult::TimedOut { stdout, stderr, .. } => program_outcome(
            false,
            format!("timed out after {DEFAULT_SHELL_TIMEOUT_SECS}s"),
            &stdout,
            &stderr,
        ),
        // `ExitedWithLeftovers` cannot come out of `run_program` — a direct run
        // is always ENDED, never kept ([`LeftoverPolicy::End`]) — but both
        // outcomes say the same thing here: the run's own exit was observed
        // while a process it left behind held its output pipes.
        ShellRunResult::ExitedWithLeftovers { stdout, stderr, .. }
        | ShellRunResult::EndedWithLeftovers { stdout, stderr, .. } => program_outcome(
            false,
            "output drain overrun — a leftover process held the pipes".to_string(),
            &stdout,
            &stderr,
        ),
        ShellRunResult::MemoryExceeded {
            stdout,
            stderr,
            used,
            limit,
            ..
        } => program_outcome(false, mem::exceeded_failure(used, limit), &stdout, &stderr),
        ShellRunResult::SpawnFailed(e) => {
            program_outcome(false, format!("failed to start: {e}"), &[], &[])
        }
    }
}

/// Run `program` with `args` (argv — never a shell command string) in `cwd`,
/// under the bounds a direct run is held to (see [`run_bounded`]), contained as
/// an agent's command (see [`RunOwner::Agent`]), with the OWNER's environment:
/// his own command doing his own work.
///
/// `label` names what the caller asked to run and is what the failure prose
/// talks about, so the model reads back the thing it called rather than the
/// interpreter's path. Program and argv are taken explicitly rather than
/// specialised to the script convention so that the argv contract — nothing in
/// an argument is ever parsed as shell syntax — can be exercised without the
/// managed runtime.
///
/// Returns the run's combined output, annotated the way the shell annotates a
/// failure: the `[exit status: …]` note is appended as its own paragraph for
/// anything but a clean exit. `Err` is a run that could not complete — spawn
/// failure, timeout, drain overrun or the memory ceiling — never a non-zero
/// exit, so a script's own failure stays the script's output.
pub(crate) async fn run_program_with_timeout(
    cwd: &Path,
    program: &Path,
    args: &[String],
    label: &str,
) -> anyhow::Result<String> {
    annotate_run(
        run_program(cwd, program, args, RunOwner::Agent).await,
        label,
    )
}

/// [`run_program_with_timeout`] for the product's OWN work rather than the
/// owner's: the run gets the reduced [`internal_env_pairs`] environment, which
/// holds none of his secrets. The entry point is separate so that no caller has
/// to name an environment to say whose work a run is.
pub(crate) async fn run_internal_program_with_timeout(
    cwd: &Path,
    program: &Path,
    args: &[String],
    label: &str,
) -> anyhow::Result<String> {
    annotate_run(
        run_bounded(
            build_internal_program_command(program, args, cwd),
            RunOwner::Agent,
        )
        .await,
        label,
    )
}

/// The one mapping behind both entry points above: a finished run turned into
/// the caller's answer.
fn annotate_run(run: ShellRunResult, label: &str) -> anyhow::Result<String> {
    match run {
        ShellRunResult::Completed {
            stdout,
            stderr,
            status,
            ..
        } => {
            let code = status.code();
            let output = decode_raw_streams(&stdout, &stderr);
            if code == Some(0) {
                return Ok(output);
            }
            Ok(with_note(&output, &format_exit_status_note(code)))
        }
        // The same error class as the shell tool's timeout (a run that could
        // not complete), but a typed one-liner carrying the output tail rather
        // than the shell's structured block: a direct run has no per-call knob
        // to raise, so nothing here may advertise the `timeout_secs` escape
        // hatch, and it does not name what the kill ended the way the tool's
        // block does.
        ShellRunResult::TimedOut {
            stdout,
            stderr,
            elapsed,
            ..
        } => Err(anyhow::anyhow!(
            "timeout: {label} did not finish within {DEFAULT_SHELL_TIMEOUT_SECS}s and was killed\n{}",
            program_error_tail(elapsed, &stdout, &stderr),
        )),
        // The same impossibility as `run_program_outcome`: a direct run is
        // always ended, never kept — both outcomes are reported alike here.
        ShellRunResult::ExitedWithLeftovers {
            stdout,
            stderr,
            elapsed,
            ..
        }
        | ShellRunResult::EndedWithLeftovers {
            stdout,
            stderr,
            elapsed,
        } => Err(anyhow::anyhow!(
            "timeout: {label} exited but a leftover process kept its output pipes open \
             past the drain limit — hint: keep any process the script launches inside its \
             own lifetime\n{}",
            program_error_tail(elapsed, &stdout, &stderr),
        )),
        ShellRunResult::MemoryExceeded {
            stdout,
            stderr,
            elapsed,
            used,
            limit,
            ..
        } => Err(anyhow::anyhow!(
            "{label} {}\n{}",
            mem::exceeded_failure(used, limit),
            program_error_tail(elapsed, &stdout, &stderr),
        )),
        ShellRunResult::SpawnFailed(e) => Err(anyhow::anyhow!(
            "io: cannot run {label}: {e} — hint: the program must exist and be executable"
        )),
    }
}

/// Elapsed time plus the scrubbed tails of both streams, for a program run
/// that did not complete.
fn program_error_tail(elapsed: Duration, stdout: &[u8], stderr: &[u8]) -> String {
    let mut msg = format!("elapsed: {:.1}s", elapsed.as_secs_f64());
    append_output_tail(&mut msg, "stdout", stdout);
    append_output_tail(&mut msg, "stderr", stderr);
    msg
}

/// Decode both raw streams ([`decode_and_strip_ansi`]'s reading + ANSI strip) and
/// combine stderr onto its own line when non-blank (never a leading blank line
/// when stdout is empty). Never credential-scrubbed here: the `custom` tool's
/// output is scrubbed by the agent-level pass, while an alarm's trigger
/// deliberately shows a check exactly as the check produced it.
fn decode_raw_streams(stdout: &[u8], stderr: &[u8]) -> String {
    let stdout = decode_and_strip_ansi(stdout);
    let stderr = decode_and_strip_ansi(stderr);
    if stderr.trim().is_empty() {
        stdout
    } else if stdout.trim().is_empty() {
        stderr
    } else {
        format!("{stdout}\n{stderr}")
    }
}

fn tail_chars(s: &str, max_chars: usize) -> String {
    let char_count = s.chars().count();
    if char_count <= max_chars {
        return s.to_string();
    }
    s.chars().skip(char_count - max_chars).collect()
}

/// Appends the tail of an output buffer to `msg` with a label (e.g. "stdout" or "stderr").
///
/// The transformation chain: this platform's reading of a program's output
/// ([`decode_and_strip_ansi`]) → strip ANSI escapes → scrub credentials →
/// truncate to [`TIMEOUT_OUTPUT_TAIL_CHARS`] characters.
fn append_output_tail(msg: &mut String, label: &str, data: &[u8]) {
    if !data.is_empty() {
        let scrubbed = strip_and_scrub(data);
        let tail = tail_chars(&scrubbed, TIMEOUT_OUTPUT_TAIL_CHARS);
        let _ = write!(
            msg,
            "\n{label} (last {} chars): {tail}",
            tail.chars().count()
        );
    }
}

fn format_timeout_error(
    command: &str,
    elapsed: Duration,
    timeout_limit: Duration,
    pid: Option<u32>,
    stdout: &[u8],
    stderr: &[u8],
) -> String {
    let mut msg = format!(
        "Shell command timed out.\n\
         command: {command}\n\
         elapsed: {:.1}s\n\
         timeout_limit: {:.0}s",
        elapsed.as_secs_f64(),
        timeout_limit.as_secs_f64(),
    );
    if let Some(p) = pid {
        let _ = write!(msg, "\npid: {p}");
    }
    msg.push_str("\nreason: command was killed after exceeding the timeout");
    msg.push_str(
        "\nhint: for known-long commands, pass a larger per-call timeout via the `timeout_secs` tool argument (max 3600s).",
    );

    append_output_tail(&mut msg, "stdout", stdout);
    append_output_tail(&mut msg, "stderr", stderr);
    msg
}

/// The memory failure's structured block, in the shape of
/// [`format_timeout_error`]: the same fields and output tails, a reason that
/// names the memory ceiling rather than the timeout, and a hint pointing at
/// the one thing an agent can do about it. It never says "timed out" — a run
/// ended for memory must be impossible to mistake for one that ran out of
/// time. The amount is weighed against the machine's RAM in the first line,
/// and the ceiling that was crossed is named as its own field, as
/// `timeout_limit` is for a timeout.
fn format_memory_error(
    command: &str,
    elapsed: Duration,
    used: u64,
    limit: u64,
    pid: Option<u32>,
    stdout: &[u8],
    stderr: &[u8],
) -> String {
    let mut msg = format!(
        "Shell command {}.\n\
         command: {command}\n\
         elapsed: {:.1}s\n\
         memory_limit: {}",
        mem::exceeded_failure(used, limit),
        elapsed.as_secs_f64(),
        mem::gib(limit),
    );
    if let Some(p) = pid {
        let _ = write!(msg, "\npid: {p}");
    }
    msg.push_str("\nreason: command was killed after exceeding the memory limit");
    msg.push_str(
        "\nhint: the command's whole process tree grew past the ceiling — bound the \
         input it reads or split it into smaller commands.",
    );

    append_output_tail(&mut msg, "stdout", stdout);
    append_output_tail(&mut msg, "stderr", stderr);
    msg
}

/// The block appended to a completed command's output when the command exited but
/// left a process behind that still holds an output channel
/// ([`ShellRunResult::ExitedWithLeftovers`], the [`LeftoverPolicy::Keep`] path).
///
/// It is a NOTE on a completed command, never an error: the command's own exit
/// status and the output above it are the result, so this block only reports what is
/// still running and, in the mode that can act on it, how to stop it. Its lead is the
/// second section of `tool/shell_leftover.md` — moved out of Rust so the asset is the
/// one statement of it, including the survival bound the held channel gives the
/// leftover ([`crate::util::leftover_channels`]). `platform` is taken as a value
/// rather than read from [`SHELL_PLATFORM`] so both platforms' wording is drivable
/// from any host's tests, and the stop recipe is the platform's own
/// ([`leftover_stop_recipe`] — on Windows it lists the released root's children
/// rather than addressing the released pid). The mode's own sentence is the SAME
/// fragment [`render_leftover_notes`] renders into the tool description
/// ([`leftover_mode_sentence`]), so no Rust literal can drift from it: Full mode
/// emits the platform's stop recipe and then that fragment; ReadOnly emits the
/// fragment alone, because its guard rejects the process-control commands
/// (`kill`/`pkill`/`killall`, `taskkill`) the recipe names. `leftover_stop_recipe`
/// stays available for the durable record written into the log store (shown on
/// Logs → Issues), which is a record rather than guidance.
fn format_leftover_note(mode: ShellMode, platform: ShellPlatform, scope: Option<u32>) -> String {
    let mut msg = crate::prompt::load_prompt_sections("tool/shell_leftover.md")
        .into_iter()
        .nth(1)
        .expect("tool/shell_leftover.md carries the note's lead as its second section");
    // Full mode can stop what it names, so only there does the note carry this
    // platform's stop recipe; ReadOnly's guard rejects the commands it names.
    if matches!(mode, ShellMode::Full) {
        let _ = write!(msg, "\n{}", leftover_stop_recipe(platform, scope));
    }
    let _ = write!(msg, "\n{}", leftover_mode_sentence(mode));
    msg
}

/// The mode's own leftover fragment — [`render_leftover_notes`] renders it into
/// the tool description and [`format_leftover_note`] appends it to the per-call
/// note, so one asset serves both and neither can drift from the other.
fn leftover_mode_sentence(mode: ShellMode) -> String {
    crate::prompt::load_prompt(match mode {
        ShellMode::Full => "tool/shell_leftover_full.md",
        ShellMode::ReadOnly => "tool/shell_leftover_read_only.md",
    })
    .trim()
    .to_owned()
}

/// A leftover's containment and the way to stop it, in the exact wording Full mode's
/// note embeds and the durable record's `detail` carries — the identification
/// line plus the platform's stop command, or the honest unnamed case. Extracted so the
/// agent's note and the record cannot drift.
///
/// The two platforms differ in what `scope` can name. On unix it is the leftover's
/// process group id and the group still exists while any member lives, so
/// `kill -TERM -<pgid>` is directly actionable. On Windows it is the pid of the run's
/// root process, which the caller has already reaped with `child.wait()` by the time
/// this path is reached — so `taskkill /PID <pid> /T /F` would address a released pid
/// (failing, or worse, hitting a recycled unrelated tree). Windows records the parent
/// pid on each child, so the tree left behind is still reachable by parent: the recipe
/// lists it with `tasklist /FI "PPID eq <pid>"` and stops each listed process instead.
fn leftover_stop_recipe(platform: ShellPlatform, scope: Option<u32>) -> String {
    match (scope, platform) {
        (Some(pid), ShellPlatform::Unix) => {
            format!("leftover process group: {pid}\nstop it with: kill -TERM -{pid}")
        }
        (Some(pid), ShellPlatform::Windows) => format!(
            "leftover process tree: started by pid {pid}, which has already exited\n\
             list what it left: tasklist /FI \"PPID eq {pid}\"\n\
             stop each one: taskkill /PID <listed pid> /T /F"
        ),
        (None, _) => "the leftover could not be identified, so it cannot be named for a stop — \
                      remember it is still running."
            .to_string(),
    }
}

/// Shell command execution tool
pub struct ShellTool {
    /// Whether the shell runs in full or read-only mode.
    pub mode: ShellMode,
}

impl ShellTool {
    /// Create a new [`ShellTool`] with the given execution mode.
    #[must_use]
    pub const fn new(mode: ShellMode) -> Self {
        Self { mode }
    }

    /// Launch a command in the background (Full mode only): the command keeps
    /// running after this tool call returns, its raw output is written to a
    /// file in the temp area's `.agent` directory, and the returned message
    /// carries that file's path. The agent reads progress with the read tool
    /// and stops the session via [`Self::stop_background`].
    ///
    /// Two texts, and neither substitutes for the other: `executed` is the
    /// platform's reading of `written` ([`windows_line::executable`]), which is
    /// what actually runs, while `written` is the line the agent wrote: the one the
    /// started-session message shows it, and the one a launch failure or a refusal
    /// names it by. They arrive as [`windows_line::Executed`] and
    /// [`windows_line::Written`], so a call cannot pass them the other way round. A
    /// background command must never be the one path that loses its lines after the
    /// first: the whole reading is what the shell is handed here, and [`self::bg`] is
    /// where it is measured and handed over.
    async fn launch_background(
        &self,
        ws: &Workspace,
        executed: windows_line::Executed<'_>,
        written: windows_line::Written<'_>,
    ) -> anyhow::Result<(String, Option<i32>)> {
        let sessions = Self::background_sessions_handle()?;
        let path = sessions
            .launch(executed, written, ws.as_path(), self.mode)
            .await
            .map_err(anyhow::Error::msg)?;
        Ok((
            format!(
                "Background session started.\n\
                 output file: {}\n\
                 command: {}\n\
                 The command is running detached from this tool call — its raw output \
                 is written to the output file. Read the file with the read tool to follow \
                 progress. When the command exits, the line `[exit status: N]` is appended \
                 to the end of the file (including for exit 0) — its presence means the \
                 command finished. Stop the session with the shell tool's `stop` argument \
                 set to this output-file path.",
                path.display(),
                written.0
            ),
            Some(0),
        ))
    }

    /// Stop a background session by its output-file path (Full mode only):
    /// two-stage SIGTERM → grace → SIGKILL on unix, the session's whole process
    /// tree ended at once on Windows (see [`self::bg`] for the mechanism);
    /// stopping an already-finished session is a no-op.
    async fn stop_background(&self, stop_path: &str) -> anyhow::Result<(String, Option<i32>)> {
        let sessions = Self::background_sessions_handle()?;
        let path = PathBuf::from(stop_path);
        match sessions.stop(&path).await {
            Ok(self::bg::StopResult::Stopped) => Ok((
                format!(
                    "Background session stopped.\noutput file: {}",
                    path.display()
                ),
                Some(0),
            )),
            Ok(self::bg::StopResult::AlreadyFinished) => Ok((
                format!(
                    "Background session already finished — no action taken.\noutput file: {}",
                    path.display()
                ),
                Some(0),
            )),
            Err(e) => anyhow::bail!("{e}"),
        }
    }

    /// The agent-scoped background-session registry, read from the tool-batch
    /// context (set once per tool batch by the agent's `execute_tool_group`).
    /// `None` outside an agent run (management diagnostics, tests) —
    /// background mode is unavailable there.
    fn background_sessions_handle()
    -> anyhow::Result<std::sync::Arc<crate::tools::shell::BackgroundSessions>> {
        crate::agent::CURRENT_TOOL_BACKGROUND_SESSIONS
            .try_with(std::clone::Clone::clone)
            .unwrap_or(None)
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Background shell mode is not available in this context \
                     (no agent session registry)."
                )
            })
    }

    /// Execute a command and return `(formatted_output, exit_code)`.
    ///
    /// `exit_code` is `Some(0)` for success, `Some(n)` for non-zero exit, or
    /// `None` when the process was terminated by a signal.
    ///
    /// The `formatted_output` includes the `[exit status: N]` annotation for
    /// non-zero exits and signal termination (same format as [`execute()`]).
    /// Credentials are already scrubbed from the returned output.
    #[expect(clippy::too_many_lines)] // orchestration: validation, engine hook, containment
    pub(crate) async fn execute_with_status(
        &self,
        ws: &Workspace,
        args: serde_json::Value,
    ) -> anyhow::Result<(String, Option<i32>)> {
        // ── Background mode (Full shell roles only) ──
        // `stop`/`background` are checked before `command` is required, so a
        // stop-only invocation (no command) works. ReadOnly mode never reads
        // these arguments — its behavior is byte-identical to before.
        if self.mode == ShellMode::Full {
            let stop_path = super::get_opt_str(&args, "stop").filter(|s| !s.is_empty());
            let background = super::get_opt_bool(&args, "background")?.unwrap_or(false);
            if let Some(stop_path) = stop_path {
                if background {
                    anyhow::bail!(
                        "The `stop` and `background` arguments cannot be combined — \
                         pass only `stop` with the output-file path of a background session."
                    );
                }
                return self.stop_background(stop_path).await;
            }
            if background {
                let command_str = super::get_str(&args, "command")?;
                // The foreground's own reading (see [`Self::launch_background`]), so a
                // background command loses no line either.
                let exec_str = windows_line::executable(command_str, SHELL_PLATFORM, self.mode)
                    .map_err(anyhow::Error::msg)?;
                // The one whole-line rule both modes share: read-only mode reaches
                // it through `check_command`'s walk, this mode through its own entry
                // — keyed on the agent's own text, not on the platform's respelt
                // reading the spawn is handed.
                readonly::check_line_divergences(command_str, SHELL_PLATFORM)
                    .map_err(anyhow::Error::msg)?;
                return self
                    .launch_background(
                        ws,
                        windows_line::Executed(&exec_str),
                        windows_line::Written(command_str),
                    )
                    .await;
            }
        }

        let command_str = super::get_str(&args, "command")?;

        // Read-only mode: validate command before execution.
        // The grep engine interception runs in BOTH modes (read-only for the
        // validation path, full for the inherent read-only engine) — see below.
        //
        // `base` is the platform's reading of the command — the text that will
        // be executed, and the text the serve decision below is taken on (a
        // rewrite's members are that reading's, not the agent's spelling of it).
        // `command_str` stays the original: it is what the read-only check
        // validates, what the grep telemetry records, what profiles the output
        // and what every error message quotes.
        let base = windows_line::executable(command_str, SHELL_PLATFORM, self.mode)
            .map_err(anyhow::Error::msg)?;
        let mut exec_str = base.as_ref().to_owned();

        // Capture the grep-engine serve decision once, before the mode branch;
        // reused by both branches for the rewrite and by the telemetry write
        // after execution.
        let mut grep_serve = grep_engine::try_serve_command(&exec_str, ws.as_path());
        // The rewrite may name scratch spec files (the Windows hand-off); the
        // guard removes them on every exit path below, `bail!`s included.
        let _spec_files = SpecFiles(std::mem::take(&mut grep_serve.spec_files));

        if self.mode == ShellMode::ReadOnly {
            let ctx = self::readonly::CheckContext::for_workspace(ws.as_path());
            if let Err(rejection) = check_command(command_str, &ctx) {
                anyhow::bail!("{rejection}");
            }
            if let Some(rewritten) = grep_serve.rewritten.as_deref() {
                // The engine verb is an unlisted literal and passes validation; on the
                // off chance it does not, `exec_str` keeps the reading of the line it
                // was seeded with (on Windows the refusal below reports it instead).
                if check_command(rewritten, &ctx).is_ok() {
                    exec_str = rewritten.to_string();
                }
            }
        } else {
            // Full mode: no read-only validation, but the whole-line divergences
            // (`;`, `#`, a heredoc) are the one guard rule both modes decide —
            // `check_command` reaches them in read-only mode, this entry here, and
            // before the engine's refusal below so a `;`-line carrying a grep word
            // still gets the guard's message. Keyed on the agent's own text, not on
            // the platform's respelt reading the spawn is handed. Like every other
            // guard refusal, this one files no grep telemetry: a refused line is
            // not a search outcome, and nothing ran.
            readonly::check_line_divergences(command_str, SHELL_PLATFORM)
                .map_err(anyhow::Error::msg)?;
            // The engine is inherently read-only and preserves non-grep (incl.
            // mutating) segments verbatim. Background-mode Full greps are
            // deliberately NOT served (the early return above runs them on the
            // platform's reading of the line, and a background command is never
            // handed to the engine).
            if let Some(rewritten) = grep_serve.rewritten.as_deref() {
                exec_str = rewritten.to_string();
            }
        }

        // ── Windows: an unserved search is a tool error ──
        // The deliberate, documented exception to "a completed command is never
        // a tool error" (the engine module header states why): an unserved grep
        // member, or a produced rewrite the read-only guard rejected, would
        // otherwise reach the agent as interpreter noise under a status it
        // cannot tell from "no match". On unix `unserved_refusal` is `None` and
        // the original command runs.
        if let Some(cause) =
            unserved_refusal(SHELL_PLATFORM, &grep_serve, exec_str != base.as_ref())
        {
            self.write_grep_telemetry(ws, command_str, &grep_serve, false, &cause, None)
                .await;
            // The remedy follows the text that would run, not the cause: a text that
            // still carries a line break is the one shape only a file can run, whatever
            // cause the engine's refusal carries ([`windows_line::remedy`]). Only this
            // refusal can offer one — the text it refuses is a reading this module kept
            // a break in, while the failure the engine reports after a run is about a
            // text it served, which carries none.
            let remedy = exec_str
                .contains('\n')
                .then(|| windows_line::remedy(self.mode));
            anyhow::bail!(
                "{}",
                grep_engine::unserved_failure(&cause, remedy.as_deref())
            );
        }

        // Allow agent to override the default timeout via `timeout_secs`.
        // Capped at MAX_SHELL_TIMEOUT_SECS to prevent absurdly long runs.
        let timeout_secs = super::get_opt_u64(&args, "timeout_secs")?
            .map_or(DEFAULT_SHELL_TIMEOUT_SECS, |s| {
                s.min(MAX_SHELL_TIMEOUT_SECS)
            });
        let timeout = Duration::from_secs(timeout_secs);
        let drain_limit = output_drain_timeout();

        // ── The runner's own steps ──
        // A produced rewrite is executed by the plan its analysis was rendered
        // with, because the shell does not wait for this service's own image
        // ([`plan`]): the members the runner spawns itself are waited for by the
        // runner, and the status the tool reports is theirs. A produced rewrite that
        // was never applied bailed out above as an unserved search, so a plan here is
        // always the one the line was rewritten into.
        let mut plan_run = grep_serve.plan.take();
        if plan_run.is_none() {
            // A line the serve decision did not plan can still be an own-image
            // call of its own (`mahbot debug …`, `mahbot -V`): one the runner can
            // run as a single step is run by the runner, one it cannot is
            // refused rather than handed to a shell that will not wait for it.
            match plan::plan_for_command(
                windows_line::Executed(&exec_str),
                windows_line::Written(command_str),
                ws.as_path(),
            ) {
                plan::OwnImage::None => {}
                plan::OwnImage::Direct(direct) => plan_run = Some(direct),
                plan::OwnImage::Refused(cause) => {
                    anyhow::bail!("{}", plan::refusal_message(&cause));
                }
            }
        }

        // Measured at each hand-off — a planned fold, or the text the shell is spawned
        // with when no plan serves it — as [`windows_line::check_command_line`] states.
        match &plan_run {
            Some(plan_run) => plan_run
                .steps
                .iter()
                .try_for_each(|step| match &step.run {
                    plan::Run::Shell { text } => {
                        windows_line::check_command_line(text, SHELL_PLATFORM, self.mode)
                    }
                    plan::Run::Own { .. } => Ok(()),
                })
                .map_err(anyhow::Error::msg)?,
            None => windows_line::check_command_line(&exec_str, SHELL_PLATFORM, self.mode)
                .map_err(anyhow::Error::msg)?,
        }

        // Execute with timeout to prevent hanging commands. `exec_str` may be
        // the grep-engine rewrite — run through its plan when one was built, and
        // through the shell otherwise. The ORIGINAL `command_str` is what
        // `process_shell_output` sees below, so the grep output profile keeps
        // matching (and `cd … &&` chains still navigate the shell).
        let mut result = if let Some(plan_run) = &plan_run {
            plan::run(
                plan_run,
                timeout,
                drain_limit,
                mem::default_limit(),
                RunOwner::Agent,
            )
            .await
        } else {
            let mut cmd = build_shell_command(&exec_str, ws.as_path());
            run_command_with_timeout(
                &mut cmd,
                timeout,
                drain_limit,
                mem::default_limit(),
                RunOwner::Agent,
                LeftoverPolicy::Keep,
            )
            .await
        };

        // Stream-size marker: the engine reports stdin-fed stream bytes
        // consumed via a stderr marker; strip it from the agent-visible stderr.
        // The strip removes any line containing the marker token. The pre-flight
        // `exec` check misses env-prefixed (`FOO=1 exec 2>&1`) and escaped-verb
        // (`\exec 2>&1`) redirects, so the marker can leak into the agent-visible
        // stdout or a file — beyond this strip's reach. Runs on timeout output
        // too — the marker is flushed before the engine exits, so a later-member
        // hang would otherwise surface it.
        match &mut result {
            ShellRunResult::Completed { stderr, .. }
            | ShellRunResult::ExitedWithLeftovers { stderr, .. }
            | ShellRunResult::EndedWithLeftovers { stderr, .. }
            | ShellRunResult::TimedOut { stderr, .. }
            | ShellRunResult::MemoryExceeded { stderr, .. } => {
                if exec_str != base.as_ref() {
                    grep_engine::strip_stream_size_marker(stderr);
                }
            }
            ShellRunResult::SpawnFailed(_) => {}
        }

        // Grep-engine failure containment: the sentinel exit code means the
        // engine could neither serve nor exec the real grep, and a stale
        // self-update binary (one lacking the hidden subcommand) runs full
        // main() and dies at instance-lock with the lock message — its exit 1
        // is a legitimate grep no-match code, so the message is treated the
        // same. On unix the original command is re-run so the agent sees the
        // authentic result: in Full mode that re-executes the whole original
        // command, including any preserved mutation segments (mv/cp/mkdir/…)
        // kept verbatim in the rewrite — documented behavior: a mid-command
        // engine failure may repeat them. Residual: a mid-search panic after
        // output was streamed exits sentinel-3, but a pipe/chain member's exit
        // status masks it — aggregation tails (`grep | wc -l`, `grep | sort`)
        // are the worst case, turning the partial stream into authoritative-
        // looking wrong answers — so the agent sees the partial output.
        //
        // On Windows the same signatures are the engine failing to serve a
        // search the platform cannot run itself: telemetry is recorded and the
        // call is refused (the Windows-only exception above), with the engine's
        // own stderr line — where it wrote why it could not serve — as the
        // named cause. There the refusal marker covers the pipe/chain case the
        // exit status would otherwise mask. Timed-out/spawn-failed
        // results are not sentinel cases and keep their own handling below; a
        // leftover-holding result carries the command's own exit status and is
        // read the same way a completed one is.
        //
        // Accepted limit of reading exit 3 as the engine's on both platforms: on
        // Windows that refuses the call, so a SERVED multi-member command whose
        // last verbatim member legitimately exits 3 (`grep -rn x . &&
        // something-that-exits-3`, or `grep … | tail -1` with a tail that exits
        // 3) is refused even though the search ran — with the run's stderr read
        // as the cause, the generic line when it holds none. On unix the same
        // false trigger only re-runs the original command. The parent reads the
        // run's one composed status, never a per-member one, so a member-3 is
        // not told apart from an engine-3 here.
        let engine_failure = match &result {
            ShellRunResult::Completed { status, stderr, .. }
            | ShellRunResult::ExitedWithLeftovers { status, stderr, .. }
                if exec_str != base.as_ref() =>
            {
                engine_failure(status.code(), stderr, SHELL_PLATFORM)
            }
            _ => None,
        };
        let mut sentinel_rerun = false;
        let result = match engine_failure {
            Some(EngineFailure::Refused(cause)) => {
                self.write_grep_telemetry(
                    ws,
                    command_str,
                    &grep_serve,
                    false,
                    &cause,
                    Some(&result),
                )
                .await;
                // No remedy: a served text carries no break, so the serve decision
                // above offers none.
                anyhow::bail!("{}", grep_engine::unserved_failure(&cause, None));
            }
            Some(EngineFailure::ReRun) => {
                sentinel_rerun = true;
                // The platform that re-runs here is the one whose interpreter reads the
                // whole text itself, so the re-executed line has no single-line limit
                // to check — the refusal arm above is the other platform's.
                let mut original = build_shell_command(base.as_ref(), ws.as_path());
                run_command_with_timeout(
                    &mut original,
                    timeout,
                    drain_limit,
                    mem::default_limit(),
                    RunOwner::Agent,
                    LeftoverPolicy::Keep,
                )
                .await
            }
            None => result,
        };

        // Record the served invocation's exit code at DEBUG (filtered from the
        // general log stream). The dedicated `grep_telemetry` table is the
        // source of truth for grep decisions; this line is observability only.
        if exec_str != base.as_ref() {
            let exit_code = match &result {
                ShellRunResult::Completed { status, .. }
                | ShellRunResult::ExitedWithLeftovers { status, .. } => status.code(),
                _ => None,
            };
            tracing::debug!(
                command = command_str,
                ?exit_code,
                "grep engine: served exit"
            );
        }

        // Grep-engine telemetry: one row per greppable call lands in the
        // dedicated `grep_telemetry` table, keeping the general `logs` stream
        // clean of grep detail. Best-effort/fail-open — a telemetry failure
        // never affects the shell result. `applied` is the ground truth of
        // whether the shell was rewritten to the engine: the analysis outcomes
        // can report served even when no engine ran (engine unavailable, spec
        // too large, ReadOnly rejection) — and a sentinel re-run replaced the
        // engine with a real-grep run — so the row's served flag must reflect
        // the ACTUAL execution. The engine-internal `exec_grep` path (cwd
        // mismatch, matcher-build failure, version mismatch) re-execs real grep
        // in place, which is NOT observable from the parent; that residual is
        // documented rather than fixed.
        let applied = exec_str != base.as_ref();
        let served = applied && !sentinel_rerun;
        let reason = if sentinel_rerun {
            "engine sentinel re-run (real grep)"
        } else if !applied && grep_serve.rewritten.is_some() {
            // The rewrite was produced but ReadOnly validation rejected it —
            // the whole command ran real grep. Per-member skip reasons
            // describe the analysis, not why real grep ran. (On Windows this
            // case never reaches the row: it is refused above, under the same
            // cause.)
            GUARD_REJECTED_REASON
        } else if applied {
            grep_serve
                .outcomes
                .iter()
                .find(|o| !o.served)
                .map(|o| o.reason.as_str())
                .unwrap_or_default()
        } else {
            // No rewrite at all (engine unavailable / spec too large / only
            // skipped members): the outcomes carry the concrete reason.
            grep_serve
                .outcomes
                .iter()
                .find(|o| !o.reason.is_empty())
                .map_or("no rewrite produced", |o| o.reason.as_str())
        };
        self.write_grep_telemetry(ws, command_str, &grep_serve, served, reason, Some(&result))
            .await;

        // A completed run and one that left a process holding its output are the
        // same result — the command's own exit status and the output above it.
        // Only the latter additionally reports the leftover, so its scope is read
        // off the result before the match consumes it: `Some(None)` is a leftover
        // whose containment could not be identified (a rewritten plan's, whose
        // members are separate process groups), which is still a leftover to report.
        let leftover_scope = match &result {
            ShellRunResult::ExitedWithLeftovers { scope, .. } => Some(*scope),
            _ => None,
        };

        match result {
            ShellRunResult::Completed {
                stdout,
                stderr,
                status,
                elapsed,
            }
            | ShellRunResult::ExitedWithLeftovers {
                stdout,
                stderr,
                status,
                elapsed,
                ..
            } => {
                let stdout = decode_and_strip_ansi(&stdout);
                let stderr = decode_and_strip_ansi(&stderr);

                let exit_code = status.code(); // Option<i32> — None means signal
                let exit_note = format_exit_status_note(exit_code);

                // All completed commands return output with exit info,
                // regardless of exit code. Only actual execution failures
                // (timeout, process launch failure) are tool errors — plus the
                // Windows unserved search refused above.
                let processed = process_shell_output(
                    command_str,
                    &stdout,
                    &stderr,
                    exit_code.unwrap_or(-1),
                    elapsed,
                );
                let combined = if exit_code == Some(0) {
                    processed
                } else {
                    with_note(&processed, &exit_note)
                };

                // A command that exited but left a process behind that still holds
                // its output channel adds a leftover note on top of this completed
                // result, and one durable record in the log store (shown on Logs →
                // Issues). The note is built as
                // its own step and applied once below, so the call has a single
                // return and the "finished result plus a leftover note" shape is
                // visible at a glance.
                let leftover_note = match leftover_scope {
                    Some(scope) => {
                        // The durable record of what outlived the call — the one
                        // record of the occurrence, shown on Logs → Issues: the
                        // stop recipe (shown to the agent only in Full mode), the
                        // containment it names, the run's elapsed time and the
                        // calling agent's own attribution (see
                        // [`crate::logs::record_stray_event`]).
                        let scope_text = scope.map_or_else(String::new, |pid| pid.to_string());
                        let workspace = ws.as_path().to_string_lossy().into_owned();
                        crate::logs::record_stray_event(crate::logs::StrayEvent {
                            source: crate::logs::STRAY_SOURCE_SHELL,
                            message: "the command exited while a process it left running still held \
                                      its output channel, so no more of that output could be \
                                      collected",
                            recipe: &leftover_stop_recipe(SHELL_PLATFORM, scope),
                            scope: &scope_text,
                            session: "",
                            workspace: &workspace,
                            duration_ms: Some(crate::util::millis_i64(elapsed)),
                        })
                        .await;
                        Some(format_leftover_note(self.mode, SHELL_PLATFORM, scope))
                    }
                    None => None,
                };
                let combined = if let Some(note) = leftover_note {
                    with_note(&combined, &note)
                } else {
                    combined
                };
                Ok((combined, exit_code))
            }
            // A run whose tree was ended because a leftover held its output pipes
            // past the drain limit must never be folded into a finished call.
            ShellRunResult::EndedWithLeftovers { elapsed, .. } => anyhow::bail!(
                "Shell command exited but a leftover process held its output pipes open \
                 past the drain limit; the run's tree was ended (elapsed: {:.1}s)",
                elapsed.as_secs_f64()
            ),
            ShellRunResult::TimedOut {
                stdout,
                stderr,
                pid,
                elapsed,
            } => {
                tracing::info!(
                    command = command_str,
                    elapsed_secs = elapsed.as_secs_f64(),
                    ?pid,
                    stdout_bytes = stdout.len(),
                    stderr_bytes = stderr.len(),
                    "Shell command timed out"
                );
                let msg =
                    format_timeout_error(command_str, elapsed, timeout, pid, &stdout, &stderr);
                anyhow::bail!("{msg}");
            }
            ShellRunResult::MemoryExceeded {
                stdout,
                stderr,
                pid,
                elapsed,
                used,
                limit,
            } => {
                tracing::info!(
                    command = command_str,
                    elapsed_secs = elapsed.as_secs_f64(),
                    ?pid,
                    used = used,
                    limit = limit,
                    stdout_bytes = stdout.len(),
                    stderr_bytes = stderr.len(),
                    "Shell command terminated: exceeded memory limit"
                );
                let msg =
                    format_memory_error(command_str, elapsed, used, limit, pid, &stdout, &stderr);
                anyhow::bail!("{msg}");
            }
            ShellRunResult::SpawnFailed(e) => anyhow::bail!(
                "Failed to start shell command.\n\
                 command: {command_str}\n\
                 reason: {e}"
            ),
        }
    }

    /// Persist one grep-engine telemetry row, best-effort (fail-open: a
    /// telemetry failure never affects the shell result). One helper because
    /// the record is required on every platform and on every outcome — the
    /// post-execution decision as well as the two Windows failure paths, which
    /// bail with the row's `reason` before ever running a command.
    ///
    /// `served` is the ground truth of the actual engine execution and `reason`
    /// the decision's cause; `result` is the run the row describes (`None` for
    /// a call that bailed before executing, so its elapsed time and exit code
    /// are empty). A command the analysis never reached a grep member in writes
    /// no row — except a refused Windows search, which is recorded precisely
    /// because it must not be invisible (the shape fields stay empty).
    async fn write_grep_telemetry(
        &self,
        ws: &Workspace,
        command: &str,
        grep_serve: &grep_engine::GrepServe,
        served: bool,
        reason: &str,
        result: Option<&ShellRunResult>,
    ) {
        if grep_serve.outcomes.is_empty() && grep_serve.refusal.is_none() {
            return;
        }
        let shape = grep_serve.telemetry_shape(served);
        let mode = match self.mode {
            ShellMode::ReadOnly => "ReadOnly",
            ShellMode::Full => "Full",
        };
        let workspace = ws.as_path().to_string_lossy().into_owned();
        let (duration_ms, exit_code) = match result {
            Some(
                ShellRunResult::Completed {
                    elapsed, status, ..
                }
                | ShellRunResult::ExitedWithLeftovers {
                    elapsed, status, ..
                },
            ) => (Some(crate::util::millis_i64(*elapsed)), status.code()),
            // A stopped run and one whose tree was ended for a leftover
            // ([`LeftoverPolicy::End`], never a tool call's own result) report a
            // clock and no exit status.
            Some(
                ShellRunResult::TimedOut { elapsed, .. }
                | ShellRunResult::MemoryExceeded { elapsed, .. }
                | ShellRunResult::EndedWithLeftovers { elapsed, .. },
            ) => (Some(crate::util::millis_i64(*elapsed)), None),
            // A spawn failure has an attempt behind it but no clock to read: the
            // duration is the placeholder zero, and the absent exit status is
            // what marks the row.
            Some(ShellRunResult::SpawnFailed(_)) => (Some(0), None),
            // A call that bailed before running has nothing to measure: the row
            // carries no timing at all, rather than a zero that would read as a
            // genuine zero-duration run.
            None => (None, None),
        };
        if let Some(store) = crate::logs::LOG_STORE.get() {
            let row = crate::logs::GrepTelemetryRow {
                command,
                served,
                reason,
                recursive: shape.recursive,
                piped: shape.piped,
                operand_count: shape.operand_count,
                flags: shape.flags.as_str(),
                mode,
                workspace: workspace.as_str(),
                grep_count: shape.grep_count,
                served_count: shape.served_count,
                skipped_count: shape.skipped_count,
                duration_ms,
                exit_code,
            };
            let _ = store.record_grep_telemetry(row).await;
        }
    }
}

/// Extra `PATH` entries prepended to the fallback `PATH` (see
/// [`resolved_shell_path`]) so developer tools (`cargo`, Homebrew, npm global
/// bins, the managed bun runtime, etc.) resolve even in the product's own
/// internal work, which never reads a parent `PATH`.
///
/// Always includes the cargo bin directory (via `$CARGO_HOME/bin` if set,
/// else `~/.cargo/bin`) plus commonly expected system tool directories.
///
/// The standard per-user programs directory
/// ([`crate::util::managed_bin::mahbot_install_dir`]) is on the list as well: the
/// product's own installed command lives there, so an agent that runs it by bare
/// name reaches the installed copy.
///
/// # `$CARGO_HOME` belt-and-suspenders
///
/// When `$CARGO_HOME` is explicitly set, both `$CARGO_HOME/bin` (from
/// [`crate::util::cargo_bin_dir`]) AND `~/.cargo/bin` are added, so users
/// with a non-default `CARGO_HOME` still have their cargo-installed tools
/// found. Deduplication in [`prepend_path_entries`] handles the case when
/// both point to the same directory.
fn extra_shell_path_prefixes() -> Vec<PathBuf> {
    let mut v = Vec::new();

    // cargo_bin_dir() returns $CARGO_HOME/bin if CARGO_HOME is set,
    // else ~/.cargo/bin.
    if let Some(dir) = crate::util::cargo_bin_dir() {
        v.push(dir);
    }

    // Belt-and-suspenders: when CARGO_HOME is explicitly set, also add
    // ~/.cargo/bin so both paths are covered. Dedup by prepend_path_entries.
    if let Ok(cargo_home) = std::env::var("CARGO_HOME")
        && !cargo_home.is_empty()
        && let Some(dirs) = UserDirs::new()
    {
        v.push(dirs.home_dir().join(".cargo").join("bin"));
    }

    // The product's own installed command.
    if let Some(dir) = crate::util::managed_bin::mahbot_install_dir() {
        v.push(dir);
    }

    #[cfg(unix)]
    if let Some(dirs) = UserDirs::new() {
        v.push(dirs.home_dir().join(".npm-global").join("bin"));
    }
    #[cfg(target_os = "macos")]
    {
        v.push(PathBuf::from("/opt/homebrew/bin"));
        v.push(PathBuf::from("/usr/local/bin"));
    }

    // Managed bun runtime (~/.bun/bin) — appended LAST so a user-installed bun
    // (Homebrew, npm, official installer) keeps precedence over ours.
    if let Some(dir) = crate::util::managed_bin::bun_bin_dir() {
        v.push(dir);
    }
    v
}

#[cfg(unix)]
const fn default_search_path_without_parent_env() -> &'static str {
    "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
}

/// The system root (normally `C:\Windows`) from the system's own values — the
/// drive is never assumed, since Windows may be installed on another one.
///
/// Resolution order: [`GetWindowsDirectoryW`] (authoritative — it is what the
/// OS itself uses), then `%SystemRoot%`, then `%WINDIR%`. Cached because it is
/// read several times per spawned command. The empty string when all three
/// fail, in which case callers refuse to hand out a fabricated root.
///
/// [`GetWindowsDirectoryW`]: windows_sys::Win32::System::SystemInformation::GetWindowsDirectoryW
#[cfg(windows)]
#[must_use]
fn windows_system_root() -> &'static str {
    static ROOT: OnceLock<String> = OnceLock::new();
    ROOT.get_or_init(|| {
        system_root_from_api()
            .or_else(|| env_system_root("SystemRoot"))
            .or_else(|| env_system_root("WINDIR"))
            .unwrap_or_else(|| {
                tracing::error!(
                    "Windows system root unavailable: GetWindowsDirectoryW failed and \
                     %SystemRoot%/%WINDIR% are unset"
                );
                String::new()
            })
    })
}

/// The system root as the OS reports it, through `GetWindowsDirectoryW`'s
/// two-pass protocol: probe the required length with a null/short buffer, then
/// read into a buffer of exactly that length. Trailing separators are trimmed
/// so callers can append `\System32` to the result.
#[cfg(windows)]
#[must_use]
fn system_root_from_api() -> Option<String> {
    use windows_sys::Win32::System::SystemInformation::GetWindowsDirectoryW;

    // SAFETY: a null buffer with a zero size is the documented length probe —
    // with no room to write, the API only reports the required size.
    let needed = unsafe { GetWindowsDirectoryW(std::ptr::null_mut(), 0) };
    if needed == 0 {
        return None;
    }
    let mut buf = vec![0u16; needed as usize];
    // SAFETY: `buf` has room for exactly the `needed` UTF-16 units the probe
    // asked for; the API writes at most that many and reports how many.
    let written = unsafe { GetWindowsDirectoryW(buf.as_mut_ptr(), needed) };
    if written == 0 {
        return None;
    }
    // `written` excludes the terminator, but a root that grew between the probe
    // and the read returns the (larger) required size instead — clamp it.
    let root = String::from_utf16_lossy(&buf[..(written as usize).min(buf.len())]);
    let root = root.trim_end_matches(['\\', '/', '\0']);
    if root.is_empty() {
        return None;
    }
    Some(root.to_string())
}

/// A root taken from the named environment variable: unset, empty or
/// separator-only values count as absent, and a trailing separator is trimmed
/// so the value joins natively.
#[cfg(windows)]
#[must_use]
fn env_system_root(name: &str) -> Option<String> {
    let value = std::env::var(name).ok()?;
    let trimmed = value.trim_end_matches(['\\', '/']);
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

#[cfg(windows)]
fn default_search_path_without_parent_env() -> String {
    let root = windows_system_root();
    if root.is_empty() {
        // An empty baseline beats one fabricated around a drive we can't
        // confirm; the extra prefixes are still prepended onto it.
        return String::new();
    }
    format!(r"{root}\System32;{root};{root}\System32\Wbem;{root}\System32\WindowsPowerShell\v1.0")
}

fn prepend_path_entries(base: impl AsRef<str>, extras: &[PathBuf]) -> String {
    let base = base.as_ref();
    let sep = if cfg!(windows) { ";" } else { ":" };

    let mut seen = HashSet::<String>::new();
    let mut parts = Vec::new();

    let normalize = |s: &str| -> String {
        if cfg!(windows) {
            s.to_lowercase()
        } else {
            s.to_string()
        }
    };

    for p in extras {
        let s = p.to_string_lossy().to_string();
        if s.is_empty() {
            continue;
        }
        if seen.insert(normalize(&s)) {
            parts.push(s);
        }
    }

    for part in base.split(sep) {
        if part.is_empty() {
            continue;
        }
        if seen.insert(normalize(part)) {
            parts.push(part.to_string());
        }
    }

    parts.join(sep)
}

/// The `PATH` of the reduced fallback environment
/// ([`internal_env_pairs`]): a portable system baseline plus
/// [`extra_shell_path_prefixes`], not the owner's `PATH`.
///
/// It is *not* what an agent's commands get once the owner's environment has
/// been read — those run with the owner's own `PATH` (see [`agent_env_pairs`]).
/// This list serves the product's internal work and stands in whenever no read
/// has succeeded.
fn resolved_shell_path() -> String {
    prepend_path_entries(
        default_search_path_without_parent_env(),
        &extra_shell_path_prefixes(),
    )
}

/// Baseline value of a [`FALLBACK_ENV_VARS`] entry. The temp variables are not
/// handled here: they come from [`crate::temp::shell_temp_vars`] (see
/// [`internal_env_pairs`]).
fn baseline_env_value(name: &str) -> Option<String> {
    match name {
        "PATH" => Some(resolved_shell_path()),
        "HOME" | "USERPROFILE" => {
            UserDirs::new().map(|d| d.home_dir().to_string_lossy().into_owned())
        }
        // Read from this process rather than derived: usernames are not
        // secrets, and the fallback has no other source for one.
        "USER" | "USERNAME" => std::env::var("USER")
            .or_else(|_| std::env::var("USERNAME"))
            .ok()
            .or_else(|| Some("user".into())),
        "TERM" => Some("dumb".into()),
        "LANG" | "LC_ALL" | "LC_CTYPE" => Some("C.UTF-8".into()),
        "SHELL" => Some("/bin/sh".into()),
        _ => {
            #[cfg(windows)]
            if let Some(val) = windows_baseline_env_value(name) {
                return Some(val);
            }
            None
        }
    }
}

/// Returns baseline values for Windows-specific environment variables.
///
/// These variables are only meaningful on Windows. Where the parent process
/// knows the value (`%SystemDrive%`, `%ComSpec%`), its own is preferred; the
/// rest are derived from the OS-reported system root rather than from a
/// hard-coded `C:`, so an install on another drive still gets a usable
/// environment.
#[cfg(windows)]
fn windows_baseline_env_value(name: &str) -> Option<String> {
    match name {
        "PATHEXT" => Some(".COM;.EXE;.BAT;.CMD;.VBS;.JS".into()),
        "HOMEDRIVE" | "HOMEPATH" => UserDirs::new().and_then(|d| {
            let s = d.home_dir().to_string_lossy().into_owned();
            // Note: Windows home paths always start with a drive letter
            // (e.g., "C:\Users\..."), so byte-index slicing at positions 0..2
            // is safe. We validate the drive-letter pattern by checking that
            // the second byte is b':' (colon). This relies on the ASCII
            // representation of drive letters (A-Z).
            if s.len() >= 2 && s.as_bytes().get(1) == Some(&b':') {
                match name {
                    "HOMEDRIVE" => Some(s[..2].to_string()),
                    // HOMEPATH: slice from byte 2 onward to skip "C:"
                    _ => Some(s[2..].to_string()),
                }
            } else {
                None
            }
        }),
        // None of these is ever fabricated around a `C:` assumption: an absent
        // system root leaves the variable unset rather than pointing a child at
        // a plausible-but-wrong drive.
        "SYSTEMROOT" | "WINDIR" => {
            let root = windows_system_root();
            (!root.is_empty()).then(|| root.to_string())
        }
        "SYSTEMDRIVE" => inherited_env_value("SystemDrive").or_else(|| {
            // Drive prefix of the system root — the drive letter plus its colon
            // (`C:`), derived rather than assumed: the second byte being `:`
            // proves the `X:` shape, and both bytes are ASCII, so slicing is
            // safe.
            let root = windows_system_root();
            (root.as_bytes().get(1) == Some(&b':')).then(|| root[..2].to_string())
        }),
        "COMSPEC" => inherited_env_value("ComSpec").or_else(|| {
            let root = windows_system_root();
            (!root.is_empty()).then(|| format!(r"{root}\System32\cmd.exe"))
        }),
        _ => None,
    }
}

/// The parent process's value for a Windows variable that is not a secret, when
/// set to something non-empty — the authoritative source when it exists.
#[cfg(windows)]
#[must_use]
fn inherited_env_value(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|value| !value.is_empty())
}

/// The read-only banner: the shared skeleton with the daemon's temp root and the
/// session platform's check bullets substituted in. A literal path is the one
/// spelling every shell resolves the same way, so the skeleton carries it; the
/// platform's own tools and temp variables are named only in the selected
/// fragment, since one shared file would push one platform's spellings at the
/// other's sessions (the same reason `crate::temp`'s temp-cleanup renderer
/// selects its tool block).
fn render_readonly_banner() -> String {
    let platform_checks = crate::prompt::load_prompt(match SHELL_PLATFORM {
        ShellPlatform::Windows => "tool/shell_readonly_banner_windows.md",
        ShellPlatform::Unix => "tool/shell_readonly_banner_unix.md",
    })
    .trim()
    .to_owned();
    crate::prompt::substitute(
        &crate::prompt::load_prompt("tool/shell_readonly_banner.md"),
        &[
            ("{{temp_root}}", &crate::temp::shell_tmpdir()),
            ("{{platform_checks}}", &platform_checks),
        ],
    )
}

/// The grep-engine disclosure: the shared skeleton with the session platform's
/// fragment substituted in — the engine serves the same searches here as
/// everywhere, but what a platform does with the ones it cannot serve, and what
/// it has to fall back on, differs. Both renderers read [`SHELL_PLATFORM`], the
/// same value the guard and the engine's command model read, so a Windows
/// session is never told about a system `grep` and a unix one never about its
/// absence.
fn render_grep_notes() -> String {
    let platform_notes = crate::prompt::load_prompt(match SHELL_PLATFORM {
        ShellPlatform::Windows => "tool/shell_grep_notes_windows.md",
        ShellPlatform::Unix => "tool/shell_grep_notes_unix.md",
    })
    .trim()
    .to_owned();
    crate::prompt::substitute(
        &crate::prompt::load_prompt("tool/shell_grep_notes.md"),
        &[("{{platform_notes}}", &platform_notes)],
    )
}

/// The command-line reading: this platform's own rules for a command text's line
/// breaks, the reading the shell applies before the guard looks at anything. One
/// skeleton for both modes — the reading is the same in both, one line or two — with
/// the sentences the mode decides substituted in from its own fragment: which
/// characters a caret's escape may reach, whether that same text is read by the
/// guard's reader as well, and the answer to every shape the reading refuses (a file,
/// which the read-only mode does not run). The read-only mode's aside is the one
/// sentence the skeleton carries no place for: the mode that has none must not be left
/// a paragraph for it, so it is added to the rendered text (see below). `platform` and
/// `mode` are arguments rather than the process-global pair, so a host of either kind
/// renders — and tests — both. `None` on the platform whose own interpreter already
/// separates commands at a break: it has nothing to be told about line breaks.
fn render_command_line_notes(platform: ShellPlatform, mode: ShellMode) -> Option<String> {
    if platform != ShellPlatform::Windows {
        return None;
    }
    // Each of the mode's fragments — the caret's clause and the remedy — is written
    // exactly once in the skeleton, and [`crate::prompt::substitute`] replaces every
    // occurrence it finds: a fragment written twice is a sentence the agent reads twice.
    let escaped_target = crate::prompt::load_prompt(match mode {
        ShellMode::Full => "tool/shell_command_lines_escaped_full.md",
        ShellMode::ReadOnly => "tool/shell_command_lines_escaped_read_only.md",
    })
    .trim()
    .to_owned();
    let remedy = windows_line::remedy(mode);
    // The limit's sentence is built from the same constants the refusal names, so the
    // three numbers cannot drift apart.
    let cap = windows_line::COMMAND_LINE_CAP.to_string();
    let limit = windows_line::TEXT_UNIT_LIMIT.to_string();
    let overhead = (windows_line::COMMAND_LINE_CAP - windows_line::TEXT_UNIT_LIMIT).to_string();
    let mut notes = crate::prompt::substitute(
        &crate::prompt::load_prompt("tool/shell_command_lines.md"),
        &[
            ("{{escaped_target}}", &escaped_target),
            ("{{remedy}}", &remedy),
            ("{{cap}}", &cap),
            ("{{limit}}", &limit),
            ("{{overhead}}", &overhead),
        ],
    );
    // The aside is added to the mode that has one, one blank line after the last
    // paragraph: the skeleton's own trailing line break goes with the join.
    if mode == ShellMode::ReadOnly {
        notes = format!(
            "{}\n\n{}",
            notes.trim_end(),
            crate::prompt::load_prompt("tool/shell_command_lines_read_only_aside.md").trim()
        );
    }
    Some(notes)
}

/// The full-mode notes: the shared skeleton with this platform's answers
/// substituted in. What stopping a session does, and what a trailing separator
/// is, are the two things the platforms do differently — a session must never be
/// promised a mechanism its platform does not have, and a separator must not be
/// described by another platform's meaning. [`tree`] is where the stop mechanisms
/// themselves are.
fn render_full_mode_notes() -> String {
    let stop = stop_semantics();
    let trailing = crate::prompt::load_prompt(match SHELL_PLATFORM {
        ShellPlatform::Windows => "tool/shell_full_trailing_windows.md",
        ShellPlatform::Unix => "tool/shell_full_trailing_unix.md",
    })
    .trim()
    .to_owned();
    crate::prompt::substitute(
        &crate::prompt::load_prompt("tool/shell_full.md"),
        &[
            ("{{stop_semantics}}", &stop),
            ("{{trailing_separator}}", &trailing),
        ],
    )
}

/// The leftover-process section, rendered in **both** modes: what the agent is
/// handed when a command exits while a process it started still holds the
/// command's output channel ([`format_leftover_note`]). It renders ONLY the first
/// section of `tool/shell_leftover.md` — the shared skeleton that states the note's
/// own meaning (a FINISHED call whose result is the command's own output and exit
/// status, the leftover left RUNNING with no further output from it collected, its
/// containment named where one can be named) — so the description does not grow the
/// per-call note's lead, which is the asset's second section. The mode's own
/// sentence closes it: Full mode carries the platform's stop command where the
/// containment is known and points at the `background: true` / `stop` mechanism,
/// ReadOnly mode states that this mode has no process control at all. One skeleton,
/// so the two modes cannot describe the same note differently.
fn render_leftover_notes(mode: ShellMode) -> String {
    let mode_sentence = leftover_mode_sentence(mode);
    let skeleton = crate::prompt::load_prompt_sections("tool/shell_leftover.md")
        .into_iter()
        .next()
        .expect("tool/shell_leftover.md carries the description skeleton as its first section");
    crate::prompt::substitute(&skeleton, &[("{{mode_sentence}}", &mode_sentence)])
}

/// This platform's own section — what its tool set is, what the two readers read
/// differently, how its interpreter is started and how its programs' output is
/// read back — rendered in **both** modes: none of it is a mode's rule, and an
/// agent's command is read the same way whichever mode it is running in. `None`
/// on the platform these notes would not be true of, so nothing is said there.
fn render_platform_notes(platform: ShellPlatform) -> Option<String> {
    match platform {
        ShellPlatform::Windows => Some(
            crate::prompt::load_prompt("tool/shell_platform_windows.md")
                .trim()
                .to_owned(),
        ),
        ShellPlatform::Unix => None,
    }
}

/// What stopping a run does on this platform — one text for both the tool
/// description's stop bullet and the `stop` argument's schema entry, so the two
/// cannot promise different mechanisms.
fn stop_semantics() -> String {
    crate::prompt::load_prompt(match SHELL_PLATFORM {
        ShellPlatform::Windows => "tool/shell_full_stop_windows.md",
        ShellPlatform::Unix => "tool/shell_full_stop_unix.md",
    })
    .trim()
    .to_owned()
}

#[async_trait]
impl Tool for ShellTool {
    fn name(&self) -> &'static str {
        "shell"
    }

    fn description(&self) -> String {
        // The base description and the grep-engine disclosure are shared
        // verbatim between the modes (a single copy each, so the two
        // descriptions cannot drift); only the read-only banner, the full-mode
        // sections (stop semantics included), the leftover-process section and
        // the platform-selected texts — this platform's own rules, the grep
        // notes and the command-line reading — are mode-/platform-specific.
        let base = crate::prompt::load_prompt("tool/shell.md");
        let mut sections: Vec<String> = match self.mode {
            ShellMode::ReadOnly => vec![render_readonly_banner(), base],
            ShellMode::Full => vec![base, render_full_mode_notes()],
        };
        sections.push(render_leftover_notes(self.mode));
        // A platform with nothing to add is handed the sections it had before this one
        // existed, with no blank line where it would have been.
        if let Some(platform_notes) = render_platform_notes(SHELL_PLATFORM) {
            sections.push(platform_notes);
        }
        sections.push(render_grep_notes());
        if let Some(command_lines) = render_command_line_notes(SHELL_PLATFORM, self.mode) {
            sections.push(command_lines);
        }
        sections
            .iter()
            .map(|s| s.trim_end())
            .collect::<Vec<_>>()
            .join("\n\n")
    }

    fn parameters_schema(&self) -> serde_json::Value {
        let timeout_secs = json!({
            "type": "integer",
            "description": "Optional custom timeout in seconds (default: 600, max: 3600). Use this for long-running commands that need more than the default 10-minute timeout.",
            "minimum": 1,
            "maximum": 3600
        });
        match self.mode {
            // ReadOnly: byte-identical to the pre-background literal. The
            // background capability is Full-only; the shared `timeout_secs`
            // binding below keeps the two schemas from drifting.
            ShellMode::ReadOnly => super::tool_params_schema(
                &json!({
                    "command": {
                        "type": "string",
                        "description": "The shell command to execute"
                    },
                    "timeout_secs": timeout_secs,
                }),
                &["command"],
            ),
            // Full: adds the background/stop arguments on top of the same
            // command/timeout_secs literal. `command` is intentionally NOT in
            // `required` here: a stop-only invocation passes just `stop`, and
            // requiring `command` would push a schema-following model into
            // inventing a dummy command for stop calls (the daemon accepts
            // both shapes, but the documented stop-only shape must not be
            // rejected by provider-side validation).
            ShellMode::Full => super::tool_params_schema(
                &json!({
                    "command": {
                        "type": "string",
                        "description": "The shell command to execute. Required for normal and background runs; not needed (and ignored) when `stop` is set."
                    },
                    "timeout_secs": timeout_secs,
                    "background": {
                        "type": "boolean",
                        "description": "When true, run the command in the background: it keeps running after this tool call returns and its raw output is written to a file in the temp area whose path is returned. Read that file with the read tool; when the command exits, the line `[exit status: N]` is appended to its end (including exit 0). `timeout_secs` is ignored in background mode. Default: false.",
                        "default": false
                    },
                    "stop": {
                        "type": "string",
                        // The platform's own stop text (`stop_semantics`) — the
                        // same text the description's stop bullet carries.
                        "description": format!(
                            "Output-file path of a background session (as returned by a \
                             background launch) to stop. {} Pass only `stop` with the exact \
                             path — a `command` is not needed and is ignored if present, and \
                             `background` must NOT be combined with `stop` (the tool rejects \
                             the combination). Stopping an already-finished session is a no-op.",
                            stop_semantics()
                        )
                    },
                }),
                &[],
            ),
        }
    }

    fn side_effects(&self) -> bool {
        // ReadOnly mode validates commands against a mutating-command blocklist
        // — best-effort guard, not a sandbox, but sufficient for grouping.
        self.mode != ShellMode::ReadOnly
    }

    fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
        false // shell pipeline already scrubs stdout and stderr once at pipeline entry
    }

    async fn execute(&self, ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
        self.execute_with_status(ws, args)
            .await
            .map(|(output, _)| output)
    }
}

/// Get the shared temp directory for spill/full output logs.
///
/// NO startup purge here: crash-leftover `.agent` files are reclaimed by the
/// periodic temp cleaner (see [`crate::temp`]) or the OS temp sweep — the
/// daemon builds no startup reclamation. Within a run, owner-deletes-at-end
/// removes what the agent created.
pub(crate) fn agent_temp_dir() -> Option<std::path::PathBuf> {
    let dir = std::env::temp_dir().join(".agent");
    std::fs::create_dir_all(&dir).ok()?;
    Some(dir)
}

/// Spill paths created during agent runs, keyed by the owning agent id: spill
/// files plus the read tool's per-call document-conversion directories.
/// Owner-deletes-at-end: [`cleanup_agent_spills`] removes them when the agent
/// run ends. Entries for a dead agent id are removed on cleanup; a daemon
/// crash leaves the files behind for the OS temp sweep and the periodic
/// temp cleaner (the daemon performs no startup purge).
static SPILL_OWNERS: std::sync::LazyLock<
    std::sync::Mutex<std::collections::HashMap<String, Vec<std::path::PathBuf>>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));

/// Record a spill path (file or the read tool's conversion directory) under the
/// current tool's owning agent id (set during agent tool execution). Outside an
/// agent run (tests, the verification round's project commands) it is recorded under
/// [`crate::agent::role::DIAGNOSTICS_ROLE`] (`"diagnostics"`). Agent ids are
/// always prefixed (`ticket_*`, `manager_*`, etc.) and never equal bare
/// `"diagnostics"` so no collision. Tests outside an agent also bucket there
/// (acceptable).
pub(crate) fn record_spill_owner(path: std::path::PathBuf) {
    let agent = crate::agent::CURRENT_TOOL_AGENT_ID
        .try_with(Clone::clone)
        .unwrap_or(None);
    if let Some(ref agent_id) = agent {
        debug_assert_ne!(
            agent_id,
            crate::agent::role::DIAGNOSTICS_ROLE,
            "agent id must not collide with diagnostics spill owner"
        );
    }
    let key = agent.unwrap_or_else(|| crate::agent::role::DIAGNOSTICS_ROLE.to_string());
    let mut map = SPILL_OWNERS.lock().unwrap_poison();
    map.entry(key).or_default().push(path);
}

/// Delete the spill paths recorded for `agent_id` (owner-deletes-at-end): a
/// path that is a directory (the read tool's per-call document-conversion
/// artifacts) is removed whole with [`std::fs::remove_dir_all`], a spill file
/// with [`std::fs::remove_file`]. Also clears the registry entry so a later run
/// of the same agent id starts fresh. Callers: the agent run-end cleanup guard
/// (`RunEndCleanup`, which fires on every unwinding exit path of a run — see its
/// doc for the ones it cannot cover) and the verification round's project-commands
/// run (which passes [`crate::agent::role::DIAGNOSTICS_ROLE`]). That spill owner is
/// [`crate::agent::role::DIAGNOSTICS_ROLE`] (`"diagnostics"`).
pub(crate) fn cleanup_agent_spills(agent_id: &str) {
    let mut map = SPILL_OWNERS.lock().unwrap_poison();
    let Some(paths) = map.remove(agent_id) else {
        return;
    };
    for p in paths {
        let _ = if p.is_dir() {
            std::fs::remove_dir_all(&p)
        } else {
            std::fs::remove_file(&p)
        };
    }
}

// ── Pipeline functions ────────────────────────────────────────────────

/// Quote-tracking state machine. Returns `true` when `c` is outside quotes
/// and should be examined for shell operators or redirect patterns.
///
/// This function tracks ONLY quote state — escape handling is the caller's
/// responsibility. Most callers should use [`track_char_context`] instead,
/// which combines both escape and quote tracking.
const fn check_outside_quotes(c: char, in_single: &mut bool, in_double: &mut bool) -> bool {
    match c {
        '\'' if !*in_double => {
            *in_single = !*in_single;
            false
        }
        '"' if !*in_single => {
            *in_double = !*in_double;
            false
        }
        _ => !*in_single && !*in_double,
    }
}

/// Combined escape and quote tracking for shell command scanning.
///
/// Handles backslash escaping (with the `escaped` flag) and quote state
/// transitions (via [`check_outside_quotes`]). Returns `true` when `c` is
/// a normal unescaped character outside quotes that the caller should
/// examine for shell operators or redirect patterns. Returns `false` when:
///
/// * `c` was preceded by an escape backslash (the `escaped` flag was set)
/// * `c` is itself a backslash starting an escape
/// * `c` is a quote character or inside quotes
///
/// After a `false` return, the caller may still need to push the character
/// to an output buffer (e.g., [`super::scan::strip_heredoc_bodies`]
/// preserves the command string for redirect scanning, while the token
/// classifier simply continues without pushing).
///
/// # Known limitation
///
/// Inside double quotes, `\` should only escape `\`, `$`, `` ` ``, `"`, and
/// newline in a real shell. This function treats any backslash inside double
/// quotes as an escape, which is acceptable for redirect detection: a quoted
/// redirect operator is harmless, and an escaped actual redirect would be a
/// false negative (allow), also harmless.
const fn track_char_context(
    c: char,
    in_single: &mut bool,
    in_double: &mut bool,
    escaped: &mut bool,
) -> bool {
    if *escaped {
        *escaped = false;
        return false;
    }
    if c == '\\' && !*in_single {
        *escaped = true;
        return false;
    }
    check_outside_quotes(c, in_single, in_double)
}

/// Consume a `$(...)` or backtick command substitution (delimiters included)
/// into `current` when `c` starts one; returns whether one was consumed.
/// Escape- and quote-aware via [`track_char_context`]: separators inside the
/// body are substitution content, not command separators — mis-splitting
/// flips `is_chained` in [`process_shell_output`] and disables
/// standalone-only output transforms. Paren depth mirrors
/// scan::find_paren_close.
fn consume_substitution(
    c: char,
    chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
    current: &mut String,
) -> bool {
    if c == '$' && chars.peek() == Some(&'(') {
        current.push(c);
        current.push(chars.next().expect("peeked '('"));
        let mut depth = 1usize;
        let mut sub_single = false;
        let mut sub_double = false;
        let mut sub_escaped = false;
        for c2 in chars.by_ref() {
            current.push(c2);
            if !track_char_context(c2, &mut sub_single, &mut sub_double, &mut sub_escaped) {
                continue;
            }
            // Every unquoted paren nests — mirrors scan::find_paren_close.
            if c2 == '(' {
                depth += 1;
            } else if c2 == ')' {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
        }
        return true;
    }
    if c == '`' {
        current.push(c);
        let mut sub_escaped = false;
        for c2 in chars.by_ref() {
            current.push(c2);
            if sub_escaped {
                sub_escaped = false;
            } else if c2 == '\\' {
                sub_escaped = true;
            } else if c2 == '`' {
                break;
            }
        }
        return true;
    }
    false
}

/// Split a shell command string into logical segments at shell operators
/// (quote- and substitution-aware, newlines separate, heredoc bodies
/// stripped first). Mis-splitting flips `is_chained` in
/// [`process_shell_output`] and disables standalone-only output transforms.
fn extract_command_segments(command: &str) -> Vec<String> {
    // Heredoc bodies are excluded from command scanning (see the read-only
    // shell guard contract): body text must never be segmented
    // as commands, and redirect operators inside bodies must not be scanned.
    let scan = scan::strip_heredoc_bodies(command);
    segment_command(&scan, SegmentMode::Profile)
        .expect("profile segmentation never errors")
        .into_iter()
        .map(|(seg, _)| seg)
        .collect()
}

/// Splitting policy of the shared segmenter core ([`segment_command`]): the
/// profile-selection and grep-interception splitters had already drifted
/// apart silently (backslash handling); both run this core, and the divergence
/// is these policies plus, in grep mode, `sh`'s bare-`&` separator and its
/// unquoted-`#` comment. Unifying them is a separate decision.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum SegmentMode {
    /// Empty segments silently skipped; backslash dropped before ordinary chars.
    Profile,
    /// Empty segments before a connector are syntax errors, except blank
    /// lines and `;;` case-arm terminators; backslash always preserved; an
    /// unquoted `#` opening a word comments out the rest of its line (see the
    /// arm).
    Grep,
}

/// Empty-segment handling at a flush: skip (profile) or hard error (grep).
/// Grep's blank-line and case-`;;` allowances are structural, not policy
/// variants: the `\n` flush skips; the `;` arm consumes the second `;`.
#[derive(Clone, Copy)]
enum EmptySegPolicy {
    Skip,
    Error,
}

/// Escape-sensitive chars for the profile backslash policy: preserved so
/// downstream scans see escaped operators, not real ones.
const fn is_escape_sensitive(c: char) -> bool {
    matches!(
        c,
        '\\' | '\'' | '"' | '>' | '<' | '&' | '|' | ';' | '$' | '`'
    )
}

/// True when the raw text accumulated for the current segment ends where a word
/// could open — nothing yet, or an unescaped whitespace. `\ ` is an escaped
/// space and stays inside its word, so the backslash run before the whitespace
/// decides; quotes need no handling here (a closing quote is not whitespace, so
/// `f" "#c` counts as mid-word, as `sh` reads it).
fn at_word_start(segment: &str) -> bool {
    match segment.chars().next_back() {
        None => true,
        Some(c) if !c.is_whitespace() => false,
        Some(_) => segment
            .chars()
            .rev()
            .skip(1)
            .take_while(|c| *c == '\\')
            .count()
            .is_multiple_of(2),
    }
}

/// True when `keyword` (e.g. `case` when opening, `esac` when closing a
/// `case` statement) appears in command position: first word of the segment,
/// or second after a block keyword that introduces commands.
fn segment_command_word(segment: &str, keyword: &str) -> bool {
    let mut words = segment.split_whitespace();
    match words.next() {
        Some(w) if w == keyword => true,
        Some("do" | "then" | "else" | "elif" | "if") => words.next() == Some(keyword),
        _ => false,
    }
}

/// Shared quote/substitution-aware segmenter core: split an already-heredoc-
/// stripped command into (segment, connector) pairs. Grep mode also reads
/// `sh`'s bare `&` as the separator it is (`&>` and a `>&` dup stay inside
/// their token) and its unquoted `#` as the comment it is (dropped with
/// everything inside it, to the end of its line); the profile splitter sees
/// both as ordinary text. Returns `None` when a connector follows an empty
/// segment in a mode that errors on it (grep; blank-line and case-arm `;;`
/// exceptions apply).
#[expect(clippy::too_many_lines)] // quote/substitution state machine
pub(super) fn segment_command(command: &str, mode: SegmentMode) -> Option<Vec<(String, String)>> {
    let mut out: Vec<(String, String)> = Vec::new();
    let mut current = String::new();
    let mut in_single = false;
    let mut in_double = false;
    let mut in_case = false;
    let mut chars = command.chars().peekable();

    let flush = |current: &mut String,
                 out: &mut Vec<(String, String)>,
                 conn: &str,
                 policy: EmptySegPolicy,
                 in_case: &mut bool|
     -> bool {
        let t = current.trim();
        let pushed = !t.is_empty();
        if pushed {
            out.push((t.to_string(), conn.to_string()));
            *in_case =
                segment_command_word(t, "case") || (*in_case && !segment_command_word(t, "esac"));
        }
        current.clear();
        pushed || matches!(policy, EmptySegPolicy::Skip)
    };

    let base = match mode {
        SegmentMode::Profile => EmptySegPolicy::Skip,
        SegmentMode::Grep => EmptySegPolicy::Error,
    };

    while let Some(c) = chars.next() {
        if c == '\\' && !in_single {
            match chars.next() {
                Some('\n') => continue,
                // Profile drops the backslash before ordinary chars; grep
                // always preserves both (dropping `\*` makes a shell glob).
                Some(next) if mode == SegmentMode::Profile && !is_escape_sensitive(next) => {
                    current.push(next);
                }
                Some(next) => {
                    current.push('\\');
                    current.push(next);
                }
                None => current.push('\\'),
            }
            continue;
        }

        if check_outside_quotes(c, &mut in_single, &mut in_double) {
            if consume_substitution(c, &mut chars, &mut current) {
                continue;
            }
            match c {
                '&' if chars.peek() == Some(&'&') => {
                    chars.next();
                    if !flush(&mut current, &mut out, "&&", base, &mut in_case) {
                        return None;
                    }
                    continue;
                }
                // An unquoted `<`/`>` keeps a glued `&` inside its token: `>&`
                // and `<&` are one fd-dup operator each (`2>&1`, `<&2`,
                // `2<&1`) and must not split at that `&`. Only that `&` is
                // consumed: every other character — a second `<`/`>`, a pipe —
                // still takes the path it took before.
                '<' | '>' if mode == SegmentMode::Grep => {
                    current.push(c);
                    if chars.peek() == Some(&'&') {
                        current.push(chars.next().expect("peeked `&`"));
                    }
                    continue;
                }
                // A bare `&` backgrounds the command before it — `sh`'s own
                // separator, like `;` but asynchronous. Everything after it
                // belongs to the next command and must survive the rewrite
                // verbatim. `&>` is the bash redirect operator, not a
                // backgrounding, and stays inside its token.
                '&' if mode == SegmentMode::Grep && chars.peek() != Some(&'>') => {
                    if !flush(&mut current, &mut out, "&", base, &mut in_case) {
                        return None;
                    }
                    continue;
                }
                // `>|` is one compound redirect, not a pipe (bare `>` misread).
                '|' if current.trim_end().ends_with('>') => {
                    current.push(c);
                    continue;
                }
                '|' => {
                    // `|&` is one connector in grep mode; profile splits at `|`.
                    if mode == SegmentMode::Grep && chars.peek() == Some(&'&') {
                        chars.next();
                        if !flush(&mut current, &mut out, "|&", base, &mut in_case) {
                            return None;
                        }
                    } else if chars.peek() == Some(&'|') {
                        chars.next();
                        if !flush(&mut current, &mut out, "||", base, &mut in_case) {
                            return None;
                        }
                    } else if !flush(&mut current, &mut out, "|", base, &mut in_case) {
                        return None;
                    }
                    continue;
                }
                // Newlines separate commands; blank lines stay valid sh
                // (grep's blank-line exception: this flush always skips).
                '\n' => {
                    flush(
                        &mut current,
                        &mut out,
                        "\n",
                        EmptySegPolicy::Skip,
                        &mut in_case,
                    );
                    continue;
                }
                ';' => {
                    if !flush(&mut current, &mut out, ";", base, &mut in_case) {
                        return None;
                    }
                    // Case-arm `;;` (grep): consume the second `;` so no empty
                    // flush happens for it. Outside a case, `;;` errors in grep
                    // mode and is silently skipped in profile mode.
                    if mode == SegmentMode::Grep && in_case && chars.peek() == Some(&';') {
                        chars.next();
                    }
                    continue;
                }
                // An unquoted `#` opening a word starts `sh`'s comment, which
                // ends at the newline. The comment text is dropped with
                // everything inside it (`&`, `;` and `|` are ordinary characters
                // there, and a search spelled after it never runs), and the
                // line's own connector is that newline, so the lines below are
                // still segmented — and served.
                '#' if mode == SegmentMode::Grep && at_word_start(&current) => {
                    let _ = chars.find(|c| *c == '\n');
                    if !flush(
                        &mut current,
                        &mut out,
                        "\n",
                        EmptySegPolicy::Skip,
                        &mut in_case,
                    ) {
                        return None;
                    }
                    continue;
                }
                _ => {}
            }
        }
        current.push(c);
    }
    flush(
        &mut current,
        &mut out,
        "",
        EmptySegPolicy::Skip,
        &mut in_case,
    );
    // Trailing pipe/`&&`/`||` would silently drop an empty member into a
    // VALID executed pipeline — fail closed (grep policy only).
    if mode == SegmentMode::Grep
        && matches!(
            out.last().map(|(_, c)| c.as_str()),
            Some("|" | "|&" | "||" | "&&")
        )
    {
        return None;
    }
    Some(out)
}

/// Find the index of the first non-flag word in a slice, skipping:
/// - Git global flags (and their values) when `is_git` is true
/// - Cargo toolchain specifiers (`+nightly`-style) when not git
/// - Stderr-capture suffixes (`2>&1`, `1>&2`) — never a subcommand
/// - Any word starting with `-`
///
/// Shared helper used by [`canonical_command`] and `extract_git_subcommand`
/// to avoid duplicating the flag-skipping loop. The toolchain/stderr-capture
/// skipping fixes the subcommand-resolution bugs where `cargo +nightly build`
/// or `git --version 2>&1` parsed the toolchain/suffix as the subcommand
/// (guard contract, resolved).
pub(super) fn find_first_non_flag_index(words: &[&str], is_git: bool) -> Option<usize> {
    let mut i = 0;
    while i < words.len() {
        let w = words[i];
        if is_git && GIT_GLOBAL_FLAGS.contains(&w) {
            i += 2; // skip flag and its value (safe: loop condition checks len)
            continue;
        }
        // Toolchain specifiers (`+nightly`, `+stable`) — cargo only.
        if !is_git && w.starts_with('+') {
            i += 1;
            continue;
        }
        // Stderr-capture suffixes (`2>&1`, `1>&2`) are not subcommands.
        if w == "2>&1" || w == "1>&2" {
            i += 1;
            continue;
        }
        if w.starts_with('-') {
            i += 1;
            continue;
        }
        return Some(i);
    }
    None
}

/// Find the index of the first word that is a command (not a shell prefix,
/// flag, or environment variable assignment).
///
/// Shared helper used by [`first_command_word`] and [`canonical_command`]
/// to avoid duplicating the scanning logic. A balanced-quoted word (`"env"`,
/// `'sudo'`) names the same program — it is normalized before the prefix
/// match so `"env" "t"ouch` resolves to `touch` instead of being masked as
/// an unknown quoted `env` (fail-closed blocklist dispatch). Env assignments
/// are matched the same way (`"TMPDIR=/tmp"` is an assignment), so `export
/// "TMPDIR=/tmp"` has no command word and `"TMPDIR=/tmp" cmd` resolves to
/// `cmd`. Note this also feeds profile selection (`"env" ls` classifies as
/// the ls profile), which is directionally more correct for exotic
/// quoted-prefix spellings.
pub(super) fn find_first_command_word_index(words: &[&str]) -> Option<usize> {
    words.iter().position(|w| {
        let u = scan::strip_quoted_word(w);
        !SHELL_PREFIXES.contains(&u) && !w.starts_with('-') && !is_env_assignment(u)
    })
}

/// Extract the first command word index, basename, and the split words
/// from a shell segment.
///
/// Trims the segment, splits on whitespace keeping `$(...)`/backtick
/// substitutions whole (bash treats them as ONE word — a plain split would
/// shift the command word onto a substitution's inner word and skip the
/// mutator/git/cargo dispatch), finds the first non-prefix/non-flag/non-env
/// word index via [`find_first_command_word_index`], and extracts the
/// basename from it (see [`command_word_basename`]). Returns `None` when no
/// command word is found (e.g., only prefixes/flags/env assignments).
fn command_word_from_segment(segment: &str) -> Option<(usize, &str, Vec<&str>)> {
    let trimmed = segment.trim();
    let words = scan::split_words_keeping_substitutions(trimmed);
    let idx = find_first_command_word_index(&words)?;
    Some((idx, command_word_basename(words[idx]), words))
}

/// Basename of a command word, for the blocklist/git/profile dispatch.
///
/// Balanced quotes are not part of the name, so the split runs on the literal
/// spelling rather than the raw one — otherwise the split leaves a stray quote
/// in the basename (`'/opt/mahbot/bin/mahbot'` → `mahbot'`) and the verb
/// classifiers read the result as unprovable. An unprovable word keeps its raw
/// spelling: it is no literal name anyway, and the guard resolves a variable
/// command word by exact spelling (`"$BIN"` must stay `"$BIN"`).
pub(super) fn command_word_basename(word: &str) -> &str {
    // Unix-only, like the classifier arm this consumes (see
    // `classify_verb_word`): elsewhere the raw spelling is split, as before.
    #[cfg(unix)]
    let word = match readonly::classify_verb_word(word) {
        readonly::VerbClass::Literal(content) => content,
        readonly::VerbClass::Unprovable => word,
    };
    word.rsplit('/')
        .next()
        .expect("rsplit always yields at least one element")
}

/// Extract just the first command word (basename) from a shell segment.
///
/// Strips shell prefixes, environment variable assignments (`KEY=value`), and
/// absolute paths, but stops before any subcommand detection. This is the
/// lightweight alternative to [`canonical_command`] for callers that only need
/// the command name (e.g., the read-only guard's verb dispatch).
pub(super) fn first_command_word(segment: &str) -> &str {
    let Some((_, cmd, _)) = command_word_from_segment(segment) else {
        return "";
    };
    cmd
}

/// Extract a canonical command key from a shell segment for profile matching.
///
/// Strips shell prefixes, environment variable assignments (`KEY=value`),
/// absolute paths, and flags between the command and its subcommand. For git, also skips flag *values* for global flags like `-C` and
/// `-c`. For all other commands, only the flag token itself is skipped — flags
/// that take values (e.g., `cargo --profile release build`) will have their
/// value misidentified as the subcommand. This is a known limitation: the
/// returned key won't match any profile, falling through to generic filtering,
/// which is the same end state as the pre-fix behavior.
fn canonical_command(segment: &str) -> String {
    let Some((cmd_idx, cmd, words)) = command_word_from_segment(segment) else {
        return String::new();
    };

    let remaining = &words[cmd_idx + 1..];
    if remaining.is_empty() {
        return cmd.to_string();
    }

    // Skip flags between command and subcommand using shared helper
    // cmd is the bare basename (quotes stripped, then rsplit('/').next()),
    // so == comparison is safe.
    let is_git = cmd == "git";
    if let Some(sub_idx) = find_first_non_flag_index(remaining, is_git) {
        format!("{} {}", cmd, remaining[sub_idx])
    } else {
        cmd.to_string()
    }
}

/// Check if a word is a POSIX shell variable assignment (`VAR=value`).
///
/// The word must start with `[A-Za-z_]`, contain at least one `=`, and the
/// name portion (before `=`) must consist only of `[A-Za-z0-9_]`.
fn is_env_assignment(word: &str) -> bool {
    if let Some(eq_pos) = word.find('=')
        && eq_pos > 0
    {
        let prefix = &word[..eq_pos];
        return prefix
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
            && prefix
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_');
    }
    false
}

/// Select the first matching profile for a command string.
/// Returns on the first match in the first matching command segment
/// (breaks out of both segment and profile iteration early); chained
/// commands are handled by iterating over pre-parsed segments.
///
/// Profiles with `standalone_only` are skipped when `is_chained` is true,
/// so transforms that assume homogeneous output (e.g., `compact_ls`) are
/// not applied to chained commands. The command falls through to
/// `GEN_FALLBACK` with its sensible truncation defaults instead.
fn select_profile(segments: &[String], is_chained: bool) -> &'static Profile {
    for segment in segments {
        let canonical = canonical_command(segment);
        if canonical.is_empty() {
            continue;
        }
        for p in PROFILES.iter() {
            if is_chained && p.standalone_only {
                continue;
            }
            if p.match_command.is_match(&canonical) {
                return p;
            }
        }
    }
    &GEN_FALLBACK
}

/// Combine stdout with (filtered) stderr.
///
/// Returns stdout as-is when stderr is empty, regardless of exit code.
/// On success (exit 0) with `keep_stderr` patterns: only stderr lines
/// matching those patterns are appended. On success without patterns
/// (or when no stderr lines match), stderr is silently dropped.
/// On failure (non-zero exit) with `keep_stderr` patterns: the same
/// filtering is applied to avoid dumping command progress noise
/// (e.g. `Checking mahbot ...` from cargo). When no lines match,
/// the stderr section is omitted entirely. On failure without
/// patterns, all stderr is appended unconditionally.
fn combine_output(
    stdout: &str,
    stderr: &str,
    exit_code: i32,
    keep_stderr: Option<&RegexSet>,
) -> String {
    let stderr_trimmed = stderr.trim();
    if stderr_trimmed.is_empty() {
        return stdout.to_string();
    }
    // Apply keep_stderr filtering on both success and failure paths.
    let filtered = keep_stderr.and_then(|patterns| filter_keep_stderr(stderr, patterns));
    let with_stderr_section = |body: &str| {
        if stdout.is_empty() {
            format!("stderr:\n{body}")
        } else {
            format!("{stdout}\nstderr:\n{body}")
        }
    };
    match (exit_code == 0, filtered) {
        // Matching lines found — append them as a stderr section.
        (_, Some(relevant)) => with_stderr_section(&relevant),
        // Failure without keep_stderr: dump all stderr unconditionally.
        (false, None) if keep_stderr.is_none() => with_stderr_section(stderr_trimmed),
        // Success or failure with keep_stderr but no matching lines: omit stderr section.
        _ => stdout.to_string(),
    }
}

/// Filter stderr lines through `keep_stderr` patterns and join matching lines.
/// Returns `None` when no lines match.
fn filter_keep_stderr<'a>(stderr: &'a str, patterns: &RegexSet) -> Option<String> {
    let relevant: Vec<&'a str> = stderr.lines().filter(|l| patterns.is_match(l)).collect();
    if relevant.is_empty() {
        return None;
    }
    Some(relevant.join("\n"))
}

/// Shared tail: append elapsed timing (if ≥1s), then spill to file.
///
/// When `full_output_for_spill` is provided, it represents the full output
/// *before* head/tail truncation was applied. If it exceeds the spill
/// threshold, the full version is saved and a spill header is appended to
/// `combined` — this preserves complete content for agent review when
/// head/tail trimming reduces the inline view to a small snippet.
///
/// When no pre-head/tail output is available (or it's too small to spill),
/// the final `combined` output is checked against the threshold and spilled
/// if large enough, replacing the inline content with a preview.
fn finish_shell_output(
    mut combined: String,
    elapsed: Duration,
    full_output_for_spill: Option<&str>,
) -> String {
    // Both stdout and stderr are credential-scrubbed once at
    // `apply_profile_pipeline` entry, so no further scrubbing is needed
    // here.  ShellTool overrides `should_scrub_output` to return `false`,
    // disabling the agent-level scrub as redundant — the pipeline
    // guarantees scrubbing before any data reaches this function.
    if elapsed.as_secs_f64() >= 1.0 {
        let _ = write!(combined, "\n[took {:.1}s]", elapsed.as_secs_f64());
    }

    // When pre-head/tail output is available and large enough, spill the
    // fuller version so agents can `read` the complete output despite the
    // head/tail truncation reducing inline content to a snippet.
    // `full_output_for_spill` is already credential-scrubbed.
    // The `pre` value is only provided when output exceeds
    // `TOOL_OUTPUT_BUDGET_BYTES` (guaranteed by `apply_line_truncation`),
    // so no length re-check is needed here.
    if let Some(pre) = full_output_for_spill {
        debug_assert!(
            pre.len() > TOOL_OUTPUT_BUDGET_BYTES,
            "invariant: pre-truncation output ({}) must exceed threshold ({})",
            pre.len(),
            TOOL_OUTPUT_BUDGET_BYTES,
        );
        let byte_count = pre.len();
        let line_count = pre.lines().count();
        if let Some(path) = spill_output(pre) {
            let hint = format_spill_header(&path, byte_count, line_count);
            combined.push('\n');
            combined.push_str(&hint);
        }
        return combined;
    }

    // No pre-truncation spill — try spilling the final combined output
    try_spill_to_file(combined, TOOL_OUTPUT_BUDGET_BYTES)
}

/// Append `line` to `buf`, inserting a `'\n'` separator if `buf` is non-empty.
fn push_line(buf: &mut String, line: &str) {
    if !buf.is_empty() {
        buf.push('\n');
    }
    buf.push_str(line);
}

/// Collapse runs of blank lines to at most 2 consecutive.
fn collapse_blank_lines(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut blank_run = 0usize;
    for line in input.lines() {
        if line.trim().is_empty() {
            blank_run += 1;
            if blank_run > 2 {
                continue; // skip excess blank lines
            }
        } else {
            blank_run = 0;
        }
        push_line(&mut result, line);
    }
    result
}

/// State machine for processing cargo test output.
/// Drops passing test lines, captures only failure blocks + summary.
pub(super) fn filter_cargo_test_output(output: &str, exit_code: i32) -> String {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Section {
        Normal,
        InFailures,
    }

    struct CargoTestFilter {
        section: Section,
        has_failures: bool,
        has_compile_errors: bool,
        summary_lines: Vec<String>,
        output_lines: Vec<String>,
    }

    let exit_ok = exit_code == 0;

    let mut f = CargoTestFilter {
        section: Section::Normal,
        has_failures: false,
        has_compile_errors: false,
        summary_lines: Vec::new(),
        output_lines: Vec::new(),
    };

    for line in output.lines() {
        let trimmed = line.trim_start();

        // Skip compilation/download noise (Running is useful context in test output)
        if CARGO_COMPILE_PREFIXES
            .iter()
            .any(|p| *p != "Running" && trimmed.starts_with(p))
        {
            continue;
        }

        if trimmed.starts_with("test ") && trimmed.contains("... ok") {
            continue;
        }

        // Skip "running N" lines
        if trimmed.starts_with("running ") {
            continue;
        }

        // Track compile errors for fallback
        if trimmed.starts_with("error[") || trimmed.starts_with("error:") {
            f.has_compile_errors = true;
        }

        // "failures:" toggles section state
        if trimmed == "failures:" {
            f.section = Section::InFailures;
            continue;
        }

        // Capture test result summary — must remain unconditional by section.
        // The second "failures:" now stays in InFailures (no InFailureNames state),
        // so "test result:" after a failure-name list is caught here, not by the
        // InFailures block below. Adding a section guard here would break the output.
        if trimmed.starts_with("test result:") {
            f.summary_lines.push(line.to_string());
            f.section = Section::Normal;
            continue;
        }

        // In failure section — keep the block
        if f.section != Section::Normal {
            f.has_failures = true;
            f.output_lines.push(line.to_string());
            continue;
        }

        // Default: pass through (warnings, non-test output, etc.)
        f.output_lines.push(line.to_string());
    }

    // If we captured failure blocks, show them + summary
    if f.has_failures {
        let mut result = f.output_lines.join("\n");
        if !f.summary_lines.is_empty() {
            push_line(&mut result, &f.summary_lines.join("\n"));
        }
        return result;
    }

    // If there were compile errors but no test failures, show build error summary
    if f.has_compile_errors && !exit_ok {
        // Just show last 15 meaningful lines
        let lines: Vec<&str> = f
            .output_lines
            .iter()
            .map(String::as_str)
            .filter(|l| !l.trim().is_empty())
            .collect();
        let last = lines
            .iter()
            .rev()
            .take(15)
            .rev()
            .copied()
            .collect::<Vec<_>>();
        return last.join("\n");
    }

    // All passed — return just the summary
    if !f.summary_lines.is_empty() {
        return f.summary_lines.join("\n");
    }

    // Fallback: return raw output (shouldn't normally reach here)
    let result = output.to_string();
    if exit_ok && result.trim().is_empty() {
        // NOTE: This emptiness check runs before combine_output, so it only
        // considers stdout. The cargo test profile has keep_stderr: None, so
        // combine_output never appends stderr on success — the result is empty
        // too. If keep_stderr were ever added to the cargo test profile, this
        // check would produce [cargo test: ok] even when stderr contains
        // warnings, while combine_output would then append them after it.
        // That's arguably better behavior (tests passed, warnings are
        // secondary), but the coupling should be intentional.
        "[cargo test: ok]".to_string()
    } else {
        result
    }
}

/// Parse a single `ls -l` line into its listing entry. Returns `None` for the
/// `total` header, blank lines, the `.`/`..` entries, and anything that is not
/// an `ls -l` row.
fn parse_ls_line(line: &str) -> Option<ListingEntry> {
    if line.starts_with("total ") || line.trim().is_empty() {
        return None;
    }
    let mut parts = line.split_whitespace();
    let permissions = parts.next()?;
    if permissions.len() < 10
        || !(permissions.starts_with('-')
            || permissions.starts_with('d')
            || permissions.starts_with('l'))
    {
        return None;
    }
    // `l` (a link) is a file entry: a link is never grouped with directories.
    let is_dir = permissions.starts_with('d');
    parts.next(); // link count
    parts.next(); // owner
    parts.next(); // group
    // `ls -l` prints bytes, which the listing renders human-readable. A `-h`
    // listing's `1.0K` and the `?` of an entry `ls` itself could not stat are
    // already display text and pass through unchanged.
    let size = parts.next()?;
    let size = size
        .parse::<u64>()
        .ok()
        .map_or_else(|| size.to_string(), human_readable_size);
    parts.next(); // month
    parts.next(); // day
    parts.next(); // time or year
    let name = parts.collect::<Vec<_>>().join(" ").trim().to_string();
    if name.is_empty() || name == "." || name == ".." {
        return None;
    }
    // Strip symlink target
    let name = name
        .split(" -> ")
        .next()
        .expect("split always yields at least one element")
        .to_string();
    if name.is_empty() {
        return None;
    }
    Some(ListingEntry {
        name,
        is_dir,
        // A directory never carries a size (see `ListingEntry::size`).
        size: if is_dir { None } else { Some(size) },
    })
}

/// Compress `ls -l` output into the compact listing ([`format_listing`]).
///
/// Non-`-l` output (without a `total N` header) passes through unchanged.
pub(super) fn compact_ls(output: &str, _exit_code: i32) -> String {
    // If the output lacks a "total N" header, it's not in `-l` format.
    // `parse_ls_line` can only parse `-l` lines — passing non-`-l` output
    // through would trigger the "(empty)" false positive.
    if !output.lines().any(|line| line.starts_with("total ")) {
        return output.to_string();
    }

    let mut entries: Vec<ListingEntry> = Vec::new();
    let mut lines_seen = 0usize;

    for line in output.lines() {
        if line.starts_with("total ") || line.trim().is_empty() {
            continue;
        }
        lines_seen += 1;
        if let Some(entry) = parse_ls_line(line) {
            entries.push(entry);
        }
    }

    if lines_seen == 0 {
        // Only the header of an empty `-A` listing: it stays as printed.
        return output.to_string();
    }

    format_listing(&entries)
}

/// Main entry point for shell output processing.
///
/// Routes command output through the profile system: select profile → apply
/// profile pipeline → combine → finish. Custom output transforms for commands
/// like `cargo test` (state machine) and `ls` (compact parser) are handled
/// through the profile's `output_transform` field rather than as hardcoded
/// special cases.
fn process_shell_output(
    command: &str,
    stdout: &str,
    stderr: &str,
    exit_code: i32,
    elapsed: Duration,
) -> String {
    let segments = extract_command_segments(command);
    let is_chained = segments.len() > 1;
    let profile = select_profile(&segments, is_chained);
    apply_profile_pipeline(profile, stdout, stderr, exit_code, elapsed)
}

/// Apply strip_lines filter.
fn apply_strip_lines(output: &str, profile: &Profile) -> String {
    output
        .lines()
        .filter(|l| {
            if let Some(ref set) = profile.strip_lines
                && set.is_match(l)
            {
                return false;
            }
            true
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Build a head/tail sandwich with an omission marker in the middle.
///
/// `marker_verb` is the verb shown in the marker line — "omitted" for head/tail
/// sandwiches, "truncated" for the `max_lines`-only cap. It is a plain string
/// rather than an enum; a typo would silently alter tool output, which is
/// acceptable for the fixed call sites given the existing tests.
///
/// Edge cases:
/// - `head=0` (tail-only, e.g., `ping`, `gh`, `helm` profiles, and the
///   `max_lines`-only cap, which calls this as `(output, max, 0, "truncated")`):
///   no leading newline before the omission marker. A future `max_lines = 0`
///   profile would hit this path too (unreachable today — profiles.rs minimum
///   is 20) and would format the marker without a leading newline.
/// - `tail=0` (head-only, e.g., `git log` profile): no trailing newline after
///   the omission marker.
fn format_sandwich(output: &str, head: usize, tail: usize, marker_verb: &str) -> String {
    let lines: Vec<&str> = output.lines().collect();
    let total = lines.len();
    if total <= head + tail {
        return output.to_string();
    }
    let omitted = total - head - tail;

    // Build the result directly from &str slices, avoiding intermediate Vec<String> copies.
    let mut result = lines[..head].join("\n");
    if result.is_empty() {
        // head=0: no leading newline before the omission marker
        let _ = write!(result, "... ({omitted} lines {marker_verb})");
    } else {
        let _ = write!(result, "\n... ({omitted} lines {marker_verb})");
    }
    if tail > 0 {
        let _ = write!(result, "\n{}", lines[total - tail..].join("\n"));
    }
    result
}

/// Apply line truncation: head/tail sandwich (byte-gated), `max_lines`-only absolute cap, or passthrough.
///
/// Returns `(truncated_output, pre_truncation_copy)` where the copy captures the
/// full output before truncation for potential spilling by `finish_shell_output`.
/// Head/tail is gated on `TOOL_OUTPUT_BUDGET_BYTES` — small outputs are shown in full
/// regardless of configured head/tail line counts.
fn apply_line_truncation(output: &str, profile: &Profile) -> (String, Option<String>) {
    let head = profile.head_lines.unwrap_or(0);
    let tail = profile.tail_lines.unwrap_or(0);
    let max = profile.max_lines;

    // Fast path: no truncation configured at all
    if head == 0 && tail == 0 && max.is_none() {
        return (output.to_string(), None);
    }

    let line_count = output.lines().count();

    // Capture pre-truncation output for spilling — only when head/tail
    // actually truncates (byte threshold exceeded + would reduce lines).
    let should_sandwich = (head > 0 || tail > 0)
        && line_count > head + tail
        && output.len() > TOOL_OUTPUT_BUDGET_BYTES;

    let pre_truncation = if should_sandwich {
        Some(output.to_string())
    } else {
        None
    };

    // Single-pass truncation:
    // 1. Head/tail sandwich (byte-gated), OR
    // 2. max_lines-only absolute cap (head-only sandwich with "truncated" verb), OR
    // 3. passthrough.
    let result = if should_sandwich {
        format_sandwich(output, head, tail, "omitted")
    } else if let Some(max) = max {
        format_sandwich(output, max, 0, "truncated")
    } else {
        output.to_string()
    };

    // Invariant: head+tail+1 <= max_lines — guaranteed by profile configs.
    debug_assert!(
        !should_sandwich || max.is_none_or(|m| result.lines().count() <= m),
        "sandwich result ({}) exceeds max_lines ({:?}) — profile invariant violated",
        result.lines().count(),
        max,
    );

    (result, pre_truncation)
}

/// Run the full profile-based processing pipeline on pre-processed output.
///
/// Upstream processing (`execute()`) handles ANSI stripping, and the pipe read
/// cap (`SHELL_PIPE_READ_CAP`, 256 KB) bounds output collected during execution.
/// Both stdout and stderr are scrubbed once at pipeline entry so all paths
/// (early-return and main) consistently receive clean data.  No further
/// scrubbing is needed anywhere downstream — all derived output (truncated,
/// pre-head/tail for spill, on_empty messages) originates
/// from this single scrubbed source.
///
/// Early-return stages (on_empty) call `combine_output` only.  The main path continues through `combine_output` →
/// `finish_shell_output` (timing, spill-to-file).  `TOOL_OUTPUT_BUDGET_BYTES`
/// (5 KB) gates the head/tail truncation and spill preview — it is a trigger,
/// not a truncation cutoff.  `finish_shell_output` → `try_spill_to_file`'s
/// use of `crate::util::truncate_tool_output` (5 KB head+tail) provides a final
/// safety net for output that still exceeds the threshold after all pipeline
/// stages.
///
/// Stages: line filters, collapse, truncate, line_truncation,
///         on_empty, output_transform.
fn apply_profile_pipeline(
    profile: &Profile,
    output: &str,
    stderr: &str,
    exit_code: i32,
    elapsed: Duration,
) -> String {
    // Scrub both stdout and stderr once at pipeline entry so all
    // downstream paths (on_empty, main) uniformly receive clean
    // data.  Scrubbing before keep_stderr filtering means credential
    // lines that matched keep_stderr patterns will be dropped entirely
    // because the redacted version no longer matches — this is acceptable
    // since credentials should never appear in output.  No further
    // credential scrubbing is needed anywhere in the pipeline; all
    // derived data (truncated output, spill output) originates from
    // this single scrubbed source.
    let stderr = scrub_credentials(stderr);
    let output = scrub_credentials(output);

    // Local closure capturing the trailing combine_output arguments (stderr,
    // exit_code, keep_stderr) to reduce repetition across all call sites.
    // Output is already scrubbed at pipeline entry.
    let combine =
        |output: &str| combine_output(output, &stderr, exit_code, profile.keep_stderr.as_ref());

    // Stage 1: strip lines
    let mut processed = apply_strip_lines(&output, profile);

    // Stage 2: collapse blank lines (runs >2 → 2).
    processed = collapse_blank_lines(&processed);

    // Stage 3: truncate long lines
    if let Some(max) = profile.max_line_len {
        processed = truncate_line_width(&processed, max);
    }

    // Stage 4: line truncation (head/tail + max_lines).
    // Returns pre-truncation output for spilling by finish_shell_output,
    // so the complete content remains accessible even when truncation
    // reduces the inline view to a snippet.
    let (truncated, pre_head_tail) = apply_line_truncation(&processed, profile);
    processed = truncated;

    // Stage 5: on_empty — fallback when all output stripped
    if processed.trim().is_empty()
        && let Some(msg) = profile.on_empty
    {
        // When on_fail_msg is set, use it (fully replacing the message
        // including the "(failed)" suffix) to avoid contradictory output
        // like "[cargo clippy: ok] (failed)".
        if exit_code != 0
            && let Some(fail_msg) = profile.on_fail_msg
        {
            let secs = elapsed.as_secs_f64();
            return combine(&format!("{fail_msg} ({secs:.1}s)"));
        }
        let exit_note = if exit_code == 0 { "" } else { " (failed)" };
        let secs = elapsed.as_secs_f64();
        return combine(&format!("{msg}{exit_note} ({secs:.1}s)"));
    }

    // Stage 6: output transform — replaces processed output before combine/finish.
    // This allows profiles to apply custom transformations (e.g., cargo test state
    // machine, ls compaction) that operate on the full output after standard
    // line-level processing has been applied.
    // `standalone_only` profiles are already skipped at profile-selection time
    // for chained commands, so the transform here is always applicable.
    if let Some(transform) = profile.output_transform {
        processed = transform(&processed, exit_code);
    }

    let combined = combine(&processed);
    finish_shell_output(combined, elapsed, pre_head_tail.as_deref())
}

/// Decode raw shell output bytes into text ([`windows_text::decode`]: this
/// platform's own reading of a program's output) and strip ANSI escape
/// sequences.
///
/// This is the first step before further processing such as credential scrubbing
/// ([`strip_and_scrub`]).
fn decode_and_strip_ansi(data: &[u8]) -> String {
    strip_ansi_escapes(&windows_text::decode(data))
}

/// Read a file the product itself had a program write — a background session's
/// output file, the one such file an agent reads back through the read tool —
/// the way the shell reads a program's output ([`windows_text::decode`]).
///
/// `None` for every other path, so the read tool keeps its own reading for the
/// files an agent or the owner points it at: only a path named like the product's
/// own output is a program's output here ([`bg::is_output_file`]).
pub(crate) fn decode_session_output(path: &Path, bytes: &[u8]) -> Option<String> {
    bg::is_output_file(path).then(|| windows_text::decode(bytes))
}

/// Format the tool-facing exit-status note: `[exit status: N]`, or
/// `[exit status: terminated by signal]` when the process was killed by a
/// signal (exit code `None`). Shared by the foreground and background paths
/// so the two renderings cannot drift.
pub(super) fn format_exit_status_note(exit_code: Option<i32>) -> String {
    match exit_code {
        Some(c) => format!("[exit status: {c}]"),
        None => "[exit status: terminated by signal]".to_string(),
    }
}

/// Decode raw shell output bytes ([`decode_and_strip_ansi`]'s reading), strip
/// ANSI escape sequences, then scrub credentials.
///
/// Builds on [`decode_and_strip_ansi`] by additionally applying credential
/// scrubbing. Use this whenever you need to process raw shell bytes into
/// display-safe text.
fn strip_and_scrub(data: &[u8]) -> String {
    scrub_credentials(&decode_and_strip_ansi(data))
}

/// Truncate any single line exceeding `max_line_len` with a note.
fn truncate_line_width(input: &str, max_line_len: usize) -> String {
    let mut result = String::with_capacity(input.len());
    for line in input.lines() {
        if line.len() > max_line_len {
            let cut = line.floor_char_boundary(max_line_len);
            push_line(&mut result, &line[..cut]);
            let _ = write!(
                result,
                "\n... ({} more chars on this line)",
                line[cut..].chars().count()
            );
        } else {
            push_line(&mut result, line);
        }
    }
    result
}

/// Format the spill file header line shared by all spill hint producers.
fn format_spill_header(path: &Path, byte_count: usize, line_count: usize) -> String {
    format!(
        "[Output saved to {} ({} bytes, {} lines)]\n\
         [view with: read {}]\n",
        path.display(),
        byte_count,
        line_count,
        path.display(),
    )
}

/// Build a head/tail preview for large output that was spilled to a file.
fn format_spill_preview(output: &str, path: &Path) -> String {
    let line_count = output.lines().count();
    let byte_count = output.len();
    let header = format_spill_header(path, byte_count, line_count);
    format!("{header}{}", format_sandwich(output, 5, 5, "omitted"))
}

/// Write content to the agent temp directory with the given filename.
/// Content should already be credential-scrubbed. The path is recorded under
/// the owning agent id (owner-deletes-at-end).
fn write_to_spill(content: &str, filename: &str) -> Option<std::path::PathBuf> {
    let dir = agent_temp_dir()?;
    let path = dir.join(filename);
    std::fs::write(&path, content).ok()?;
    record_spill_owner(path.clone());
    Some(path)
}

/// Write pre-scrubbed output to a random spill file.
/// Caller is responsible for scrubbing credentials before calling this function.
fn spill_output(output: &str) -> Option<std::path::PathBuf> {
    let filename = crate::tools::path::format_spill_filename();
    write_to_spill(output, &filename)
}

/// If output exceeds threshold, spill to a temp file and return a preview.
/// The full output is saved to a file; the inline preview is a short summary.
///
/// Reused by read-only tools (e.g. [`crate::tools::mahbot_debug`]) to keep
/// large result sets out of the LLM context while still making them available
/// on demand via the read path.
pub(crate) fn try_spill_to_file(output: String, threshold_bytes: usize) -> String {
    if output.len() <= threshold_bytes {
        return output;
    }

    match spill_output(&output) {
        Some(path) => format_spill_preview(&output, &path),
        None => crate::util::truncate_tool_output(&output),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::workspace::test_ws;
    use tempfile::TempDir;

    #[cfg(unix)]
    use crate::util::test::env_lock;
    use crate::util::test::set_env_var;

    // ── Table-driven test helpers ─────────────────────────────────────
    // These helpers reduce boilerplate for process_shell_output and
    // filter_cargo_test_output test groups. Each case carries its own
    // assertions (contains, not_contains, eq) with a descriptive name
    // so test failures show exactly which scenario broke.

    /// Shared assertion helper: verify that all `contains` strings are present
    /// and all `not_contains` strings are absent in `result`.
    fn assert_contains_not_contains(
        name: &str,
        result: &str,
        contains: &[&str],
        not_contains: &[&str],
    ) {
        for &s in contains {
            assert!(
                result.contains(s),
                "[{name}] expected contains {s:?}\n  got: {result:?}",
            );
        }
        for &s in not_contains {
            assert!(
                !result.contains(s),
                "[{name}] expected NOT contains {s:?}\n  got: {result:?}",
            );
        }
    }

    /// A test case for [`process_shell_output`] with multi-assertion support.
    #[derive(Default)]
    struct ShellOutputCase {
        /// Human-readable name for failure diagnostics.
        name: &'static str,
        /// Canonical/shell command string passed to select_profile.
        command: &'static str,
        stdout: &'static str,
        /// Stderr input. Default: `""`.
        stderr: &'static str,
        /// Exit code. Default: `0`.
        exit_code: i32,
        /// Elapsed time in seconds. Default: `0.0`.
        elapsed_secs: f64,
        /// Strings that must all be present in the output.
        contains: &'static [&'static str],
        /// Strings that must all be absent from the output.
        not_contains: &'static [&'static str],
        /// If set, asserts `result.trim() == eq` (leading/trailing whitespace
        /// is stripped before comparison).
        eq: Option<&'static str>,
    }

    #[derive(Default)]
    /// A test case for [`filter_cargo_test_output`].
    struct CargoTestFilterCase {
        /// Human-readable name for failure diagnostics.
        name: &'static str,
        output: &'static str,
        exit_code: i32,
        contains: &'static [&'static str],
        not_contains: &'static [&'static str],
    }

    /// Run [`process_shell_output`] for each case and assert expectations.
    ///
    /// `contains` and `not_contains` are checked against the raw result.
    /// `eq` (if set) compares against `result.trim()` — leading/trailing
    /// whitespace is stripped, consistent with how profiles produce
    /// on_empty messages (e.g. `"[cargo test: ok]"`).
    fn check_shell_output(cases: &[ShellOutputCase]) {
        for case in cases {
            let result = process_shell_output(
                case.command,
                case.stdout,
                case.stderr,
                case.exit_code,
                Duration::from_secs_f64(case.elapsed_secs),
            );
            assert_contains_not_contains(case.name, &result, case.contains, case.not_contains);
            if let Some(expected) = case.eq {
                assert_eq!(
                    result.trim(),
                    expected,
                    "[{}] expected eq {expected:?}",
                    case.name,
                );
            }
        }
    }

    /// Run [`filter_cargo_test_output`] for each case and assert expectations.
    fn check_cargo_test_filter(cases: &[CargoTestFilterCase]) {
        for case in cases {
            let result = filter_cargo_test_output(case.output, case.exit_code);
            assert_contains_not_contains(case.name, &result, case.contains, case.not_contains);
        }
    }

    // ── Consolidated table-driven tests ───────────────────────────────
    //
    // Each `_cases` function replaces multiple individual test functions
    // that followed the same pattern (call process_shell_output →
    // assert contains/not_contains). Adding a new scenario is a single
    // struct literal with a descriptive name.

    #[test]
    fn cargo_test_filter_cases() {
        // Cargo test output filter state machine — consolidated table.
        let cases: &[CargoTestFilterCase] = &[
            CargoTestFilterCase {
                name: "failure block captures failures and panic message",
                output: "\n\
                    Compiling foo v1.0.0\n\
                    test test1 ... ok\n\
                    test test2 ... FAILED\n\
                    \n\
                    failures:\n\
                    \n\
                    ---- test2 stdout ----\n\
                    thread 'test2' panicked at src/lib.rs:42:\n\
                    assertion failed\n\
                    \n\
                    \n\
                    failures:\n\
                    test2\n\
                    \n\
                    test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\n\
                ",
                exit_code: 1,
                contains: &["test2 ... FAILED", "assertion failed", "test result:"],
                not_contains: &["Compiling", "test1 ... ok"],
            },
            CargoTestFilterCase {
                name: "all pass returns summary",
                output: "\
                    Compiling foo v1.0.0\n\
                    Checking bar v2.0.0\n\
                    test test1 ... ok\n\
                    test test2 ... ok\n\
                    \n\
                    test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n\
                ",
                exit_code: 0,
                contains: &["test result:"],
                not_contains: &["Compiling", "Checking", "test1 ... ok", "test2 ... ok"],
            },
            CargoTestFilterCase {
                name: "compile error fallback preserves errors",
                output: "\
                    Compiling foo v1.0.0\n\
                    error[E0425]: cannot find value `bar` in this scope\n\
                     --> src/lib.rs:1:5\n\
                    \n\
                    error: could not compile `foo` due to 1 previous error\n\
                ",
                exit_code: 1,
                contains: &["error[E0425]", "could not compile"],
                not_contains: &["Compiling"],
            },
            CargoTestFilterCase {
                name: "Running preserved in test output",
                output: "\
                    Compiling foo v1.0.0\n\
                    Running unittests src/lib.rs\n\
                    test test1 ... ok\n\
                    test test2 ... FAILED\n\
                    \n\
                    failures:\n\
                    \n\
                    ---- test2 stdout ----\n\
                    assertion failed\n\
                    \n\
                    failures:\n\
                    test2\n\
                    \n\
                    test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\n\
                ",
                exit_code: 1,
                contains: &["Running unittests", "test2 ... FAILED", "test result:"],
                not_contains: &["Compiling"],
            },
        ];
        check_cargo_test_filter(cases);
    }

    #[expect(clippy::too_many_lines)]
    #[test]
    fn profile_selection_cases() {
        // Profile selection/dispatch tests — consolidated table.
        // Includes detection of correct profiles from canonical commands,
        // fallback behavior for unknown/builtin-only commands, and chained
        // command dispatch that selects the first matching segment.
        let cases: &[ShellOutputCase] = &[
            ShellOutputCase {
                name: "cargo --release test triggers state machine",
                command: "cargo --release test",
                eq: Some("[cargo test: ok]"),
                ..Default::default()
            },
            ShellOutputCase {
                name: "git -C /repo diff triggers git diff on_empty",
                command: "git -C /repo diff",
                contains: &["no changes"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "unknown tool falls through to generic",
                command: "some_obscure_tool --flag",
                stdout: "some\nrandom\noutput\n",
                contains: &["some", "output"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "empty command uses fallback",
                command: "",
                stdout: "hello world",
                contains: &["hello"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "builtins-only falls through to generic",
                command: "cd .. && cd /tmp",
                stdout: "some output",
                contains: &["some output"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "chained command selects first matching profile (pnpm install)",
                command: "cd frontend && pnpm install && pnpm build",
                stdout: "Already up to date\nsome output\n",
                not_contains: &["Already up to date"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "chained cargo test falls through to GEN_FALLBACK",
                command: "cd project && cargo test",
                stdout: "Compiling foo v1.0.0\ntest test1 ... ok\ntest test2 ... FAILED\n\nfailures:\n\n---- test2 stdout ----\npanic!\n\nfailures:\n    test2\n\ntest result: FAILED. 1 passed; 1 failed\n",
                exit_code: 1,
                contains: &["test2 ... FAILED", "Compiling", "test1 ... ok"],
                ..Default::default()
            },
            // Regression: chained cargo test with compile errors and exit_code=0
            // must NOT produce the misleading "[cargo test: ok]".
            ShellOutputCase {
                name: "chained cargo test compile error regression",
                command: "cargo test --lib || true",
                stdout: "",
                stderr: "error[E0425]: cannot find value `x` in this scope\n  --> src/lib.rs:2:21\n   |\n2 |     let y = x + 1;\n   |             ^ not found in this scope\n",
                exit_code: 0,
                not_contains: &["[cargo test: ok]"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "chained git log preserves content",
                command: "cd repo && git log --oneline",
                stdout: "commit abc123\nAuthor: test\nDate:   Mon Jan 1\n\n    initial commit\n",
                contains: &["commit", "Author"],
                ..Default::default()
            },
            // ── Multi-line commands (newline = command separator) ─────────
            // Regression: newline splitting in the shared
            // extract_command_segments changes is_chained, which disables
            // standalone_only output transforms (compact_ls, cargo test state
            // machine) for multi-line commands. Raw output must pass through.
            ShellOutputCase {
                name: "multi-line ls skips compact_ls (newline = chained)",
                command: "ls -la\ncat README.md",
                stdout: "total 8\n-rw-r--r--  1 user  group  2048 May 21 10:00 file.txt\n",
                contains: &["total 8", "file.txt"],
                not_contains: &["Summary:"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "multi-line cargo test skips state machine",
                command: "cargo test --lib\ncat notes.txt",
                stdout: "Compiling foo v1.0.0\ntest test1 ... ok\ntest result: ok. 1 passed; 1 failed\n",
                contains: &["Compiling foo", "test1 ... ok", "test result:"],
                not_contains: &["[cargo test: ok]"],
                ..Default::default()
            },
            // Heredoc bodies are removed before segmentation, so a heredoc
            // command stays a single segment and keeps its profile (the cargo
            // test state machine still applies — it is not skipped as chained).
            ShellOutputCase {
                name: "heredoc command stays single segment for profile selection",
                command: "cargo test --lib <<EOF\nbody\nEOF",
                stdout: "test test1 ... ok\ntest result: ok. 1 passed; 0 failed\n",
                eq: Some("test result: ok. 1 passed; 0 failed"),
                ..Default::default()
            },
            // Regression: a heredoc whose UNQUOTED body contains a
            // command substitution emits that substitution as its own segment
            // (it must remain scanned — bash executes `$()` in unquoted
            // bodies), so the command becomes chained and standalone-only
            // profiles (the cargo test state machine) are skipped.
            ShellOutputCase {
                name: "heredoc with substitution body becomes chained",
                command: "cargo test --lib <<EOF\n$(echo hi)\nEOF",
                stdout: "Compiling foo v1.0.0\ntest test1 ... ok\ntest result: ok. 1 passed; 0 failed\n",
                contains: &["Compiling foo", "test1 ... ok", "test result:"],
                not_contains: &["[cargo test: ok]"],
                ..Default::default()
            },
            // ── npx-wrapped tools (profile selection) ─────────────────
            ShellOutputCase {
                name: "npx eslint selects eslint profile",
                command: "npx eslint .",
                contains: &["[eslint: ok]"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "npx prettier selects prettier profile",
                command: "npx prettier --check file.js",
                stdout: "unchanged",
                contains: &["unchanged"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "npx tsc selects tsc profile",
                command: "npx tsc --noEmit",
                contains: &["[tsc: ok]"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "npx vitest selects vitest profile",
                command: "npx vitest --run",
                stdout: "stdout: Tests passed\nPASS src/test.ts\n",
                // Vitest profile strips "PASS" prefixed lines but keeps "stdout:" lines
                not_contains: &["PASS"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "npx with flags before subcommand selects eslint profile",
                command: "npx --yes eslint .",
                contains: &["[eslint: ok]"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "unknown npx tool falls through to generic",
                command: "npx some_obscure_tool --flag",
                stdout: "some\nrandom\noutput\n",
                contains: &["some", "output"],
                ..Default::default()
            },
        ];
        check_shell_output(cases);
    }

    #[test]
    fn mahbot_chrome_envelope_line_bypasses_the_line_cap() {
        // The chrome CLI emits ONE line of JSON; its profile must not apply
        // GEN_FALLBACK's 500-byte line cap, which would truncate the envelope
        // mid-JSON and drop the page content.
        let envelope = format!(
            r#"{{"schema":1,"action":"open","ok":true,"kind":"ok","content":"{}","url":"https://example.com/"}}"#,
            "x".repeat(600)
        );
        let result = process_shell_output(
            "mahbot chrome open https://example.com",
            &envelope,
            "",
            0,
            Duration::from_secs_f64(1.0),
        );
        assert_contains_not_contains(
            "mahbot chrome envelope",
            &result,
            &[r#""content":""#],
            &["more chars on this line"],
        );
        assert!(
            result.contains(&envelope),
            "envelope line must survive intact"
        );
    }

    #[expect(clippy::too_many_lines)]
    #[test]
    fn tool_profile_cases() {
        // Specific tool profile tests — consolidated table.
        // Covers strip, on_empty, and transform behaviors of named
        // tool profiles (git, docker, df, du, make, rsync, tsc, gh,
        // terraform, pytest, and the generic fallback pipeline).
        let cases: &[ShellOutputCase] = &[
            ShellOutputCase {
                name: "git diff no changes via on_empty",
                command: "git diff",
                contains: &["no changes"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "docker build success via on_empty",
                command: "docker build -t myimage .",
                stdout: "Step 1/3 : FROM alpine\n ---> abc123\nStep 2/3 : RUN echo hi\n ---> Using cache\nStep 3/3 : CMD [\"sh\"]\n ---> def456\nSuccessfully built abc123\nSuccessfully tagged myimage:latest\n",
                contains: &["[docker"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "git log preserves content",
                command: "git log --oneline",
                stdout: "commit abc123\nAuthor: test\nDate:   Mon Jan 1\n\n    initial commit\n\ncommit def456\nAuthor: test\nDate:   Tue Jan 2\n\n    second commit\n\n",
                contains: &["commit", "Author"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "generic pipeline: strips ANSI, preserves content",
                command: "unknown",
                stdout: "Compiling foo v1.0.0 (/tmp)\nCompiling bar v2.0.0 (/tmp)\nresult: ok\nline1\nline2\nline3\nline3\nline3\nline3\nline3\nline3\nline3\n",
                contains: &["Compiling", "result: ok"],
                not_contains: &["\x1B["],
                ..Default::default()
            },
            ShellOutputCase {
                name: "du strips blank lines",
                command: "du -sh",
                stdout: "1.0K\t./file1\n\n2.0K\t./file2\n\n\n3.0K\t./file3",
                not_contains: &["\n\n"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "make strips directory noise",
                command: "make",
                stdout: "make[1]: Entering directory `/tmp'\nmake[1]: Leaving directory `/tmp'\ncc -c file.c\nNothing to be done",
                not_contains: &["Entering directory", "Nothing to be done"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "rsync success shows transfer summary",
                command: "rsync -avz source/ dest/",
                stdout: "building file list ... done\nsent 100 bytes  received 50 bytes\n\ntotal size is 98765  speedup is 658.43\n",
                contains: &["building file list", "total size is", "98765"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "tsc on empty returns ok",
                command: "tsc --noEmit",
                eq: Some("[tsc: ok] (0.0s)"),
                ..Default::default()
            },
            ShellOutputCase {
                name: "tsc on empty shows timing",
                command: "tsc --noEmit",
                elapsed_secs: 3.2,
                contains: &["(3.2s)"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "docker strips build steps and shows on_empty",
                command: "docker build -t myapp .",
                stdout: "Step 1/10 : FROM node:18\nStep 2/10 : WORKDIR /app\n ---> Using cache\nSuccessfully built abc123\nSuccessfully tagged myapp:latest\n",
                contains: &["[docker: ok]"],
                not_contains: &["Step "],
                ..Default::default()
            },
            ShellOutputCase {
                name: "gh strips warning noise, preserves output",
                command: "gh pr create --fill",
                stdout: "  \n - some detail\nwarning: consider updating gh\n✓ Created pull request\n",
                contains: &["Created pull request"],
                not_contains: &["warning:"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "terraform shows no changes message",
                command: "terraform plan",
                stdout: "data.aws_region.current: Refreshing state...\nNo changes. Your infrastructure matches the configuration.\n",
                contains: &["No changes", "infrastructure matches"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "pytest strips collected count",
                command: "pytest",
                stdout: "============================= test session starts ==============================\ncollected 5 items\n\n.test..\n\n============================== 5 passed ==============================\n",
                not_contains: &["collected"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "python -m pytest falls through to generic (collected preserved)",
                command: "python -m pytest tests/",
                stdout: "============================= test session starts ==============================\ncollected 5 items\n\n.test..\n\n============================== 5 passed ==============================\n",
                contains: &["collected"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "poetry run pytest falls through to generic (collected preserved)",
                command: "poetry run pytest tests/",
                stdout: "============================= test session starts ==============================\ncollected 5 items\n\n.test..\n\n============================== 5 passed ==============================\n",
                contains: &["collected"],
                ..Default::default()
            },
        ];
        check_shell_output(cases);
    }

    #[test]
    fn compact_ls_cases() {
        // ls compaction profile tests — consolidated table.
        // compact_ls transforms `ls -la` output into a compact summary.
        // Plain `ls` (no -l) and chained/piped commands are excluded
        // from compaction via standalone_only and selection logic.
        let cases: &[ShellOutputCase] = &[
            ShellOutputCase {
                name: "empty directory shows (empty)",
                command: "ls -la",
                stdout: "total 0\ndrwxr-xr-x  2 user  group  64 May 21 10:00 .\ndrwxr-xr-x  3 user  group  96 May 21 10:00 ..\n",
                eq: Some("(empty)"),
                ..Default::default()
            },
            ShellOutputCase {
                name: "mixed files and dirs shows summary",
                command: "ls -la",
                stdout: "total 32\ndrwxr-xr-x  5 user  group   160 May 21 10:00 .\ndrwxr-xr-x  3 user  group    96 May 21 10:00 ..\n-rw-r--r--  1 user  group  2048 May 21 10:00 main.rs\n-rw-r--r--  1 user  group  4096 May 21 10:00 lib.rs\ndrwxr-xr-x  2 user  group    64 May 21 10:00 src\nlrwxr-xr-x  1 user  group     5 May 21 10:00 link -> target\n",
                contains: &["src/", "main.rs", "lib.rs", "Summary:"],
                not_contains: &["link -> target"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "dotless files classified as no ext",
                command: "ls -la",
                stdout: "total 16\n-rw-r--r--  1 user  group  1024 May 21 10:00 Makefile\n-rw-r--r--  1 user  group  2048 May 21 10:00 README\n-rw-r--r--  1 user  group   512 May 21 10:00 .gitignore\n-rw-r--r--  1 user  group  1024 May 21 10:00 main.rs\n",
                contains: &["Makefile", "README", "no ext", ".rs"],
                not_contains: &[".Makefile", ".README"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "plain ls passes through without compaction",
                command: "ls",
                stdout: "Cargo.toml\nCargo.lock\nsrc\ntarget\nREADME.md\n",
                contains: &["Cargo.toml", "src"],
                not_contains: &["(empty)", "Summary:"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "chained ls skips compact_ls",
                command: "ls -l && echo done",
                stdout: "total 8\n-rw-r--r--  1 user  group  1024 May 21 10:00 foo\n-rw-r--r--  1 user  group  2048 May 21 10:00 bar\ndone\n",
                contains: &["done"],
                not_contains: &["Summary:"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "piped ls skips compact_ls",
                command: "ls -l | head -5",
                stdout: "total 8\n-rw-r--r--  1 user  group  1024 May 21 10:00 foo\n-rw-r--r--  1 user  group  2048 May 21 10:00 bar\n",
                contains: &["total 8"],
                not_contains: &["Summary:"],
                ..Default::default()
            },
        ];
        check_shell_output(cases);
    }

    #[test]
    fn cargo_build_cases() {
        // Cargo build/check profile tests — consolidated table.
        let cases: &[ShellOutputCase] = &[
            ShellOutputCase {
                name: "cargo build strips Compiling, preserves errors",
                command: "cargo build",
                stdout: "Compiling foo v1.0.0 (/tmp)\nCompiling bar v2.0.0 (/tmp)\n   Compiling baz v3.0.0 (/tmp)\nerror[E0425]: cannot find value\n\nFor more information about this error, try `rustc --explain E0425`.\nerror: could not compile `foo` due to 1 previous error",
                exit_code: 1,
                contains: &["error[E0425]", "could not compile"],
                not_contains: &["Compiling foo"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "cargo check strips Checking lines",
                command: "cargo check",
                stdout: "    Checking foo v1.0.0\n    Checking bar v2.0.0\n    warning: unused import\n\nwarning: 1 warning emitted\n\n    Finished `dev` profile [unoptimized] target\n",
                not_contains: &["Checking"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "cargo build strips Compiling and Finished on success",
                command: "cargo build",
                stdout: "   Compiling foo v1.0.0\n   Compiling bar v2.0.0\n    Finished dev [unoptimized]\n",
                not_contains: &["Compiling", "Finished"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "absolute cargo check strips Compiling",
                command: "/usr/local/bin/cargo check",
                stdout: "   Compiling foo v1.0.0\nwarning: unused import\n",
                not_contains: &["Compiling"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "chained cargo build strips Compiling, preserves errors",
                command: "cd project && cargo build",
                stdout: "   Compiling foo v1.0.0\n   Compiling bar v2.0.0\nerror[E0425]: cannot find value\n",
                exit_code: 1,
                contains: &["error[E0425]"],
                not_contains: &["Compiling"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "cargo build keeps stderr warnings on success",
                command: "cargo build",
                stdout: "   Compiling foo v1.0.0\n    Finished\n",
                stderr: "warning: unused import: `std::fs`\n  --> src/main.rs:1:5\n",
                contains: &["warning:"],
                ..Default::default()
            },
            // ── on_fail_msg tests ────────────────────────────────────
            ShellOutputCase {
                name: "cargo clippy failure shows on_fail_msg (no (failed) suffix)",
                command: "cargo clippy",
                exit_code: 1,
                eq: Some("[cargo clippy: failed] (0.0s)"),
                ..Default::default()
            },
            ShellOutputCase {
                name: "cargo clippy failure filters progress lines from stderr",
                command: "cargo clippy",
                stderr: "    Checking mahbot v0.1.0 (/Users/user/mahbot)\nwarning: unused import: `std::fs`\n  --> src/main.rs:1:5\n",
                exit_code: 1,
                contains: &["warning:", "[cargo clippy: failed]"],
                not_contains: &["Checking mahbot"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "cargo clippy failure omits stderr when no keep_stderr match",
                command: "cargo clippy",
                stderr: "    Checking mahbot v0.1.0\n    Finished dev [unoptimized]\n",
                exit_code: 1,
                eq: Some("[cargo clippy: failed] (0.0s)"),
                not_contains: &["Checking", "stderr:"],
                ..Default::default()
            },
            ShellOutputCase {
                name: "cargo build failure shows on_fail_msg (no (failed) suffix)",
                command: "cargo build",
                exit_code: 1,
                eq: Some("[cargo: failed] (0.0s)"),
                ..Default::default()
            },
            ShellOutputCase {
                name: "cargo build success still shows ok (backward compat)",
                command: "cargo build",
                eq: Some("[cargo: ok] (0.0s)"),
                ..Default::default()
            },
        ];
        check_shell_output(cases);
    }

    /// The reduced fallback list still carries no credential-looking name: it
    /// is what the product's own internal work runs in, and the stand-in for
    /// an agent's command until the owner's environment has been read.
    #[test]
    fn fallback_env_vars_carry_the_essentials_and_no_credentials() {
        for var in FALLBACK_ENV_VARS {
            let lower = var.to_lowercase();
            assert!(
                !lower.contains("key") && !lower.contains("secret") && !lower.contains("token")
            );
        }
        assert!(FALLBACK_ENV_VARS.contains(&"PATH"));
        assert!(FALLBACK_ENV_VARS.contains(&"HOME") || FALLBACK_ENV_VARS.contains(&"USERPROFILE"));
        assert!(FALLBACK_ENV_VARS.contains(&"TERM"));
    }

    /// Run `env` through [`build_shell_command`] and return its variables keyed
    /// by name, so an assertion about a name cannot be fooled by the same text
    /// appearing inside some other value.
    #[cfg(unix)]
    async fn shell_env_vars(workspace: &Path) -> std::collections::HashMap<String, String> {
        // Building the command reads `$CARGO_HOME` in the fallback branch;
        // the shared lock keeps that from racing another test's env write.
        let mut cmd = {
            let _guard = env_lock().lock().unwrap_poison();
            build_shell_command("env", workspace)
        };
        let output = cmd.output().await.expect("env should run");
        String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter_map(|line| line.split_once('='))
            .map(|(name, value)| (name.to_string(), value.to_string()))
            .collect()
    }

    /// Once the owner's environment has been read, the child runs in it: a
    /// variable that exists only there reaches the child — credential-shaped
    /// names included, nothing is filtered — and nothing the reduced fallback
    /// would add is merged in (`TERM=dumb` is the tell). The private temp root
    /// still wins over whatever the snapshot carried.
    ///
    /// `#[serial]`: the snapshot is process-global, so a command another lane
    /// spawns during this window runs in the fixture too — which is why the fixture
    /// carries the `PATH` a real owner's environment always has.
    #[cfg(unix)]
    #[serial_test::serial(shell_env)]
    #[tokio::test]
    async fn build_shell_command_uses_the_owner_environment_once_read() {
        crate::shell_env::set_snapshot(Some(crate::shell_env::OwnerEnv::new(vec![
            (
                OsString::from("OWNER_ONLY"),
                OsString::from("from-the-snapshot"),
            ),
            // The owner's own environment is his to expose: a token in it is
            // handed over as it is, because the command is his own work.
            (
                OsString::from("AWS_SECRET_ACCESS_KEY"),
                OsString::from("owner-secret-value"),
            ),
            (
                OsString::from("PATH"),
                OsString::from("/usr/local/bin:/usr/bin:/bin"),
            ),
        ])));

        let tmp = TempDir::new().expect("tempdir");
        let vars = shell_env_vars(tmp.path()).await;
        crate::shell_env::set_snapshot(None);

        assert_eq!(
            vars.get("OWNER_ONLY").map(String::as_str),
            Some("from-the-snapshot"),
            "a snapshot variable must reach the child: {vars:?}"
        );
        assert_eq!(
            vars.get("AWS_SECRET_ACCESS_KEY").map(String::as_str),
            Some("owner-secret-value"),
            "the owner's own environment is unfiltered: {vars:?}"
        );
        assert!(
            !vars.contains_key("TERM"),
            "the fallback must not be merged into the owner's environment: {vars:?}"
        );
        // The data-location home is imposed even though the snapshot carried
        // none: that is the exception the scratch-instance workflow relies on.
        match std::env::var("HOME") {
            Ok(home) => assert_eq!(vars.get("HOME"), Some(&home), "{vars:?}"),
            Err(_) => assert!(vars.contains_key("HOME"), "{vars:?}"),
        }
        // `sh` adds `PWD` and friends of its own; the pinned temp names are the
        // product's and must survive them.
        for (name, value) in crate::temp::shell_temp_vars() {
            assert_eq!(
                vars.get(&name).map(String::as_str),
                Some(value.as_str()),
                "{name} must stay the private temp root: {vars:?}"
            );
        }
    }

    /// With no snapshot the child gets exactly the reduced fallback: baseline
    /// values for its names, and nothing from this process's environment.
    ///
    /// `#[serial]`: another lane's snapshot is process-global, and this lane
    /// asserts the absence of one.
    #[cfg(unix)]
    #[serial_test::serial(shell_env)]
    #[tokio::test]
    async fn build_shell_command_falls_back_until_the_owner_environment_is_read() {
        crate::shell_env::set_snapshot(None);

        let tmp = TempDir::new().expect("tempdir");
        let vars = shell_env_vars(tmp.path()).await;

        assert!(
            vars.contains_key("HOME"),
            "HOME must be in the fallback env"
        );
        assert!(
            vars.contains_key("PATH"),
            "PATH must be in the fallback env"
        );

        // Parent-process env vars outside the fallback list must NOT leak.
        // CARGO_HOME is commonly set but is not in the list.
        assert!(
            !vars.contains_key("CARGO_HOME"),
            "CARGO_HOME must not leak into the child env: {vars:?}"
        );
    }

    /// A direct program run takes its arguments as argv: nothing in them is
    /// parsed as shell syntax, a non-zero exit is a completed run (reported with
    /// the standard note), and the output is decoded like the shell's.
    #[cfg(unix)]
    #[tokio::test]
    async fn run_program_with_timeout_passes_argv_and_annotates_exit() {
        let tmp = TempDir::new().expect("tempdir");
        let ws = crate::workspace::test_ws(tmp.path());
        let output = run_program_with_timeout(
            ws.as_path(),
            Path::new("/bin/sh"),
            &[
                "-c".to_string(),
                // `$0` is the placeholder below; `$1` is the hostile-looking
                // value, which must arrive verbatim rather than be executed.
                "printf '%s' \"$1\"; exit 3".to_string(),
                "sh".to_string(),
                "a; echo pwned".to_string(),
            ],
            "the test program",
        )
        .await
        .expect("a completed run");

        // The hostile-looking argument arrives verbatim as the only output
        // line; the status note follows it as its own paragraph.
        assert_eq!(
            output.lines().collect::<Vec<_>>(),
            ["a; echo pwned", "", "[exit status: 3]"]
        );
    }

    /// A direct program run reported as an outcome: output is raw and
    /// un-annotated, and only the raw streams decide whether anything was
    /// reported.
    #[cfg(unix)]
    #[tokio::test]
    async fn run_program_outcome_reports_output_and_status_without_annotations() {
        let tmp = TempDir::new().expect("tempdir");
        let ws = crate::workspace::test_ws(tmp.path());

        // Success with stdout — raw, un-annotated output.
        let out = run_program_outcome(
            ws.as_path(),
            Path::new("/bin/sh"),
            &sh_args("echo hello-prog-out"),
        )
        .await;
        assert!(out.success);
        assert!(out.has_output);
        assert!(out.output.contains("hello-prog-out"), "got: {}", out.output);
        assert!(!out.output.contains("[exit status"), "got: {}", out.output);
        assert_eq!(out.detail, "exit status 0");

        // Non-zero exit is a failed outcome whose output is still just the
        // program's own text.
        let out = run_program_outcome(
            ws.as_path(),
            Path::new("/bin/sh"),
            &sh_args("echo bad; exit 3"),
        )
        .await;
        assert!(!out.success);
        assert!(out.has_output);
        assert!(out.output.contains("bad"), "got: {}", out.output);
        assert!(!out.output.contains("[exit status"), "got: {}", out.output);
        assert_eq!(out.detail, "exit status 3");

        // No output at all: nothing was reported.
        let out =
            run_program_outcome(ws.as_path(), Path::new("/bin/sh"), &sh_args("printf ''")).await;
        assert!(out.success);
        assert!(!out.has_output);
        assert!(out.output.is_empty());

        // Whitespace-only output still counts as reported — the raw streams
        // decide, not the trimmed text.
        let out =
            run_program_outcome(ws.as_path(), Path::new("/bin/sh"), &sh_args("printf '\\n'")).await;
        assert!(out.has_output);

        // ... and so does escape-sequence-only output — reported, even though
        // the ANSI strip leaves nothing readable behind.
        let out = run_program_outcome(
            ws.as_path(),
            Path::new("/bin/sh"),
            &sh_args("printf '\\033[32m\\033[0m'"),
        )
        .await;
        assert!(out.has_output);
        assert!(out.output.is_empty(), "got: {}", out.output);

        // stderr alone counts as output.
        let out =
            run_program_outcome(ws.as_path(), Path::new("/bin/sh"), &sh_args("echo hi >&2")).await;
        assert!(out.has_output);
        assert!(out.output.contains("hi"), "got: {}", out.output);

        // The literal is split so this source does not itself look like a
        // credential to output scrubbers; the control below proves the scrubber
        // rewrites it, and that it therefore reaches the alarm verbatim.
        let raw = concat!("API_KEY=", "abcd1234");
        assert!(
            scrub_credentials(raw).contains("*[REDACTED]"),
            "the scrubber must rewrite this value, or the pin below is vacuous"
        );
        let out = run_program_outcome(
            ws.as_path(),
            Path::new("/bin/sh"),
            &sh_args(&format!("echo {raw}")),
        )
        .await;
        assert!(out.has_output);
        assert_eq!(
            out.output.trim(),
            raw,
            "the check's output must reach the alarm unredacted"
        );
    }

    #[cfg(unix)]
    fn sh_args(script: &str) -> Vec<String> {
        vec!["-c".to_string(), script.to_string()]
    }

    #[tokio::test]
    async fn shell_executes_allowed_command() {
        let tmp = TempDir::new().expect("tempdir");
        let result = ShellTool::new(ShellMode::Full)
            .execute(&test_ws(tmp.path()), json!({"command": "echo hello"}))
            .await;
        assert!(
            result.is_ok(),
            "echo command execution should succeed: {result:?}"
        );
        let result = result.unwrap();
        assert!(result.trim().contains("hello"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn shell_nonzero_exit_with_stdout_counts_as_success() {
        // `test -f` exits 1 when file doesn't exist, with no stdout/stderr.
        // Combined with `echo`, this produces stdout + non-zero exit without
        // triggering any command-specific filter profiles.
        let tmp = TempDir::new().expect("tempdir");
        let result = ShellTool::new(ShellMode::Full)
            .execute(
                &test_ws(tmp.path()),
                json!({"command": "echo partial; test -f nonexistent_file_xyz"}),
            )
            .await;
        assert!(
            result.is_ok(),
            "shell should return Ok(String) when stdout present: {result:?}"
        );
        let result = result.unwrap();
        assert!(result.contains("partial"));
        assert!(
            result.contains("[exit status: 1]"),
            "model should still see real exit status, got {result:?}",
        );
    }

    #[tokio::test]
    async fn shell_captures_exit_code() {
        let tmp = TempDir::new().expect("tempdir");
        let result = ShellTool::new(ShellMode::Full)
            .execute(
                &test_ws(tmp.path()),
                json!({"command": "ls nonexistent_dir_xyz"}),
            )
            .await;
        assert!(
            result.is_ok(),
            "command with nonexistent path should return ok: {result:?}"
        );
        let output = result.unwrap();
        assert!(
            output.contains("[exit status: 1]"),
            "output should contain exit status: {output:?}",
        );
        assert!(
            output.contains("nonexistent_dir_xyz"),
            "output should contain the error: {output:?}"
        );
    }

    // ── Background mode (Full roles only) ─────────────────────────────

    /// Run `shell_tool.execute(...)` inside the agent tool-batch context with a
    /// background-session registry, so the background/stop arguments resolve.
    async fn execute_with_bg_registry(
        shell_tool: &ShellTool,
        ws: &crate::Workspace,
        args: serde_json::Value,
        sessions: &std::sync::Arc<crate::tools::shell::BackgroundSessions>,
    ) -> anyhow::Result<String> {
        crate::agent::CURRENT_TOOL_BACKGROUND_SESSIONS
            .scope(Some(sessions.clone()), async {
                shell_tool.execute(ws, args).await
            })
            .await
    }

    #[tokio::test]
    async fn background_launch_via_tool_registers_session_and_read_tool_reads_output() {
        let tmp = TempDir::new().expect("tempdir");
        let ws = test_ws(tmp.path());
        let sessions = std::sync::Arc::new(BackgroundSessions::default());

        let output = execute_with_bg_registry(
            &ShellTool::new(ShellMode::Full),
            &ws,
            json!({"command": "echo bg-via-tool", "background": true}),
            &sessions,
        )
        .await
        .expect("background launch succeeds");

        // The message carries the output-file path.
        let path_line = output
            .lines()
            .find(|l| l.starts_with("output file:"))
            .expect("launch message must name the output file");
        let path = PathBuf::from(path_line.trim_start_matches("output file:").trim());
        assert!(
            bg::is_output_file(&path),
            "the launch message must name the product's own output file: {path:?}"
        );

        // The session is registered in the agent-scoped registry.
        assert!(sessions.contains(&path), "session must be registered");

        // The read tool can read the output file (temp-area allowlist covers
        // the .agent directory) — no allowlist changes were needed.
        let content = crate::tools::ReadTool::general()
            .execute(&ws, json!({"path": path.to_string_lossy().to_string()}))
            .await
            .expect("read tool must read the bg output file");
        assert!(
            content.contains("bg-via-tool"),
            "raw output must be in the file: {content}"
        );

        // And the annotation eventually lands.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !sessions.is_finished(&path) && std::time::Instant::now() < deadline {
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(sessions.is_finished(&path), "session should finish");
        let content = std::fs::read_to_string(&path).expect("bg output file readable");
        assert!(
            content.contains("[exit status: 0]"),
            "annotation must be appended: {content}"
        );
    }

    #[tokio::test]
    async fn background_stop_via_tool() {
        let _env = set_env_var("MAHBOT_BG_STOP_GRACE_SECS", Some("0"));
        let tmp = TempDir::new().expect("tempdir");
        let ws = test_ws(tmp.path());
        let sessions = std::sync::Arc::new(BackgroundSessions::default());
        let tool = ShellTool::new(ShellMode::Full);

        let launch_out = execute_with_bg_registry(
            &tool,
            &ws,
            json!({"command": "sleep 30", "background": true}),
            &sessions,
        )
        .await
        .expect("launch");
        let path = launch_out
            .lines()
            .find(|l| l.starts_with("output file:"))
            .expect("output file line")
            .trim_start_matches("output file:")
            .trim();

        // Stop via the tool's `stop` argument, addressing the output-file path.
        let stop_out = execute_with_bg_registry(&tool, &ws, json!({"stop": path}), &sessions)
            .await
            .expect("stop succeeds");
        assert!(
            stop_out.contains("Background session stopped"),
            "stop message: {stop_out}"
        );
        assert!(
            sessions.is_finished(Path::new(path)),
            "stopped session must be finished"
        );
    }

    #[tokio::test]
    async fn background_stop_and_background_conflict_errors() {
        let tmp = TempDir::new().expect("tempdir");
        let ws = test_ws(tmp.path());
        let sessions = std::sync::Arc::new(BackgroundSessions::default());

        let err = execute_with_bg_registry(
            &ShellTool::new(ShellMode::Full),
            &ws,
            json!({"command": "echo hi", "background": true, "stop": "/tmp/.agent/bg_0000.out"}),
            &sessions,
        )
        .await
        .expect_err("stop + background must be rejected");
        assert!(
            err.to_string().contains("cannot be combined"),
            "error message: {err}"
        );
    }

    #[tokio::test]
    async fn background_unavailable_without_agent_context() {
        // No task-local registry (management diagnostics / tests context):
        // background mode must fail loudly instead of leaking a process.
        let tmp = TempDir::new().expect("tempdir");
        let err = ShellTool::new(ShellMode::Full)
            .execute(
                &test_ws(tmp.path()),
                json!({"command": "sleep 30", "background": true}),
            )
            .await
            .expect_err("background without an agent registry must error");
        assert!(
            err.to_string().contains("not available in this context"),
            "error message: {err}"
        );
    }

    #[test]
    fn full_description_and_schema_cover_background_capability() {
        // The Full variant gets its own prompt asset and an extended argument
        // schema describing the background capability.
        let full = ShellTool::new(ShellMode::Full);
        let description = full.description();
        assert!(
            description.contains("Background mode"),
            "Full description must describe background mode"
        );
        assert!(
            description.contains("[exit status: N]"),
            "Full description must document the completion annotation"
        );
        // The platform-selected texts this description carries are checked by
        // `platform_selected_texts_are_this_platforms_own`, which reads this host's
        // platform; nothing here may depend on it.

        let schema = full.parameters_schema();
        let props = schema["properties"].as_object().expect("schema properties");
        assert!(
            props.contains_key("background"),
            "Full schema must advertise the background argument"
        );
        assert!(
            props.contains_key("stop"),
            "Full schema must advertise the stop argument"
        );
        assert_eq!(
            props["background"]["type"], "boolean",
            "background must be a boolean"
        );
        assert_eq!(
            props["background"]["default"], false,
            "background must default to false"
        );
    }

    /// The read-only variant shares the base description and the grep-engine
    /// disclosure with Full, but must not advertise the full-only background
    /// capability (it has no `background` argument).
    #[test]
    fn read_only_description_covers_grep_notes_without_background_capability() {
        let description = ShellTool::new(ShellMode::ReadOnly).description();
        assert!(
            description.contains("## Grep notes"),
            "read-only description must carry the grep-engine disclosure"
        );
        assert!(
            !description.contains("Background mode"),
            "read-only description must not advertise the full-only background capability"
        );
    }

    /// A command that outlives its timeout must be killed: the run returns
    /// `ShellRunResult::TimedOut` with an elapsed time close to the limit
    /// (not the full `sleep` duration).
    ///
    /// This test is `#[ignore]` by default because it waits out a real 1 s
    /// command timeout against a live `sleep 10` child. Run it explicitly
    /// with:
    ///
    /// ```sh
    /// cargo test run_command_with_timeout_kills_long_sleep -- --ignored --nocapture
    /// ```
    #[ignore = "waits out real command timeouts against live processes (hardcoded waits); runs only when explicitly invoked"]
    #[cfg(unix)]
    #[tokio::test]
    async fn run_command_with_timeout_kills_long_sleep() {
        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c").arg("sleep 10");
        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(1),
            Duration::from_secs(10),
            mem::default_limit(),
            RunOwner::Agent,
            LeftoverPolicy::Keep,
        )
        .await;
        match result {
            ShellRunResult::TimedOut { elapsed, .. } => {
                assert!(
                    elapsed < Duration::from_secs(3),
                    "expected ~1s timeout, got {elapsed:?}"
                );
            }
            other => panic!("expected TimedOut, got {other:?}"),
        }
    }

    /// When a command times out, stdout written before the kill must be
    /// preserved in `ShellRunResult::TimedOut`.
    ///
    /// This test is `#[ignore]` by default because it waits out a real 2 s
    /// command timeout against a live `sleep 60` child. Run it explicitly
    /// with:
    ///
    /// ```sh
    /// cargo test run_command_with_timeout_captures_partial_stdout -- --ignored --nocapture
    /// ```
    #[ignore = "waits out real command timeouts against live processes (hardcoded waits); runs only when explicitly invoked"]
    #[cfg(unix)]
    #[tokio::test]
    async fn run_command_with_timeout_captures_partial_stdout() {
        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c").arg("echo started; sleep 60");
        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(2),
            Duration::from_secs(10),
            mem::default_limit(),
            RunOwner::Agent,
            LeftoverPolicy::Keep,
        )
        .await;
        match result {
            ShellRunResult::TimedOut { stdout, .. } => {
                let s = String::from_utf8_lossy(&stdout);
                assert!(
                    s.contains("started"),
                    "stdout should contain partial output: {s}"
                );
            }
            other => panic!("expected TimedOut, got {other:?}"),
        }
    }

    /// Tests that timeout error messages include partial output (stdout and stderr
    /// tails) and ANSI stripping works.
    ///
    /// The `sleep 30` grandchild is now terminated by the PGID kill, not orphaned.
    ///
    /// This test is `#[ignore]` by default because it waits out a real 1 s command timeout against a live `sleep 30` child. Run it
    /// explicitly with:
    ///
    /// ```sh
    /// cargo test shell_timeout_error_includes_diagnostics -- --ignored --nocapture
    /// ```
    #[ignore = "waits out real command timeouts against live processes (hardcoded waits); runs only when explicitly invoked"]
    #[cfg(unix)]
    #[tokio::test]
    async fn shell_timeout_error_includes_diagnostics() {
        let tmp = TempDir::new().expect("tempdir");
        let mut cmd = build_shell_command("echo before-timeout; sleep 30", tmp.path());
        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(1),
            Duration::from_secs(10),
            mem::default_limit(),
            RunOwner::Agent,
            LeftoverPolicy::Keep,
        )
        .await;
        let ShellRunResult::TimedOut {
            stdout,
            stderr,
            pid,
            elapsed,
        } = result
        else {
            panic!("expected timeout");
        };
        let msg = format_timeout_error(
            "echo test",
            elapsed,
            Duration::from_secs(1),
            pid,
            &stdout,
            &stderr,
        );
        assert!(msg.contains("elapsed:"), "msg: {msg}");
        assert!(msg.contains("timeout_limit:"), "msg: {msg}");
        assert!(msg.contains("timeout_secs"), "msg: {msg}");
        assert!(msg.contains("before-timeout"), "msg: {msg}");

        // Verify ANSI escape sequences are stripped from timeout error messages
        let ansi_stdout = b"\x1B[31mred error\x1B[0m";
        let ansi_stderr = b"\x1B[1mBOLD STUFF\x1B[22m";
        let ansi_msg = format_timeout_error(
            "test",
            elapsed,
            Duration::from_mins(5),
            Some(42),
            ansi_stdout,
            ansi_stderr,
        );
        assert!(
            ansi_msg.contains("red error"),
            "ANSI text content should survive stripping: {ansi_msg}"
        );
        assert!(
            !ansi_msg.contains("\x1B["),
            "ANSI escape codes should be stripped from timeout error: {ansi_msg}"
        );
        assert!(
            ansi_msg.contains("BOLD STUFF"),
            "ANSI text content should survive stripping: {ansi_msg}"
        );
    }

    /// Wait — briefly — for a pid to stop existing. `kill(pid, 0)` is the
    /// existence probe: it sends no signal.
    #[cfg(unix)]
    async fn wait_for_death(pid: i32) {
        let deadline = std::time::Instant::now() + Duration::from_secs(2);
        while std::time::Instant::now() < deadline {
            // SAFETY: signal 0 performs the permission/existence check only.
            if unsafe { libc::kill(pid, 0) } != 0 {
                return;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        panic!("pid {pid} is still alive");
    }

    /// A run that can only end by being stopped: `sh` backgrounds a long sleep —
    /// which inherits sh's process group — then waits, writing the sleep's pid to
    /// `grandchild.pid` in `dir`. Returns that file and the prepared command.
    #[cfg(unix)]
    fn run_with_backgrounded_sleep(dir: &TempDir) -> (std::path::PathBuf, tokio::process::Command) {
        let pid_path = dir.path().join("grandchild.pid");
        let cmd_str = format!(
            "sleep 999 & echo $! > {}; wait",
            pid_path.to_str().expect("valid utf-8 path")
        );
        (pid_path, build_shell_command(&cmd_str, dir.path()))
    }

    /// The pid the shell wrote for that sleep, once the run has been stopped.
    #[cfg(unix)]
    fn stopped_grandchild(pid_path: &std::path::Path) -> i32 {
        std::fs::read_to_string(pid_path)
            .expect("grandchild PID file must exist — grandchild was launched")
            .trim()
            .parse()
            .expect("valid PID from file")
    }

    /// A run whose tree outgrows the memory ceiling is ended like a stop and
    /// reported as a memory failure — never as a timeout. The ceiling is a tiny
    /// injected value, never the real 80%, and the memory is allocated inside the
    /// command (a shell variable holding a few tens of MiB), so the test process
    /// itself allocates nothing near physical RAM.
    ///
    /// The memory lives in a backgrounded *subshell*, not in the run's direct
    /// child, so the sample has to reach a descendant to find it.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_run_over_the_memory_ceiling_is_killed_and_reported() {
        /// The injected ceiling: small enough that the command below crosses it
        /// long before the test machine's own 80% could be relevant.
        const CEILING: u64 = 16 * 1024 * 1024;
        /// What the subshell holds in a variable — 64 MiB, four times the
        /// ceiling, and nothing at all against physical RAM. Non-NUL bytes
        /// matter: a NUL is dropped by the shell and would never be counted.
        const PAYLOAD: usize = 64 * 1024 * 1024;

        let dir = TempDir::new().expect("tempdir");
        let mut cmd = build_shell_command(
            &format!("(x=$(yes x | head -c {PAYLOAD}); sleep 30) & wait"),
            dir.path(),
        );

        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(30),
            Duration::from_secs(5),
            Some(CEILING),
            RunOwner::Agent,
            LeftoverPolicy::Keep,
        )
        .await;

        let ShellRunResult::MemoryExceeded {
            used,
            limit,
            elapsed,
            ..
        } = result
        else {
            panic!("expected MemoryExceeded, got {result:?}");
        };
        assert_eq!(limit, CEILING);
        assert!(
            used > limit,
            "the sample that tripped the watchdog must exceed the ceiling: {used} > {limit}"
        );
        assert!(
            elapsed < Duration::from_secs(20),
            "the watchdog must not wait out the command: {elapsed:?}"
        );

        // The reported failure's shape: the memory sentence first, then the
        // timeout block's own fields, and never a timeout's wording.
        let msg = format_memory_error("test", elapsed, used, limit, None, &[], &[]);
        assert!(
            msg.starts_with("Shell command terminated: exceeded memory limit (used ~"),
            "msg: {msg}"
        );
        assert!(msg.contains("\ncommand: test"), "msg: {msg}");
        assert!(msg.contains("\nelapsed: "), "msg: {msg}");
        assert!(msg.contains("\nmemory_limit: "), "msg: {msg}");
        assert!(
            msg.contains("\nreason: command was killed after exceeding the memory limit"),
            "msg: {msg}"
        );
        assert!(!msg.contains("timed out"), "msg: {msg}");
    }

    /// A stop ends the command's whole process tree, not only its direct child:
    /// the timeout path ends the run's containment, so a grandchild the command
    /// backgrounded dies with it. This is the unix arm of [`Tree::terminate`];
    /// Windows reaches the same outcome through its job object, which only a
    /// Windows host can exercise.
    #[cfg(unix)]
    #[tokio::test]
    async fn timeout_kills_the_command_process_tree() {
        let dir = TempDir::new().expect("tempdir");
        let (pid_path, mut cmd) = run_with_backgrounded_sleep(&dir);

        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(2),
            Duration::from_secs(5),
            mem::default_limit(),
            RunOwner::Agent,
            LeftoverPolicy::Keep,
        )
        .await;
        assert!(
            matches!(result, ShellRunResult::TimedOut { .. }),
            "expected TimedOut, got {result:?}"
        );

        wait_for_death(stopped_grandchild(&pid_path)).await;
    }

    /// A run that is torn down (its future dropped — an abandoned tool call, a
    /// force-cancelled drain) takes its whole process tree with it: the
    /// kill-on-drop guard fires.
    #[cfg(unix)]
    #[tokio::test]
    async fn dropping_the_run_kills_the_command_process_tree() {
        let dir = TempDir::new().expect("tempdir");
        let (pid_path, mut cmd) = run_with_backgrounded_sleep(&dir);

        // The timeout drops the run's future, exactly as an aborted task does.
        let dropped = tokio::time::timeout(
            Duration::from_secs(2),
            run_command_with_timeout(
                &mut cmd,
                Duration::from_secs(30),
                Duration::from_secs(5),
                mem::default_limit(),
                RunOwner::Agent,
                LeftoverPolicy::Keep,
            ),
        )
        .await;
        assert!(
            dropped.is_err(),
            "the run must still be live when it is dropped"
        );

        wait_for_death(stopped_grandchild(&pid_path)).await;
    }

    /// A leftover process holding the output pipes open past the drain bound is
    /// not a failure for an agent's command: the run reports the command's own exit
    /// status, and the leftover is left RUNNING with its channel still open — a
    /// later write it makes reaches us rather than dying of SIGPIPE on a closed
    /// read end — while its process group is named for a stop.
    #[cfg(unix)]
    #[tokio::test]
    async fn output_drain_leaves_the_leftover_running_and_its_channel_open() {
        let dir = TempDir::new().expect("tempdir");
        let pid_path = dir.path().join("bg.pid");
        let marker = dir.path().join("after.txt");
        let pid_path_str = pid_path.to_str().expect("valid utf-8 path");
        let marker_str = marker.to_str().expect("valid utf-8 path");

        // Main command exits immediately; the backgrounded subshell inherits
        // stdout/stderr (no redirect), so EOF never arrives after sh exits. It
        // writes again well after the run returned: if the read end had been
        // dropped or the tree ended, that write would fail (SIGPIPE) and the
        // marker below would never appear.
        let cmd_str = format!(
            "echo before-drain; (sleep 1.5; echo after-run; echo done > {marker_str}) & \
             echo $! > {pid_path_str}"
        );
        let mut cmd = build_shell_command(&cmd_str, dir.path());

        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(30),
            Duration::from_millis(150),
            mem::default_limit(),
            RunOwner::Agent,
            LeftoverPolicy::Keep,
        )
        .await;
        let ShellRunResult::ExitedWithLeftovers {
            stdout,
            status,
            scope,
            elapsed,
            ..
        } = result
        else {
            panic!("expected ExitedWithLeftovers, got {result:?}");
        };
        let out = String::from_utf8_lossy(&stdout);
        assert!(out.contains("before-drain"), "partial stdout: {out}");
        assert_eq!(status.code(), Some(0), "the command's own status");
        assert!(scope.is_some(), "the containment root is named");
        assert!(
            elapsed < Duration::from_secs(5),
            "the run must return within the bound: {elapsed:?}"
        );

        // The leftover survived the call (it is still in its sleep) ...
        let pid_content = std::fs::read_to_string(&pid_path)
            .expect("grandchild PID file must exist — grandchild was launched");
        let pid: i32 = pid_content.trim().parse().expect("valid PID from file");
        // SAFETY: signal 0 performs the existence check only.
        assert_eq!(
            unsafe { libc::kill(pid, 0) },
            0,
            "the leftover must be left running"
        );

        // ... and the channel on our side stayed open, so its later write
        // succeeded and it carried on to write the marker.
        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        while !marker.exists() && std::time::Instant::now() < deadline {
            tokio::time::sleep(Duration::from_millis(25)).await;
        }
        assert!(
            marker.exists(),
            "the leftover's later write must reach the still-open channel"
        );
    }

    /// The leftover note is a note on a completed command, phrased in the
    /// platform's own terms and the mode's — both platforms and both modes are
    /// drivable from one host, which is why the platform is a value here. The stop
    /// recipe is Full mode's only: ReadOnly's guard rejects the commands it names.
    #[test]
    fn leftover_note_names_the_scope_and_the_platforms_stop_command() {
        let full_sentence = leftover_mode_sentence(ShellMode::Full);
        let read_only_sentence = leftover_mode_sentence(ShellMode::ReadOnly);

        let unix = format_leftover_note(ShellMode::Full, ShellPlatform::Unix, Some(1234));
        assert!(unix.contains("leftover process group: 1234"), "{unix}");
        assert!(unix.contains("kill -TERM -1234"), "{unix}");
        // The note carries the very fragment the tool description renders.
        assert!(unix.contains(&full_sentence), "{unix}");
        assert!(!unix.contains(&read_only_sentence), "{unix}");
        assert!(!unix.contains("drain"), "{unix}");
        assert!(!unix.contains("timed out"), "{unix}");

        // Windows: the run's root pid has already been reaped when this path is
        // reached, so the recipe lists the tree by parent rather than addressing
        // the released pid with `taskkill /PID <pid>`.
        let windows = format_leftover_note(ShellMode::Full, ShellPlatform::Windows, Some(42));
        assert!(
            windows.contains("leftover process tree: started by pid 42, which has already exited"),
            "{windows}"
        );
        assert!(
            windows.contains(r#"tasklist /FI "PPID eq 42""#),
            "{windows}"
        );
        assert!(
            windows.contains("taskkill /PID <listed pid> /T /F"),
            "{windows}"
        );
        assert!(!windows.contains("taskkill /PID 42"), "{windows}");

        // ReadOnly prints no stop line: the guard this mode runs rejects
        // `kill`/`pkill`/`killall` (and `taskkill`), so naming one would name a
        // command the mode refuses. Its own fragment states the limitation instead.
        let readonly = format_leftover_note(ShellMode::ReadOnly, ShellPlatform::Unix, Some(7));
        assert!(readonly.contains(&read_only_sentence), "{readonly}");
        assert!(!readonly.contains(&full_sentence), "{readonly}");
        assert!(!readonly.contains("background: true"), "{readonly}");
        assert!(!readonly.contains("kill"), "{readonly}");
        assert!(!readonly.contains("taskkill"), "{readonly}");
        let readonly_windows =
            format_leftover_note(ShellMode::ReadOnly, ShellPlatform::Windows, Some(42));
        assert!(!readonly_windows.contains("taskkill"), "{readonly_windows}");
        assert!(!readonly_windows.contains("tasklist"), "{readonly_windows}");

        let unknown = format_leftover_note(ShellMode::Full, ShellPlatform::Unix, None);
        assert!(unknown.contains("could not be identified"), "{unknown}");
        assert!(!unknown.contains("kill -TERM"), "{unknown}");
    }

    /// Short-lived backgrounded jobs that finish within the drain bound keep
    /// working — the drain completes normally.
    #[cfg(unix)]
    #[tokio::test]
    async fn output_drain_completes_for_short_lived_background_job() {
        let dir = TempDir::new().expect("tempdir");
        let mut cmd = build_shell_command("echo done; sleep 0.2 &", dir.path());
        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(30),
            Duration::from_secs(5),
            mem::default_limit(),
            RunOwner::Agent,
            LeftoverPolicy::Keep,
        )
        .await;
        let ShellRunResult::Completed { stdout, .. } = result else {
            panic!("expected Completed, got {result:?}");
        };
        assert!(String::from_utf8_lossy(&stdout).contains("done"));
    }

    /// A leftover process holding only ONE pipe (stdout EOFs, stderr hangs)
    /// still reports the completed side and the command's status without
    /// re-polling the completed reader (tokio panics on JoinHandle re-poll).
    #[cfg(unix)]
    #[tokio::test]
    async fn output_drain_keeps_the_completed_side_of_a_leftover() {
        let dir = TempDir::new().expect("tempdir");
        // The backgrounded sleep redirects stdout (releasing the shell's
        // stdout pipe → EOF) but inherits stderr, keeping it open past the bound.
        let mut cmd = build_shell_command("echo out; sleep 1.5 >/dev/null &", dir.path());
        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(30),
            Duration::from_millis(150),
            mem::default_limit(),
            RunOwner::Agent,
            LeftoverPolicy::Keep,
        )
        .await;
        let ShellRunResult::ExitedWithLeftovers { stdout, status, .. } = result else {
            panic!("expected ExitedWithLeftovers, got {result:?}");
        };
        assert_eq!(status.code(), Some(0));
        assert!(
            String::from_utf8_lossy(&stdout).contains("out"),
            "completed stdout side must be preserved: {stdout:?}"
        );
    }

    /// The [`LeftoverPolicy::End`] path — the program paths' — ends the run's tree
    /// at the drain bound: the leftover holder is killed, and the result is the
    /// failure those callers report ([`ShellRunResult::EndedWithLeftovers`]).
    #[cfg(unix)]
    #[tokio::test]
    async fn the_end_policy_kills_the_leftover_holder() {
        let dir = TempDir::new().expect("tempdir");
        let pid_path = dir.path().join("bg.pid");
        let pid_path_str = pid_path.to_str().expect("valid utf-8 path");
        let cmd_str = format!("echo before-end; sleep 5 & echo $! > {pid_path_str}");
        let mut cmd = build_shell_command(&cmd_str, dir.path());

        let result = run_command_with_timeout(
            &mut cmd,
            Duration::from_secs(30),
            Duration::from_millis(150),
            mem::default_limit(),
            RunOwner::Agent,
            LeftoverPolicy::End,
        )
        .await;
        let ShellRunResult::EndedWithLeftovers { stdout, .. } = result else {
            panic!("expected EndedWithLeftovers, got {result:?}");
        };
        assert!(
            String::from_utf8_lossy(&stdout).contains("before-end"),
            "the output collected up to the bound is the failure's to report: {stdout:?}"
        );

        let pid_content = std::fs::read_to_string(&pid_path)
            .expect("grandchild PID file must exist — grandchild was launched");
        let pid: i32 = pid_content.trim().parse().expect("valid PID from file");
        wait_for_death(pid).await;
    }

    /// A command that exited 0 but left a process holding its output is a SUCCESS
    /// through the tool: its own output plus a labelled leftover note, never a
    /// drain error.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_command_that_exited_0_with_a_leftover_is_a_success() {
        let _env = set_env_var("MAHBOT_SHELL_DRAIN_TIMEOUT_SECS", Some("1"));
        let tmp = TempDir::new().expect("tempdir");
        let ws = test_ws(tmp.path());

        let (output, code) = ShellTool::new(ShellMode::Full)
            .execute_with_status(&ws, json!({"command": "echo out; sleep 1.5 &"}))
            .await
            .expect("a completed command is not a tool error");

        assert_eq!(code, Some(0), "the command's own status: {output}");
        assert!(output.contains("out"), "output: {output}");
        assert!(output.contains("[leftover process]"), "output: {output}");
        assert!(output.contains("kill -TERM -"), "output: {output}");
        assert!(
            !output.contains("drain"),
            "never the drain error on a finished command: {output}"
        );
    }

    // ── Shell compression pipeline tests ────────────────────────────

    #[test]
    fn pipeline_credential_scrubbing_cases() {
        // Pipeline entry scrubs both stdout and stderr; on_empty (Stage 5)
        // also verifies scrubbing in stderr.
        // Each case follows the same pattern: raw credentials not present,
        // redacted form present, pipeline-specific content preserved.
        let cases: &[ShellOutputCase] = &[
            ShellOutputCase {
                // Stage 5 (on-empty): credentials from stderr are scrubbed
                // (via git diff profile's on_empty message)
                name: "git diff on_empty scrubs credentials in stderr",
                command: "git diff",
                stderr: "api_key=abcdefghijklmnop12345678",
                exit_code: 1,
                not_contains: &["api_key=abcdefghijklmnop12345678"],
                contains: &["api_key=abcd*[REDACTED]", "no changes"],
                ..Default::default()
            },
            ShellOutputCase {
                // Stage 5 (on-empty): credentials from stderr are scrubbed.
                // Uses a `warning:` prefix so the line passes through the
                // keep_stderr filter even on the failure path.
                name: "on-empty scrubs credentials in stderr",
                command: "tsc --noEmit",
                stderr: "warning: api_key=abcdefghijklmnop12345678",
                exit_code: 1,
                not_contains: &["api_key=abcdefghijklmnop12345678"],
                contains: &["api_key=abcd*[REDACTED]", "[tsc: ok]"],
                ..Default::default()
            },
            ShellOutputCase {
                // Main pipeline path (all stages applied, no early-return):
                // stdout credentials are scrubbed at pipeline entry before any
                // downstream stage processes them.
                name: "main pipeline scrubs credentials in stdout",
                command: "echo test",
                stdout: "API_KEY=abcdefghijklmnop12345678",
                not_contains: &["abcdefghijklmnop12345678"],
                contains: &["API_KEY=abcd*[REDACTED]"],
                ..Default::default()
            },
        ];
        check_shell_output(cases);
    }

    #[test]
    fn truncate_line_width_short_and_long() {
        // Long lines truncated with continuation marker
        let long = "a".repeat(500);
        let result = truncate_line_width(&long, 100);
        assert!(result.len() < long.len() + 100, "should truncate");
        assert!(
            result.contains("more chars on this line"),
            "should show continuation marker"
        );
        let lines: Vec<&str> = result.lines().collect();
        assert_eq!(lines.len(), 2, "truncated line + continuation marker");
        assert_eq!(
            lines[0].len(),
            100,
            "first line should be exactly max_chars"
        );
        assert!(
            !lines[0].contains("..."),
            "first line should not contain truncation marker"
        );

        // Short lines preserved unchanged
        let input = "hello\nworld";
        let result = truncate_line_width(input, 500);
        assert_eq!(result, input, "short lines should pass through");
    }

    #[test]
    fn try_spill_to_file_behavior() {
        // Small output passes through unchanged
        let short = "hello".to_string();
        let result = try_spill_to_file(short, TOOL_OUTPUT_BUDGET_BYTES);
        assert_eq!(result, "hello", "short output should pass through");

        // Large single-line output spills
        let large = "x".repeat(TOOL_OUTPUT_BUDGET_BYTES * 2);
        let result = try_spill_to_file(large, TOOL_OUTPUT_BUDGET_BYTES);
        assert!(
            result.contains("[Output saved to"),
            "should contain spill path"
        );
        assert!(
            result.contains("10000 bytes"),
            "should mention byte count: {result}"
        );

        // Multi-line large output shows head+tail preview
        let lines: Vec<String> = (0..800).map(|i| format!("line_{i:04}")).collect();
        let multi = lines.join("\n");
        let multi_len = multi.len();
        assert!(
            multi_len > TOOL_OUTPUT_BUDGET_BYTES,
            "test data {multi_len} must exceed spill threshold"
        );
        let result = try_spill_to_file(multi, TOOL_OUTPUT_BUDGET_BYTES);
        assert!(
            result.contains("[Output saved to"),
            "should contain spill path"
        );
        assert!(
            result.contains("[view with: read "),
            "should contain actionable read hint"
        );
        assert!(result.contains("line_0000"), "should show first line");
        assert!(result.contains("line_0799"), "should show last line");
        assert!(
            result.len() < multi_len,
            "inline preview should be truncated"
        );

        // Ensure the spill dir exists
        assert!(
            std::fs::read_dir(std::env::temp_dir().join(".agent")).is_ok(),
            "spill dir should exist"
        );
    }

    /// The `PATH` of the reduced fallback environment covers the tool
    /// directories a developer expects (`~/.cargo/bin`, `~/.npm-global/bin`,
    /// Homebrew on macOS) and honors `$CARGO_HOME`. This is the fallback
    /// `PATH` — what the product's internal work and an unread owner
    /// environment get — not the owner's own `PATH`, which replaces it once a
    /// read has succeeded.
    #[test]
    fn resolved_shell_path_covers_tool_dirs() {
        #[cfg(unix)]
        {
            let path = resolved_shell_path();
            assert!(
                path.contains(".npm-global/bin"),
                "PATH should include ~/.npm-global/bin for globally installed npm tools: {path}"
            );
            // Belt-and-suspenders means ~/.cargo/bin is always added regardless
            // of $CARGO_HOME, so it shows up in both CARGO_HOME cases below.
            assert!(
                path.contains(".cargo/bin"),
                "PATH should include ~/.cargo/bin: {path}"
            );
            assert!(
                path.contains(".local/bin"),
                "PATH should include the per-user programs directory ~/.local/bin, where the product installs itself: {path}"
            );
            {
                let _guard = set_env_var("CARGO_HOME", Some("/custom/cargo"));
                let path = resolved_shell_path();
                assert!(
                    path.contains("/custom/cargo/bin"),
                    "PATH should include $CARGO_HOME/bin when CARGO_HOME is set: {path}"
                );
                assert!(
                    path.contains(".cargo/bin"),
                    "PATH should still include ~/.cargo/bin when CARGO_HOME is set (belt-and-suspenders): {path}"
                );
            }
            // $CARGO_HOME/bin and ~/.cargo/bin must deduplicate when they point
            // to the same directory (skipped when no home directory exists).
            if let Some(dirs) = UserDirs::new() {
                let default_cargo_home = dirs
                    .home_dir()
                    .join(".cargo")
                    .to_string_lossy()
                    .into_owned();
                let _guard = set_env_var("CARGO_HOME", Some(&default_cargo_home));
                let path = resolved_shell_path();
                let count = path
                    .split(':')
                    .filter(|part| *part == format!("{default_cargo_home}/bin"))
                    .count();
                assert_eq!(
                    count, 1,
                    "$CARGO_HOME/bin and ~/.cargo/bin should deduplicate when they point to the same directory: {path}"
                );
            }
        }
        #[cfg(target_os = "macos")]
        {
            let path = resolved_shell_path();
            assert!(
                path.contains("/opt/homebrew/bin"),
                "PATH should include Homebrew bin on macOS: {path}"
            );
        }
    }

    // ── New feature tests ───────────────────────────────────────────

    #[test]
    fn collapse_blank_lines_cases() {
        let cases: &[(&str, &str)] = &[
            // 3+ consecutive blank lines collapse to 2
            ("a\n\n\n\nb\n\n\nc", "a\n\n\nb\n\n\nc"),
            // runs ≤2 left alone, longer runs collapse to 2
            ("a\n\nb\n\n\nc\n\n\n\nd", "a\n\nb\n\n\nc\n\n\nd"),
            // no blank lines → pass through unchanged
            ("a\nb\nc", "a\nb\nc"),
            // all-blank input collapses completely (no anchor lines)
            ("\n\n\n\n\n", ""),
        ];
        for (input, expected) in cases {
            let result = collapse_blank_lines(input);
            assert_eq!(result, *expected, "input: {input:?}");
        }
    }

    // ── Chained command and canonical command tests ─────────────────

    #[test]
    fn extract_segments_cases() {
        let cases: &[(&str, &[&str])] = &[
            // simple single command
            ("cargo build", &["cargo build"]),
            // chained with &&
            ("cd project && cargo build", &["cd project", "cargo build"]),
            // pipe (|) splits commands
            (
                "npm run build 2>&1 | tee build.log",
                &["npm run build 2>&1", "tee build.log"],
            ),
            // single quotes protect && and | from being treated as separators
            ("echo 'foo && bar' | cat", &["echo 'foo && bar'", "cat"]),
            // semicolon splits commands
            ("cargo build ; cargo test", &["cargo build", "cargo test"]),
            // single-quoted && preserved as one segment
            ("echo 'foo && bar'", &["echo 'foo && bar'"]),
            // double-quoted pipe preserved as one segment
            ("echo \"pipe | test\"", &["echo \"pipe | test\""]),
            // ── Newline as command separator ──────────────────────
            (
                "touch /tmp/a\necho hi > /tmp/b",
                &["touch /tmp/a", "echo hi > /tmp/b"],
            ),
            // Backslash-newline continuation joins the logical line.
            ("echo hello \\\nworld", &["echo hello world"]),
            // Heredoc bodies are removed before segmentation (never commands).
            ("cat <<EOF\nbody\nEOF", &["cat"]),
            (
                "cat <<EOF > /tmp/out\nbody\nEOF",
                &["cat   > /tmp/out"], // `<<EOF` marker replaced by a space
            ),
            // Herestrings have no body — the whole line stays one segment.
            ("cat <<< hi > /tmp/out", &["cat <<< hi > /tmp/out"]),
            // `>|` compound redirect is not split at the pipe.
            ("echo hi >| /tmp/force", &["echo hi >| /tmp/force"]),
            // ── Command substitutions stay whole ────────────────────
            // Separators inside `$(...)` are part of the substitution, not
            // command separators (mis-splitting flips is_chained and skips
            // standalone-only output transforms).
            ("echo $(echo hi; touch x)", &["echo $(echo hi; touch x)"]),
            ("echo $(echo hi) ; touch x", &["echo $(echo hi)", "touch x"]),
            ("echo `echo hi; touch x`", &["echo `echo hi; touch x`"]),
            (
                "cd /tmp && echo $(echo a && echo b)",
                &["cd /tmp", "echo $(echo a && echo b)"],
            ),
            // Nested substitution stays inside the outer one.
            ("echo $(echo $(ls; pwd))", &["echo $(echo $(ls; pwd))"]),
            // Nested `$(` adds exactly one paren; a real `;` after it splits.
            (
                "echo $(echo $(echo hi)) ; touch x",
                &["echo $(echo $(echo hi))", "touch x"],
            ),
            // Plain parens inside a substitution nest too: the `;` is body.
            (
                "echo $( (echo hi) ; echo more) tail",
                &["echo $( (echo hi) ; echo more) tail"],
            ),
            // Arithmetic with parens: `&&` inside `$((...))` is body content.
            (
                "echo $(( (a) && (b) )) tail",
                &["echo $(( (a) && (b) )) tail"],
            ),
            // `$((...))` nested inside `$(...)`.
            (
                "echo $(echo $((a+1)); echo x)",
                &["echo $(echo $((a+1)); echo x)"],
            ),
            // Substitution with newline inside stays whole.
            ("echo $(echo hi\necho bye)", &["echo $(echo hi\necho bye)"]),
            // Heredoc body with a substitution: the body substitution is
            // emitted as its own segment (it must remain scanned — bash
            // executes `$()` inside unquoted heredoc bodies).
            ("cat <<EOF\n$(touch ws)\nEOF", &["cat", "$(touch ws)"]),
            // Double-quoted substitutions stay whole too: a `;` inside
            // `"$(...)"` is part of the substitution, not a separator, and
            // bash executes the body, so segmentation must not fragment it.
            (
                "echo \"$(echo hi; touch x)\"",
                &["echo \"$(echo hi; touch x)\""],
            ),
            (
                "echo \"$(echo hi)\" ; touch x",
                &["echo \"$(echo hi)\"", "touch x"],
            ),
            (
                "echo \"`echo hi; touch x`\"",
                &["echo \"`echo hi; touch x`\""],
            ),
            // Escape-aware: `\)` is body content, not a substitution closer.
            (
                "echo $(echo \\)) ; touch x",
                &["echo $(echo \\))", "touch x"],
            ),
            // Escaped backticks inside a backtick substitution don't close it.
            (
                "echo `echo \\`hi\\`` ; touch x",
                &["echo `echo \\`hi\\``", "touch x"],
            ),
            // `\'` inside `$(...)`: the closing quote is not swallowed.
            (
                "echo $(echo 'a\\') ; touch x",
                &["echo $(echo 'a\\')", "touch x"],
            ),
        ];
        for (input, expected) in cases {
            let result = extract_command_segments(input);
            assert_eq!(
                result.iter().map(String::as_str).collect::<Vec<_>>(),
                *expected,
                "input: {input:?}"
            );
        }
    }

    #[test]
    fn canonical_command_cases() {
        // Each case: (input, expected_output) — organized by theme.
        // Adding a new case is one line; include an inline comment explaining why.
        let cases: &[(&str, &str)] = &[
            // ── Path stripping ──────────────────────────────────────
            ("/usr/local/bin/cargo build", "cargo build"),
            // ── Git global flags ────────────────────────────────────
            ("git -C /repo diff", "git diff"),
            ("git -c user.name=me log", "git log"),
            ("git -- diff", "git diff"), // -- is treated as a flag and skipped
            // ── Shell prefix: sudo ──────────────────────────────────
            ("sudo cargo build", "cargo build"),
            ("sudo -E cargo build", "cargo build"), // -E flag between prefix and command
            ("sudo --preserve-env cargo build", "cargo build"), // --preserve-env flag
            ("sudo -E git -C /repo diff", "git diff"), // compound: multiple flags + subcommand
            // ── Shell prefix: time ─────────────────────────────────
            ("time -v cargo test", "cargo test"), // -v flag skipped
            // ── cd (shell builtin) ─────────────────────────────────
            ("cd", ""),      // all shell prefixes, no command → empty
            ("cd ..", ".."), // path segment only — won't match anything but shouldn't crash
            // ── Package managers ───────────────────────────────────
            ("pnpm install", "pnpm install"),
            ("yarn add foo", "yarn add"),
            // ── Cargo flags ────────────────────────────────────────
            ("cargo test --lib", "cargo test"),
            ("cargo --release build", "cargo build"),
            // Only flags without values are skipped for non-git commands.
            // --release and --verbose don't take values, so both are skipped.
            ("cargo --release --verbose build", "cargo build"),
            // ── Toolchain specifiers and stderr-capture suffixes ───
            // `+nightly`-style toolchain specifiers and `2>&1`/`1>&2` suffixes
            // must never become the parsed subcommand.
            ("cargo +nightly build", "cargo build"),
            ("cargo +stable check", "cargo check"),
            ("cargo build 2>&1", "cargo build"),
            ("cargo --version 2>&1", "cargo"),
            ("git --version 2>&1", "git"),
            ("git status 2>&1", "git status"),
            // ── Environment variable assignments ───────────────────
            ("CC=gcc make", "make"), // env assignment before command
            ("VAR=val cargo check", "cargo check"),
            ("CC=gcc CXX=g++ make -j4", "make"), // multiple env assignments
            ("CC=gcc", ""),                      // only env assignments, no command
            ("sudo CC=gcc make", "make"),        // prefix + env assignment + command
            // ── pytest dead-branch documentation ──────────────────────
            // These cases document why `python -m pytest` and
            // `poetry run pytest` cannot match the pytest profile:
            // canonical_command strips `-m` (flag), producing "python pytest"
            // that doesn't start with "pytest"; and treats `run` as the
            // subcommand of `poetry`, producing "poetry run".
            ("python -m pytest tests/", "python pytest"),
            ("poetry run pytest tests/", "poetry run"),
            // ── npx (shell prefix) ─────────────────────────────────────
            // npx is a shell prefix, so it's stripped before command extraction.
            // Tool-specific profiles (eslint, prettier, vitest, etc.) now match
            // correctly instead of being shadowed by the generic npx catch-all.
            ("npx eslint", "eslint"),
            ("npx eslint .", "eslint ."),
            ("npx eslint --fix .", "eslint ."),
            ("npx --yes eslint .", "eslint ."),
            ("npx prettier --check file.js", "prettier file.js"),
            ("npx vitest --run", "vitest"),
            ("npx tsc --noEmit", "tsc"),
            (
                "npx --yes create-react-app my-app",
                "create-react-app my-app",
            ),
        ];
        for &(input, expected) in cases {
            assert_eq!(
                canonical_command(input),
                expected,
                "canonical_command({input:?})",
            );
        }
    }

    /// A quoted path spelling profiles like its unquoted twin. Profiles are
    /// selected from the original command string, so this is what gives an
    /// agent-written `'/usr/local/bin/cargo' build` the cargo output treatment.
    #[cfg(unix)]
    #[test]
    fn quoted_path_spelling_selects_the_same_profile_as_its_unquoted_twin() {
        let selected = |command: &str| {
            let segments = extract_command_segments(command);
            select_profile(&segments, false)
                .match_command
                .as_str()
                .to_owned()
        };
        let quoted = selected("'/usr/local/bin/cargo' build");
        assert_eq!(quoted, selected("/usr/local/bin/cargo build"));
        // Non-vacuity: an unrelated command must NOT select that same profile.
        assert_ne!(quoted, selected("'/usr/local/bin/true' build"));
    }

    #[test]
    fn first_command_word_consistent_with_canonical() {
        // Property: first_command_word returns the first word of canonical_command's
        // result, or empty when canonical_command is empty.
        let inputs: &[&str] = &[
            // Path stripping
            "/usr/local/bin/cargo build",
            // Git global flags
            "git -C /repo diff",
            "git -c user.name=me log",
            "git -- diff",
            // Shell prefix: sudo
            "sudo cargo build",
            "sudo -E cargo build",
            "sudo --preserve-env cargo build",
            "sudo -E git -C /repo diff",
            // Shell prefix: time
            "time -v cargo test",
            // cd (shell builtin)
            "cd",
            "cd ..",
            // Package managers
            "pnpm install",
            "yarn add foo",
            // Cargo flags
            "cargo test --lib",
            "cargo --release build",
            "cargo --release --verbose build",
            // Environment variable assignments
            "CC=gcc make",
            "VAR=val cargo check",
            "CC=gcc CXX=g++ make -j4",
            "CC=gcc",
            "sudo CC=gcc make",
            // Edge cases
            "",
            "   ",
            "ls",
            "cat file.txt",
            "/bin/echo hello",
        ];
        for &input in inputs {
            let canonical = canonical_command(input);
            let first = first_command_word(input);
            if canonical.is_empty() {
                assert!(
                    first.is_empty(),
                    "first_command_word({input:?}) should be empty when canonical_command is empty",
                );
            } else {
                let expected_first = canonical.split_whitespace().next().unwrap_or("");
                assert_eq!(
                    first, expected_first,
                    "first_command_word({input:?}) should match first word of canonical_command({input:?}) = {canonical:?}",
                );
            }
        }
    }

    #[test]
    fn test_all_profiles_have_valid_configs() {
        let profiles = PROFILES.iter().collect::<Vec<_>>();
        assert!(
            !profiles.is_empty(),
            "should have at least the generic fallback"
        );
        for p in &profiles {
            assert!(
                !p.match_command.as_str().is_empty(),
                "match_command should not be empty"
            );
            if let (Some(head), Some(tail), Some(max)) = (p.head_lines, p.tail_lines, p.max_lines) {
                assert!(
                    head + tail < max,
                    "head+tail ({head}+{tail}) should be strictly less than max_lines ({max}) — omission marker would overflow"
                );
            }
        }
    }

    #[test]
    fn profile_df_caps_at_20_lines() {
        let input = (0..50)
            .map(|i| format!("filesystem{i}  used  avail capacity mounted_on"))
            .collect::<Vec<_>>()
            .join("\n");
        let result = process_shell_output("df -h", &input, "", 0, Duration::ZERO);
        let lines = result.lines().count();
        // 20 lines + 1 truncated note line = 21 max
        assert!(lines <= 21, "df should cap at ~21 lines, got {lines}");
        assert!(lines >= 19, "df should have around 20 lines, got {lines}");
    }

    // ── check_outside_quotes ──────────────────────────────────────────
    // Pure quote-tracking state machine — escape handling is caller's concern.

    type QuoteStep = (char, bool, bool, bool);

    #[test]
    fn check_outside_quotes_cases() {
        // Each case: (name, &[(char, expected_return, in_single, in_double)])
        let cases: &[(&str, &[QuoteStep])] = &[
            ("normal char outside", &[('a', true, false, false)]),
            (
                "single quote blocks",
                &[
                    ('\'', false, true, false),
                    ('>', false, true, false),
                    ('\'', false, false, false),
                    ('>', true, false, false),
                ],
            ),
            (
                "double quote blocks",
                &[
                    ('"', false, false, true),
                    ('>', false, false, true),
                    ('"', false, false, false),
                    ('>', true, false, false),
                ],
            ),
            (
                "single inside double",
                &[('"', false, false, true), ('\'', false, false, true)],
            ),
            (
                "double inside single",
                &[('\'', false, true, false), ('"', false, true, false)],
            ),
        ];

        for (name, steps) in cases {
            let (mut s, mut d) = (false, false);
            for (i, &(ch, exp_out, exp_s, exp_d)) in steps.iter().enumerate() {
                let result = check_outside_quotes(ch, &mut s, &mut d);
                assert_eq!(
                    result, exp_out,
                    "{name} step {i}: check_outside_quotes({ch:?}) returned {result}, expected {exp_out}",
                );
                assert_eq!(
                    s, exp_s,
                    "{name} step {i}: after {ch:?}, in_single={s}, expected {exp_s}",
                );
                assert_eq!(
                    d, exp_d,
                    "{name} step {i}: after {ch:?}, in_double={d}, expected {exp_d}",
                );
            }
        }
    }

    // ── track_char_context ───────────────────────────────────────────
    // Combined escape + quote tracking state machine.

    type ContextStep = (char, bool, bool, bool, bool);

    #[test]
    fn track_char_context_cases() {
        // Each case: (char, expected_return, in_single, in_double, escaped)
        // The `escaped` column shows the flag AFTER processing the character.
        let cases: &[(&str, &[ContextStep])] = &[
            (
                "backslash escapes outside quotes",
                &[
                    ('\\', false, false, false, true), // backslash sets escaped
                    ('a', false, false, false, false), // escaped 'a' consumed, skip
                    ('a', true, false, false, false),  // normal 'a' outside quotes
                ],
            ),
            (
                "escaped backslash",
                &[
                    ('\\', false, false, false, true),  // first backslash sets escaped
                    ('\\', false, false, false, false), // second backslash: escaped flag was set, consume it; does NOT start new escape
                    ('a', true, false, false, false),   // normal 'a' outside quotes
                ],
            ),
            (
                "escaped quote inside double does not toggle",
                &[
                    ('"', false, false, true, false),  // double opens
                    ('\\', false, false, true, true),  // backslash inside double, sets escaped
                    ('"', false, false, true, false), // escaped quote consumed, doesn't toggle double
                    ('"', false, false, false, false), // unescaped quote closes double
                ],
            ),
            (
                "backslash inside single is literal",
                &[
                    ('\'', false, true, false, false),  // single opens
                    ('\\', false, true, false, false), // backslash inside single: not escape, still inside
                    ('a', false, true, false, false),  // inside single quotes
                    ('\'', false, false, false, false), // single closes
                    ('>', true, false, false, false),  // outside quotes again
                ],
            ),
        ];

        for (name, steps) in cases {
            let (mut s, mut d, mut e) = (false, false, false);
            for (i, &(ch, exp_out, exp_s, exp_d, exp_e)) in steps.iter().enumerate() {
                let result = track_char_context(ch, &mut s, &mut d, &mut e);
                assert_eq!(
                    result, exp_out,
                    "{name} step {i}: track_char_context({ch:?}) returned {result}, expected {exp_out}",
                );
                assert_eq!(
                    s, exp_s,
                    "{name} step {i}: after {ch:?}, in_single={s}, expected {exp_s}",
                );
                assert_eq!(
                    d, exp_d,
                    "{name} step {i}: after {ch:?}, in_double={d}, expected {exp_d}",
                );
                assert_eq!(
                    e, exp_e,
                    "{name} step {i}: after {ch:?}, escaped={e}, expected {exp_e}",
                );
            }
        }
    }

    // ── apply_line_truncation unit tests ──────────────────────────────

    struct TruncateCase {
        name: &'static str,
        head: usize,
        tail: usize,
        max: Option<usize>,
        output: &'static str,
        pre_is_some: bool,
        check_contains: &'static [&'static str],
    }

    fn check_truncate(cases: &[TruncateCase]) {
        for case in cases {
            let mut p = Profile::new("test");
            if case.head > 0 || case.tail > 0 {
                p = p.head(case.head).tail(case.tail);
            }
            if let Some(m) = case.max {
                p = p.max(m);
            }
            let (result, pre) = apply_line_truncation(case.output, &p);
            assert_eq!(
                pre.is_some(),
                case.pre_is_some,
                "[{}] pre.is_some mismatch. pre: {pre:?}",
                case.name
            );
            assert_contains_not_contains(case.name, &result, case.check_contains, &[]);
        }
    }

    #[test]
    fn truncate_simple_cases() {
        check_truncate(&[
            TruncateCase {
                name: "no config passthrough",
                head: 0,
                tail: 0,
                max: None,
                output: "line1\nline2\nline3",
                pre_is_some: false,
                check_contains: &["line1\nline2\nline3"],
            },
            TruncateCase {
                name: "head+tail small output no sandwich",
                head: 2,
                tail: 2,
                max: None,
                output: "line1\nline2\nline3\nline4\nline5",
                pre_is_some: false,
                check_contains: &["line1\nline2\nline3\nline4\nline5"],
            },
            TruncateCase {
                name: "max only caps at limit",
                head: 0,
                tail: 0,
                max: Some(3),
                output: "a\nb\nc\nd\ne",
                pre_is_some: false,
                check_contains: &["... (2 lines truncated)"],
            },
            TruncateCase {
                name: "max only fits no truncation",
                head: 0,
                tail: 0,
                max: Some(10),
                output: "a\nb\nc",
                pre_is_some: false,
                check_contains: &["a\nb\nc"],
            },
            TruncateCase {
                name: "head+tail fits when under limit",
                head: 5,
                tail: 3,
                max: None,
                output: "a\nb\nc\nd",
                pre_is_some: false,
                check_contains: &["a\nb\nc\nd"],
            },
            // head=2, tail=2, max=3 on 5-line output: small output bypasses sandwich,
            // so max cap is the only active truncation → 3 lines + marker = 4 total.
            TruncateCase {
                name: "head+tail+max small output no sandwich",
                head: 2,
                tail: 2,
                max: Some(3),
                output: "a\nb\nc\nd\ne",
                pre_is_some: false,
                check_contains: &["... (2 lines truncated)"],
            },
        ]);
    }

    #[test]
    fn truncate_head_tail_triggers_sandwich_large_output() {
        let p = Profile::new("test").head(2).tail(2);
        // Generate output large enough to exceed TOOL_OUTPUT_BUDGET_BYTES
        let lines: Vec<String> = (0..100)
            .map(|i| {
                format!(
                    "line {i} aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                )
            })
            .collect();
        let output = lines.join("\n");
        assert!(
            output.len() > TOOL_OUTPUT_BUDGET_BYTES,
            "test output must exceed threshold (got {} bytes)",
            output.len()
        );

        let (result, pre) = apply_line_truncation(&output, &p);
        assert!(pre.is_some(), "should capture pre-truncation output");
        assert!(
            result.contains("... (96 lines omitted)"),
            "should have omission marker"
        );
        assert!(
            result.starts_with("line 0 aaaaaaaa"),
            "should start with head"
        );
        assert!(
            result.ends_with("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
            "should end with tail"
        );
        // Also verify that adding max=N doesn't change behavior when
        // head+tail+1 <= N (sandwich format is already smaller than cap).
        let p2 = Profile::new("test").head(2).tail(2).max(100);
        let (result2, pre2) = apply_line_truncation(&output, &p2);
        assert!(pre2.is_some(), "should capture pre-truncation output");
        assert!(
            result2.contains("... (96 lines omitted)"),
            "should have sandwich omission marker"
        );
        assert!(
            !result2.contains("lines truncated"),
            "sandwich should not be additionally truncated when head+tail+1 <= max"
        );
    }

    // ── format_sandwich tests ──────────────────────────────────────────

    #[test]
    fn format_sandwich_cases() {
        let cases: &[(&str, usize, usize, &str)] = &[
            // (input, head, tail, expected)
            ("a\nb\nc", 2, 2, "a\nb\nc"),
            (
                "a\nb\nc\nd\ne\nf\ng",
                2,
                2,
                "a\nb\n... (3 lines omitted)\nf\ng",
            ),
            ("a\nb\nc\nd\ne\nf\ng", 7, 0, "a\nb\nc\nd\ne\nf\ng"),
            ("a\nb\nc\nd\ne\nf\ng", 0, 7, "a\nb\nc\nd\ne\nf\ng"),
            // Head-only truncation (e.g., git log profile: head=20, no tail)
            (
                "a\nb\nc\nd\ne\nf\ng",
                3,
                0,
                "a\nb\nc\n... (4 lines omitted)",
            ),
            // Tail-only truncation (e.g., ping/gh/helm profiles: tail=4..10, no head)
            (
                "a\nb\nc\nd\ne\nf\ng",
                0,
                3,
                "... (4 lines omitted)\ne\nf\ng",
            ),
        ];
        for (input, head, tail, expected) in cases {
            let result = format_sandwich(input, *head, *tail, "omitted");
            assert_eq!(
                result, *expected,
                "format_sandwich({input:?}, {head}, {tail})"
            );
        }
    }

    // ── finish_shell_output unit tests ────────────────────────────────
    // Credential scrubbing is now performed upstream at pipeline entry in
    // `apply_profile_pipeline`, so `finish_shell_output` receives pre-scrubbed
    // input.  These tests verify that non-scrubbing behavior (timing, spill,
    // idempotence) remains correct.

    struct FinishCase {
        name: &'static str,
        combined: &'static str,
        elapsed: Duration,
        pre: Option<&'static str>,
        check: &'static [&'static str], // all must be contained in result
        not_check: &'static [&'static str], // none must be contained
        eq: Option<&'static str>,
    }

    fn check_finish(cases: &[FinishCase]) {
        for case in cases {
            // For pre-truncation spill path: repeat the string enough times to
            // exceed TOOL_OUTPUT_BUDGET_BYTES, triggering the spill-to-file branch
            // in finish_shell_output. The spill content is pre-scrubbed by
            // apply_profile_pipeline before being passed to finish_shell_output.
            // This test verifies that the spill hint is properly appended.
            let pre_owned = case.pre.map(|s| s.repeat(TOOL_OUTPUT_BUDGET_BYTES + 1));
            let result = finish_shell_output(
                case.combined.to_string(),
                case.elapsed,
                pre_owned.as_deref(),
            );
            assert_contains_not_contains(case.name, &result, case.check, case.not_check);
            if let Some(expected) = case.eq {
                assert_eq!(result.trim(), expected, "[{}] expected eq", case.name);
            }
        }
    }

    #[test]
    fn finish_shell_output_cases() {
        check_finish(&[
            FinishCase {
                name: "pre-scrubbed input passes through",
                combined: "API_KEY=abcd*[REDACTED]",
                elapsed: Duration::ZERO,
                pre: None,
                check: &["abcd*[REDACTED]"],
                not_check: &["abcdefghijklmnop"],
                eq: None,
            },
            FinishCase {
                name: "pre-scrubbed combined in spill path",
                combined: "SECRET=wxyz*[REDACTED]",
                elapsed: Duration::ZERO,
                pre: Some("x"),
                check: &["wxyz*[REDACTED]", "[Output saved to"],
                not_check: &["wxyz1234abcdefgh"],
                eq: None,
            },
            FinishCase {
                name: "preserves clean output",
                combined: "no credentials here",
                elapsed: Duration::ZERO,
                pre: None,
                check: &[],
                not_check: &[],
                eq: Some("no credentials here"),
            },
            FinishCase {
                name: "appends elapsed timing with pre-scrubbed input",
                combined: "API_KEY=abcd*[REDACTED]",
                elapsed: Duration::from_secs(5),
                pre: None,
                check: &["[took 5.0s]", "abcd*[REDACTED]"],
                not_check: &["abcdefghijklmnop"],
                eq: None,
            },
            FinishCase {
                name: "scrub idempotent",
                combined: "API_KEY=abcd*[REDACTED]",
                elapsed: Duration::ZERO,
                pre: None,
                check: &[],
                not_check: &[],
                eq: Some("API_KEY=abcd*[REDACTED]"),
            },
        ]);
    }

    /// The fragments of every shared prompt skeleton must be embedded, and must
    /// carry no placeholder of their own: `substitute` does not rescan a
    /// replacement value. Each skeleton must keep exactly the keys its renderer
    /// supplies — a stray one would render literally into every agent's
    /// description. The renderers pick the fragment through `SHELL_PLATFORM`, or
    /// (the command-line notes and the leftover notes) through the mode, so a typo
    /// in a key would otherwise panic on that platform's host only. The leftover
    /// skeleton is sectioned instead: its second section is the per-call note's own
    /// lead, rendered with no substitution at all, so it must carry no key.
    #[test]
    fn platform_prompt_assets_are_embedded() {
        for (skeleton, keys, fragments) in [
            (
                "tool/shell_readonly_banner.md",
                ["{{temp_root}}", "{{platform_checks}}"].as_slice(),
                [
                    "tool/shell_readonly_banner_unix.md",
                    "tool/shell_readonly_banner_windows.md",
                ]
                .as_slice(),
            ),
            (
                "tool/shell_grep_notes.md",
                ["{{platform_notes}}"].as_slice(),
                [
                    "tool/shell_grep_notes_unix.md",
                    "tool/shell_grep_notes_windows.md",
                ]
                .as_slice(),
            ),
            (
                "tool/shell_full.md",
                ["{{stop_semantics}}", "{{trailing_separator}}"].as_slice(),
                [
                    "tool/shell_full_stop_unix.md",
                    "tool/shell_full_stop_windows.md",
                    "tool/shell_full_trailing_unix.md",
                    "tool/shell_full_trailing_windows.md",
                ]
                .as_slice(),
            ),
            (
                "tool/shell_command_lines.md",
                [
                    "{{escaped_target}}",
                    "{{remedy}}",
                    "{{cap}}",
                    "{{overhead}}",
                    "{{limit}}",
                ]
                .as_slice(),
                [
                    "tool/shell_command_lines_escaped_full.md",
                    "tool/shell_command_lines_escaped_read_only.md",
                    "tool/shell_command_lines_read_only_aside.md",
                    "tool/shell_command_lines_remedy_full.md",
                    "tool/shell_command_lines_remedy_read_only.md",
                ]
                .as_slice(),
            ),
            (
                "tool/shell_leftover.md",
                ["{{mode_sentence}}"].as_slice(),
                [
                    "tool/shell_leftover_full.md",
                    "tool/shell_leftover_read_only.md",
                ]
                .as_slice(),
            ),
        ] {
            let shared = crate::prompt::load_prompt(skeleton);
            let mut rest = shared.clone();
            for key in keys {
                assert!(shared.contains(key), "{skeleton} lost {key}");
                rest = rest.replace(key, "");
            }
            assert!(!rest.contains("{{"), "{skeleton} carries an unrendered key");
            for asset in fragments {
                let text = crate::prompt::load_prompt(asset);
                assert!(!text.contains("{{"), "{asset} carries a placeholder");
            }
        }
        // The leftover skeleton is split into sections: the first is what the tool
        // description renders (its one key supplied by the renderer), the second the
        // per-call note's lead, which takes no key at all — only section 0 is
        // substituted, so an unrendered key there would reach the agent literally.
        let leftover = crate::prompt::load_prompt_sections("tool/shell_leftover.md");
        assert_eq!(leftover.len(), 2, "tool/shell_leftover.md lost a section");
        assert!(leftover[0].contains("{{mode_sentence}}"), "{leftover:?}");
        assert!(
            !leftover[1].contains("{{"),
            "the note lead carries an unrendered key: {}",
            leftover[1]
        );
    }

    /// The Windows section of the shell description's own notes, in `mode`: the
    /// renderer whose assets `platform_prompt_assets_are_embedded` above checks.
    fn command_line_notes(mode: ShellMode) -> String {
        render_command_line_notes(ShellPlatform::Windows, mode)
            .expect("the platform whose interpreter ends a command at a break has notes")
    }

    /// Whether the rendering leaves a paragraph no sentence fills: a placeholder a
    /// mode's fragment does not fill leaves its line breaks behind, and the rendering
    /// has to be right in itself rather than after a later trim.
    fn has_blank_paragraph(text: &str) -> bool {
        text.split("\n\n").any(|para| para.trim().is_empty())
    }

    /// This platform's own section is offered on the platform it is true of and
    /// nowhere else, and it states the rules the shell now keeps there: the tool set
    /// that is not present, `;` that separates nothing, `#` that comments nothing,
    /// the settings the interpreter is started with (auto-run scripts included), and
    /// which encoding a program's output is read back in. The renderer takes no mode,
    /// so the same section is the one both modes receive.
    #[test]
    fn the_guidance_states_this_platforms_own_rules() {
        assert!(render_platform_notes(ShellPlatform::Unix).is_none());
        let guidance = render_platform_notes(ShellPlatform::Windows)
            .expect("the platform with rules of its own has a section");
        for sentence in [
            "no POSIX tool set",
            "`;` is not a command separator",
            "`#` is not a comment",
            "auto-run scripts",
            "console encoding",
        ] {
            assert!(guidance.contains(sentence), "{sentence}: {guidance}");
        }
        assert!(!guidance.contains("{{"), "{guidance}");
    }

    /// This platform's own rules reach the agent in the description of both modes,
    /// and the other platform's rules reach neither: the section is not
    /// mode-specific, so a mode that dropped it would leave rules its own runs
    /// depend on unstated.
    #[test]
    fn the_platform_notes_reach_both_modes() {
        let this = render_platform_notes(SHELL_PLATFORM);
        let other = render_platform_notes(match SHELL_PLATFORM {
            ShellPlatform::Unix => ShellPlatform::Windows,
            ShellPlatform::Windows => ShellPlatform::Unix,
        });
        for mode in [ShellMode::Full, ShellMode::ReadOnly] {
            let description = ShellTool::new(mode).description();
            assert!(!description.contains("{{"), "{description}");
            if let Some(notes) = this.as_deref() {
                assert!(
                    description.contains(notes),
                    "each mode's description must carry this platform's own rules"
                );
            }
            if let Some(other) = other.as_deref() {
                assert!(
                    !description.contains(other),
                    "no mode's description may carry the other platform's rules"
                );
            }
        }
    }

    /// The guidance the agent is handed — in both modes, on the platform whose
    /// interpreter reads one line — states the limit this reading refuses under, in
    /// numbers the constants decide.
    #[test]
    fn the_guidance_states_the_same_command_line_limit() {
        for mode in [ShellMode::Full, ShellMode::ReadOnly] {
            let guidance = command_line_notes(mode);
            // The three numbers of the limit's sentence are the constants': the
            // platform's own line, what its path, its pinned settings and its `/C`
            // switch take, and what that leaves for the text.
            for number in [
                windows_line::COMMAND_LINE_CAP,
                windows_line::TEXT_UNIT_LIMIT,
                windows_line::COMMAND_LINE_CAP - windows_line::TEXT_UNIT_LIMIT,
            ] {
                assert!(
                    guidance.contains(&number.to_string()),
                    "{number}: {guidance}"
                );
            }
            // No `{{…}}` placeholder is left: every one the skeleton writes is
            // substituted, so a missing fragment would reach the agent as its own name.
            assert!(!guidance.contains("{{"), "{guidance}");
        }
    }

    /// The section is rendered from the mode's own fragments and no other's, each of
    /// them once: the caret's escape is described by the reader that mode consults,
    /// only the read-only mode's own checks need the aside, and a fragment the skeleton
    /// wrote twice would be substituted twice (see [`super::render_command_line_notes`]),
    /// so the agent would read the same sentence twice. The fragments themselves are
    /// asserted, rather than a word like "read-only" that an unrelated sentence could
    /// later carry.
    #[test]
    fn the_guidance_names_each_modes_own_fragments() {
        let full = command_line_notes(ShellMode::Full);
        let read_only = command_line_notes(ShellMode::ReadOnly);
        let (full_escaped, read_only_escaped, aside) = (
            crate::prompt::load_prompt("tool/shell_command_lines_escaped_full.md")
                .trim()
                .to_owned(),
            crate::prompt::load_prompt("tool/shell_command_lines_escaped_read_only.md")
                .trim()
                .to_owned(),
            crate::prompt::load_prompt("tool/shell_command_lines_read_only_aside.md")
                .trim()
                .to_owned(),
        );
        assert!(!full.contains(&read_only_escaped));
        assert!(!full.contains(&aside));
        assert!(!read_only.contains(&full_escaped));
        // Once each, and the aside as a paragraph of its own: the read-only mode adds it
        // after a blank line, so it is never run on from the sentence before.
        for (guidance, fragment) in [
            (&full, full_escaped.as_str()),
            (&full, windows_line::remedy(ShellMode::Full).as_str()),
            (&read_only, read_only_escaped.as_str()),
            (
                &read_only,
                windows_line::remedy(ShellMode::ReadOnly).as_str(),
            ),
            (&read_only, aside.as_str()),
        ] {
            assert_eq!(guidance.matches(fragment).count(), 1, "{fragment}");
        }
        assert!(
            read_only.lines().any(|line| line == aside),
            "the aside is a paragraph of its own: {read_only}"
        );
        // The mode that has no aside leaves no paragraph behind for it, and neither
        // rendering leaves a blank paragraph anywhere else: both are right as they stand,
        // with nothing for the description to trim away when it joins the sections.
        assert!(!has_blank_paragraph(&full), "{full:?}");
        assert!(!has_blank_paragraph(&read_only), "{read_only:?}");
        // The platform whose interpreter already separates at a break is handed no
        // such section at all.
        assert!(render_command_line_notes(ShellPlatform::Unix, ShellMode::Full).is_none());
    }

    /// The leftover-process section reaches the agent in both modes, each mode's own
    /// sentence and no other's: a mode handed the other's fragment would promise a
    /// mechanism its runs do not have (or deny the one they do), and the section is
    /// not platform-selected, so a mode that dropped it would leave the note's own
    /// meaning unstated. A fragment that exists but is never rendered — or a sentence
    /// the skeleton wrote twice, which `substitute` would replace twice — fails here
    /// rather than reaching the agent, and the rendering is asserted to be the very
    /// text both modes' descriptions carry.
    #[test]
    fn the_leftover_notes_name_each_modes_own_mechanism() {
        let full = render_leftover_notes(ShellMode::Full);
        let read_only = render_leftover_notes(ShellMode::ReadOnly);
        let full_sentence = crate::prompt::load_prompt("tool/shell_leftover_full.md")
            .trim()
            .to_owned();
        let read_only_sentence = crate::prompt::load_prompt("tool/shell_leftover_read_only.md")
            .trim()
            .to_owned();
        assert_eq!(full.matches(&full_sentence).count(), 1, "{full}");
        assert_eq!(
            read_only.matches(&read_only_sentence).count(),
            1,
            "{read_only}"
        );
        assert!(!full.contains(&read_only_sentence), "{full}");
        assert!(!read_only.contains(&full_sentence), "{read_only}");
        // The note's own meaning is stated in both modes: a FINISHED call whose own
        // output and exit status are the result, with the leftover named and left RUNNING.
        for rendered in [&full, &read_only] {
            assert!(!rendered.contains("{{"), "{rendered}");
            for sentence in ["FINISHED", "RUNNING"] {
                assert!(rendered.contains(sentence), "{sentence}: {rendered}");
            }
        }
        // The mechanism each mode may name: Full mode points at the supported way to
        // keep a process running; ReadOnly mode has none to point at.
        for sentence in ["background: true", "`stop`"] {
            assert!(full.contains(sentence), "{sentence}: {full}");
        }
        assert!(!read_only.contains("background: true"), "{read_only}");
        // Both descriptions carry the section — a fragment that exists but is never
        // rendered fails here.
        for (mode, notes) in [
            (ShellMode::Full, full.as_str()),
            (ShellMode::ReadOnly, read_only.as_str()),
        ] {
            let description = ShellTool::new(mode).description();
            assert!(
                description.contains(notes.trim()),
                "each mode's description must carry its leftover notes"
            );
        }
    }

    /// This platform's asset named `tool/shell_{stem}_{platform}.md`, and the other
    /// platform's — the whole of what "platform-selected" means for a text the
    /// description carries.
    fn platform_text(stem: &str) -> (String, String) {
        let read = |platform: &str| {
            crate::prompt::load_prompt(&format!("tool/shell_{stem}_{platform}.md"))
                .trim()
                .to_owned()
        };
        match SHELL_PLATFORM {
            ShellPlatform::Unix => (read("unix"), read("windows")),
            ShellPlatform::Windows => (read("windows"), read("unix")),
        }
    }

    /// Every platform-selected text the description carries is this platform's own
    /// and the other platform's is absent: a placeholder left behind would reach the
    /// agent as its own name, and another platform's sentence would promise it a
    /// mechanism this one does not have. The stop text is additionally the one text
    /// the description's stop bullet and the `stop` argument's schema entry both
    /// carry, so the two cannot promise different mechanisms either (see `tree`).
    #[test]
    fn platform_selected_texts_are_this_platforms_own() {
        let full = ShellTool::new(ShellMode::Full);
        let description = full.description();
        assert!(!description.contains("{{"), "{description}");
        for stem in ["full_stop", "full_trailing", "grep_notes"] {
            let (this, other) = platform_text(stem);
            assert!(
                description.contains(&this),
                "the description must carry this platform's {stem} text"
            );
            assert!(
                !description.contains(&other),
                "the description must not carry the other platform's {stem} text"
            );
        }

        let (this, other) = platform_text("full_stop");
        let schema = full.parameters_schema();
        let stop = schema["properties"]["stop"]["description"]
            .as_str()
            .expect("the stop argument carries a description");
        assert!(
            stop.contains(&this),
            "the stop schema must carry this platform's stop text"
        );
        assert!(
            !stop.contains(&other),
            "the stop schema must not promise the other platform's stop text"
        );
    }

    /// The Windows-only refusal decision, driven directly: the serve decision's
    /// own refusal, a produced rewrite the read-only guard rejected, and `None`
    /// everywhere else — on unix in particular, where the original command runs.
    #[test]
    fn unserved_refusal_is_windows_only_and_covers_both_cases() {
        let produced = grep_engine::GrepServe {
            rewritten: Some("engine".into()),
            outcomes: Vec::new(),
            spec_files: Vec::new(),
            plan: None,
            refusal: None,
        };
        // An applied rewrite is never a refusal; on unix neither case refuses.
        assert!(unserved_refusal(ShellPlatform::Unix, &produced, true).is_none());
        assert!(unserved_refusal(ShellPlatform::Unix, &produced, false).is_none());
        assert!(unserved_refusal(ShellPlatform::Windows, &produced, true).is_none());

        // Produced but not applied (the read-only guard rejected it): refused
        // on Windows, with the guard rejection named as the cause.
        let guard = unserved_refusal(ShellPlatform::Windows, &produced, false)
            .expect("a rejected rewrite is refused on Windows");
        assert!(guard.contains("read-only guard"), "{guard}");

        // A serve decision that carries its own refusal reports that cause.
        let refused = grep_engine::GrepServe {
            rewritten: None,
            outcomes: Vec::new(),
            spec_files: Vec::new(),
            plan: None,
            refusal: Some("nested grep".into()),
        };
        assert_eq!(
            unserved_refusal(ShellPlatform::Windows, &refused, false).as_deref(),
            Some("nested grep")
        );
    }

    /// An engine failure must be recognised from a completed run, and on
    /// Windows from the refusal marker alone: a pipeline tail (`grep … | tail
    /// -1`) carries the tail's exit status, so the sentinel code is masked
    /// there and the run would otherwise look like an empty match set. On unix
    /// the same run re-runs the original command, so the marker is ignored.
    #[test]
    fn engine_failure_covers_the_masked_windows_sentinel() {
        let marker = grep_engine::ENGINE_REFUSAL_MARKER;
        let reason = "grep: engine: working directory diverged from the analyzed command";
        // The engine's own emission order: the marker first, then the detail.
        let masked = format!("{marker}\n{reason}\n");

        let Some(EngineFailure::Refused(cause)) =
            engine_failure(Some(0), masked.as_bytes(), ShellPlatform::Windows)
        else {
            panic!("the marker refuses the Windows call");
        };
        assert!(cause.contains("diverged"), "{cause}");
        assert!(
            !cause.contains(marker),
            "the marker is not agent-facing: {cause}"
        );
        assert!(
            engine_failure(Some(0), masked.as_bytes(), ShellPlatform::Unix).is_none(),
            "unix re-runs the original command instead of refusing"
        );

        // Only a line that IS the marker counts: a served run whose matched
        // line merely echoes the token is a result, not a refusal.
        let echoed = format!("f.txt:{marker}\n");
        assert!(
            engine_failure(Some(0), echoed.as_bytes(), ShellPlatform::Windows).is_none(),
            "a matched line carrying the token is not a refusal: {echoed:?}"
        );

        // The cause is the line after the marker, never a served member's own
        // stderr line that happens to come first.
        let noisy = format!("f.txt: a line mentioning {reason}\n{marker}\nengine detail\n");
        assert!(
            matches!(
                engine_failure(Some(0), noisy.as_bytes(), ShellPlatform::Windows),
                Some(EngineFailure::Refused(cause)) if cause == "engine detail"
            ),
            "the marker's own detail line is the cause"
        );

        // A sentinel exit needs no marker, and a marker with no detail line
        // still yields a refusal with a generic cause.
        assert!(matches!(
            engine_failure(
                Some(grep_engine::ENGINE_FAILED_EXIT),
                reason.as_bytes(),
                ShellPlatform::Unix
            ),
            Some(EngineFailure::ReRun)
        ));
        let bare = engine_failure(
            Some(0),
            format!("{marker}\n").as_bytes(),
            ShellPlatform::Windows,
        );
        let Some(EngineFailure::Refused(bare)) = bare else {
            panic!("a marker alone is a refusal");
        };
        assert!(bare.contains("could not serve"), "{bare}");

        // A stale self-update binary is recognised by its own message on both
        // platforms (its exit 1 is a legitimate grep no-match code) — with its
        // message as the cause where the platform renders one.
        assert!(matches!(
            engine_failure(
                Some(1),
                grep_engine::STALE_BINARY_LOCK_MSG.as_bytes(),
                ShellPlatform::Unix
            ),
            Some(EngineFailure::ReRun)
        ));
        assert!(matches!(
            engine_failure(
                Some(1),
                grep_engine::STALE_BINARY_LOCK_MSG.as_bytes(),
                ShellPlatform::Windows
            ),
            Some(EngineFailure::Refused(cause)) if cause.contains(grep_engine::STALE_BINARY_LOCK_MSG)
        ));
        // The lock message is the cause wherever it sits in the stream, not the
        // first line: a launch that meets the lock files its durable record first,
        // so the boot channel's pointer line precedes it.
        let recorded = format!(
            "start-up failure recorded in C:\\Users\\owner\\.mahbot\\error.log\n\
             Error: {} (the instance lock is held)\n",
            grep_engine::STALE_BINARY_LOCK_MSG
        );
        assert!(
            matches!(
                engine_failure(Some(1), recorded.as_bytes(), ShellPlatform::Windows),
                Some(EngineFailure::Refused(cause)) if cause.contains(grep_engine::STALE_BINARY_LOCK_MSG)
            ),
            "the lock line is the cause, not the pointer line before it: {recorded:?}"
        );
        // A served run is not a refusal: exit 0/1 with no engine complaint.
        for code in [0, 1] {
            assert!(engine_failure(Some(code), b"", ShellPlatform::Windows).is_none());
        }
    }

    /// macOS only, the platform [`program_command`] acts on: the resolution it
    /// performs and the non-forking start it buys.
    #[cfg(target_os = "macos")]
    mod program_command_tests {
        use super::*;
        use std::ffi::OsStr;
        use std::os::unix::fs::PermissionsExt;
        use std::path::PathBuf;
        use tempfile::TempDir;

        /// An executable program named `name` under `dir`: a copy of a real Mach-O
        /// binary, the only kind of file [`program_command`] names by its path — so
        /// the fixture is one the kernel starts directly, and its permissions can be
        /// changed by the tests that need that.
        fn program(dir: &Path, name: &str) -> PathBuf {
            let path = dir.join(name);
            std::fs::copy("/bin/echo", &path).expect("copy a real program");
            path
        }

        /// An executable script named `name` under `dir`, with a valid interpreter
        /// line: exactly the kind of file the naming rule leaves to the forking
        /// start.
        fn script(dir: &Path, name: &str) -> PathBuf {
            let path = dir.join(name);
            std::fs::write(&path, "#!/bin/sh\nprintf '%s' \"$0\"\n").expect("write fixture");
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
                .expect("make the fixture executable");
            path
        }

        /// `prog`'s search list as the pairs a spawn would be handed.
        fn search_path(value: &str) -> Vec<(OsString, OsString)> {
            vec![(OsString::from("PATH"), OsString::from(value))]
        }

        #[test]
        fn a_bare_name_becomes_the_path_its_own_search_list_finds() {
            let dir = TempDir::new().expect("tempdir");
            let found = program(dir.path(), "prog");
            let env = search_path(&dir.path().to_string_lossy());

            let cmd = program_command("prog", &env, Some(dir.path()));

            assert_eq!(cmd.get_program(), found.as_os_str());
        }

        /// Every file the kernel does not start by itself keeps the bare name: an
        /// empty executable (which `execvp` re-runs under `/bin/sh`), a script (which
        /// it reaches through its interpreter under rules the naming rule does not
        /// model), and a name that already carries a separator (the caller's own
        /// program, not one to look up).
        #[test]
        fn a_name_is_left_alone_where_a_resolved_path_would_change_what_runs() {
            let dir = TempDir::new().expect("tempdir");
            let env = search_path(&dir.path().to_string_lossy());
            let unresolvable = dir.path().join("prog");
            std::fs::write(&unresolvable, "").expect("write an empty fixture");
            std::fs::set_permissions(&unresolvable, std::fs::Permissions::from_mode(0o755))
                .expect("make the fixture executable");

            assert_eq!(
                program_command("prog", &env, Some(dir.path())).get_program(),
                OsStr::new("prog"),
                "an executable the kernel cannot start must keep the bare name"
            );

            std::fs::remove_file(&unresolvable).expect("clear the fixture");
            script(dir.path(), "prog");
            assert_eq!(
                program_command("prog", &env, Some(dir.path())).get_program(),
                OsStr::new("prog"),
                "a script must keep the bare name"
            );

            // The same directory holds a program a bare `prog` *would* have found,
            // so the untouched name is what a separator buys, not a missing fixture.
            std::fs::remove_file(dir.path().join("prog")).expect("clear the fixture");
            let found = program(dir.path(), "prog");
            assert_eq!(
                program_command(&found.to_string_lossy(), &env, Some(dir.path())).get_program(),
                found.as_os_str()
            );
        }

        #[test]
        fn an_empty_search_entry_resolves_against_the_commands_directory() {
            let dir = TempDir::new().expect("tempdir");
            let found = program(dir.path(), "prog");

            let cmd = program_command("prog", &search_path(""), Some(dir.path()));

            assert_eq!(cmd.get_program(), found.as_os_str());
        }

        #[test]
        fn an_environment_without_a_path_falls_back_to_the_default_search_path() {
            let cmd = program_command("true", &[], None);

            assert_eq!(cmd.get_program(), OsStr::new("/usr/bin/true"));
        }

        #[test]
        fn a_directory_and_a_non_executable_file_are_skipped_for_the_next_entry() {
            let root = TempDir::new().expect("tempdir");
            let as_dir = root.path().join("as-dir");
            std::fs::create_dir_all(as_dir.join("prog")).expect("directory named like the program");
            let no_exec = root.path().join("no-exec");
            std::fs::create_dir(&no_exec).expect("tempdir");
            std::fs::write(no_exec.join("prog"), "#!/bin/sh\n").expect("non-executable fixture");
            let good = root.path().join("good");
            std::fs::create_dir(&good).expect("tempdir");
            let found = program(&good, "prog");
            let search = std::env::join_paths([&as_dir, &no_exec, &good])
                .expect("join the search list")
                .to_string_lossy()
                .into_owned();

            let cmd = program_command("prog", &search_path(&search), Some(root.path()));

            assert_eq!(cmd.get_program(), found.as_os_str());
        }

        /// `execvp` tests whether *this* user may execute the file, not whether the
        /// mode's execute bits are set, so a file that is executable for someone
        /// else is passed over and the search goes on. (Root may execute anything,
        /// so the check has nothing to say there.)
        #[test]
        fn a_file_its_owner_may_not_execute_is_not_the_program() {
            if unsafe { libc::geteuid() } == 0 {
                return;
            }
            let root = TempDir::new().expect("tempdir");
            let not_ours = root.path().join("not-ours");
            std::fs::create_dir(&not_ours).expect("tempdir");
            let foreign = program(&not_ours, "prog");
            std::fs::set_permissions(&foreign, std::fs::Permissions::from_mode(0o001))
                .expect("executable for someone else only");
            let good = root.path().join("good");
            std::fs::create_dir(&good).expect("tempdir");
            let found = program(&good, "prog");
            let search = std::env::join_paths([&not_ours, &good])
                .expect("join the search list")
                .to_string_lossy()
                .into_owned();

            let cmd = program_command("prog", &search_path(&search), Some(root.path()));

            assert_eq!(cmd.get_program(), found.as_os_str());
        }

        #[test]
        fn nothing_resolving_leaves_the_bare_name() {
            let dir = TempDir::new().expect("tempdir");
            let env = search_path(&dir.path().to_string_lossy());

            let cmd = program_command("prog", &env, Some(dir.path()));

            assert_eq!(cmd.get_program(), OsStr::new("prog"));
        }

        /// The actual regression guard, and the one thing `Command`'s own getters
        /// cannot show: `argv[0]`. A shell script cannot say — the kernel hands its
        /// interpreter the script's own path as that — so the product's own shell
        /// start is asked to print what it was called: the interpreter is named by an
        /// absolute path, and still sees itself as bare `sh`.
        #[tokio::test]
        async fn build_shell_command_names_sh_by_path_without_changing_its_argv0() {
            let dir = TempDir::new().expect("tempdir");
            let mut cmd = build_shell_command("printf '%s' \"$0\"", dir.path());

            let program = cmd.as_std().get_program().to_owned();
            assert!(
                Path::new(&program).is_absolute(),
                "the interpreter is still named bare: {program:?}"
            );
            let ran = cmd.output().await.expect("the interpreter runs");
            assert_eq!(ran.stdout, b"sh");
        }
    }
}