newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
//! Shell execution for run_command and lifecycle: environment, confinement,
//! host-process lifetime, and shell-envelope interpretation.

use super::super::content_spill::{self, SpillStore};
use super::super::display::ToolPresentation;
use super::super::permissions::{
    DenialKind, PermissionDecision, PermissionGate, PermissionRequest,
};
use super::live_output::{LiveOutputRelay, LiveOutputSession};
use super::output_budget::{
    self, cap_model_output, cap_model_output_with_handle, max_output_tokens, output_head_tokens,
};
use super::{
    denial_context, denial_recovery_hint, full_access_requested, ocap_disabled,
    permission_granted_result, requests_are_replay_safe, resolve_tool_alias, AliasOutcome,
};
use crate::ExecOutcome;

pub fn venv_cmd_prefix() -> Option<String> {
    let venv = std::env::var("NEWT_VENV")
        .or_else(|_| std::env::var("VIRTUAL_ENV"))
        .ok();
    let exec_paths = std::env::var("NEWT_EXEC_PATHS").ok();

    if venv.is_none() && exec_paths.is_none() {
        return None;
    }

    // sh single-quoting: wrap in '', escape any ' as '\''
    let q = |s: &str| format!("'{}'", s.replace('\'', r"'\''"));

    // Build a list of dirs to prepend to PATH (venv/bin first, then exec-paths).
    let mut path_dirs: Vec<String> = Vec::new();
    let mut prefix = String::new();

    if let Some(ref venv) = venv {
        let venv_bin = format!("{venv}/bin");
        prefix.push_str(&format!("export VIRTUAL_ENV={}; ", q(venv)));
        path_dirs.push(venv_bin);
    }
    if let Some(ref paths) = exec_paths {
        for dir in paths.split(':') {
            if !dir.is_empty() {
                path_dirs.push(dir.to_string());
            }
        }
    }

    if !path_dirs.is_empty() {
        let quoted: Vec<String> = path_dirs.iter().map(|d| q(d)).collect();
        prefix.push_str(&format!("export PATH={}:\"$PATH\"; ", quoted.join(":")));
    }

    if prefix.is_empty() {
        None
    } else {
        Some(prefix)
    }
}

/// Build the venv/exec-path environment as a `{KEY:VALUE}` map for the confined
/// shell's structured `env` seam (agent-bridle, newt #783).
///
/// Same inputs as [`venv_cmd_prefix`] — `NEWT_VENV` (preferred) or
/// `$VIRTUAL_ENV`, plus `NEWT_EXEC_PATHS` — but delivered as host-supplied env
/// vars set directly on the spawned child instead of `export …;` text prepended
/// to the command. The `export` form is the #783 root cause: `export` is a
/// shell builtin, not a program, so the confined safe-subset engine refuses it
/// on a compound command (`a; b | c`). Passing the vars through the env seam
/// sidesteps that entirely and never touches the command text.
///
/// `PATH` is the venv `bin` (then any `NEWT_EXEC_PATHS` dirs) *prepended* to the
/// inherited host `PATH`: the env seam sets the value additively over the
/// child's ambient environment, so we read the host `PATH` here and build the
/// full string rather than relying on a `$PATH` expansion inside the value.
/// Returns an empty map when neither input is set (no env key is sent).
pub(super) fn venv_env_map() -> std::collections::BTreeMap<String, String> {
    let mut map = std::collections::BTreeMap::new();

    // Env passthrough: the confined shell has NO ambient shell variables, so
    // without this brush cannot expand `~` (it resolves `~` from its `HOME` shell
    // var, erroring "HOME not set") and the command silently used a literal
    // `~/…` path — leaving `<cwd>/~/…` debris on disk. Seed a minimal,
    // operator-configurable allow-list from the process env (default HOME+USER+TZ;
    // widened via `[shell] env_passthrough`, published as
    // NEWT_SHELL_ENV_PASSTHROUGH). Each var is set only when present, so nothing
    // is fabricated and the default stays narrow (the confined shell is a trust
    // boundary — a wide passthrough would leak secrets into a sandboxed command).
    for var in shell_env_passthrough() {
        if let Ok(val) = std::env::var(&var) {
            map.insert(var, val);
        }
    }
    // File-sourced import (#1243 Leg 2): the `~/.newt/shell-env/` drop-in dir —
    // deliberate, allowlisted tokens/support vars whose VALUES live in files,
    // never in config.toml or newt's own process env. Merged over the ambient
    // passthrough (explicit operator intent wins); the engine-critical vars
    // (SHELL/VIRTUAL_ENV/PATH) set below still win over a same-named token file.
    if let Some(config_path) = crate::Config::user_config_path() {
        map.extend(crate::shell_env::from_config_dir(&config_path));
    }
    // The child's temp dir, matching the write fence's scratch root. The brush
    // engine runs `do_not_inherit_env(true)`, so the ambient `TMPDIR` is not
    // inherited: this seam entry is what the child sees. Without it the child's
    // tools fall back to the platform temp dir, which a configured fence may not
    // grant. `NEWT_CHILD_TMPDIR` is published by the headless confined
    // lane from the SAME value the fence is built from (one owner, no second
    // resolution); unset everywhere else, so other lanes are unchanged.
    if let Ok(tmp) = std::env::var("NEWT_CHILD_TMPDIR") {
        if !tmp.trim().is_empty() {
            map.insert("TMPDIR".to_string(), tmp);
        }
    }
    // Model-run git: no ambient config, the hardening overrides, and the
    // agent as author (see `git_hardening::sandbox_git_env`).
    // Resolved per dispatch, so a `/settings` change applies to the next
    // command rather than the next session.
    let identity = crate::AgentIdentity::resolve().unwrap_or_default();
    let (name, email) = identity.sandbox_author();
    map.extend(crate::git_hardening::sandbox_git_env(
        (&name, &email),
        &identity.git.config,
    ));

    // Identify the confined engine so `env` / scripts can tell they're in newt's
    // shell (e.g. `SHELL=safe-subset` / `brush` / `host`), not the login shell.
    map.insert("SHELL".to_string(), shell_engine().as_str().to_string());

    let venv = std::env::var("NEWT_VENV")
        .or_else(|_| std::env::var("VIRTUAL_ENV"))
        .ok();
    let exec_paths = std::env::var("NEWT_EXEC_PATHS").ok();

    // Dirs to prepend to PATH (venv/bin first, then any exec-paths), mirroring
    // venv_cmd_prefix's ordering.
    let mut path_dirs: Vec<String> = Vec::new();
    if let Some(ref venv) = venv {
        map.insert("VIRTUAL_ENV".to_string(), venv.clone());
        path_dirs.push(format!("{venv}/bin"));
    }
    if let Some(ref paths) = exec_paths {
        for dir in paths.split(':') {
            if !dir.is_empty() {
                path_dirs.push(dir.to_string());
            }
        }
    }

    // Resolve Apple's real developer tools before the /usr/bin xcrun shims.
    // The shims need ambient per-user caches; direct tools keep workspace-only
    // writes. Explicit venv and operator executable roots retain precedence.
    #[cfg(target_os = "macos")]
    if let Some(developer) = crate::confined_exec::selected_developer_directory() {
        path_dirs.push(format!("{developer}/usr/bin"));
    }

    if !path_dirs.is_empty() {
        let prepend = path_dirs.join(":");
        let path = match std::env::var("PATH") {
            Ok(inherited) if !inherited.is_empty() => format!("{prepend}:{inherited}"),
            _ => prepend,
        };
        map.insert("PATH".to_string(), path);
    }

    map
}

/// The confined-shell env passthrough list: `NEWT_SHELL_ENV_PASSTHROUGH`
/// (colon-separated, published from `[shell] env_passthrough`) or the minimal
/// default (`HOME`, `USER`, `TZ`). Empty names are dropped; empty values survive.
fn shell_env_passthrough() -> Vec<String> {
    match std::env::var("NEWT_SHELL_ENV_PASSTHROUGH") {
        Ok(s) if !s.trim().is_empty() => s
            .split(':')
            .filter(|v| !v.is_empty())
            .map(str::to_string)
            .collect(),
        _ => crate::config::shell_env_passthrough_default(),
    }
}

/// Directory operand used by the command tools, including their aliases.
pub(super) fn command_cwd_key(name: &str) -> Option<&'static str> {
    let name = match resolve_tool_alias(name) {
        Some(AliasOutcome::Rewrite(canonical)) => canonical,
        _ => name,
    };
    match name {
        "run_command" | "build_exec" => Some("cwd"),
        "lifecycle" => Some("dir"),
        _ => None,
    }
}

/// Supply the bound task-worktree default (#2780), or the operator's existing
/// shell default, without changing workspace identity or any grant. Display,
/// admission and execution all use this projection. Explicit operands win;
/// a leading cd is subsequently resolved against this default by the shell.
pub(super) fn command_args_with_default_cwd<'a>(
    name: &str,
    args: &'a serde_json::Value,
    workspace: &str,
    default_cwd: Option<&std::path::Path>,
    session: Option<&crate::worktree_adoption::WorktreeSession>,
) -> Result<std::borrow::Cow<'a, serde_json::Value>, &'static str> {
    let Some(key) = command_cwd_key(name) else {
        return Ok(std::borrow::Cow::Borrowed(args));
    };
    if args.get(key).is_some() || !args.is_object() {
        return Ok(std::borrow::Cow::Borrowed(args));
    }
    let task_root = session.and_then(|session| session.task_root(std::path::Path::new(workspace)));
    // Without a task, preserve the existing lifecycle/build defaults.
    let is_shell = name == "run_command"
        || matches!(
            resolve_tool_alias(name),
            Some(AliasOutcome::Rewrite("run_command"))
        );
    let default_cwd = task_root
        .as_deref()
        .or_else(|| is_shell.then_some(default_cwd).flatten());
    let Some(default_cwd) = default_cwd.filter(|cwd| *cwd != std::path::Path::new(workspace))
    else {
        return Ok(std::borrow::Cow::Borrowed(args));
    };
    // #2780: canonical Windows roots have a verbatim prefix that Git may
    // interpret as non-local. Keep binding checks canonical, but pass the
    // equivalent ordinary spelling to children on every command route.
    let cwd = dunce::simplified(default_cwd).to_str().ok_or(
        "error: the command working directory is not valid UTF-8; select a UTF-8 directory",
    )?;
    let mut projected = args.clone();
    projected[key] = serde_json::Value::String(cwd.to_owned());
    Ok(std::borrow::Cow::Owned(projected))
}

/// Build the dispatch args for agent-bridle's confined `shell` tool (#783): the
/// RAW user command (free-form `cmd` mode) plus the venv carried through the
/// structured `env` seam ([`venv_env_map`]). Deliberately NO `export …;` prefix
/// on `cmd` — that is what the confined safe-subset engine refuses on a
/// compound command (the #783 root cause); the env seam sets `VIRTUAL_ENV` /
/// `PATH` on the spawned child instead. The host-bypass (`--yolo`) path keeps
/// the prefix form because it runs on a real `/bin/sh` where `export` works.
/// Resolve an optional model-supplied `cwd` (#1159) against the workspace: a
/// relative dir joins under the workspace root; an absolute one is taken as-is
/// (the confined shell's fs fence rejects any path that escapes the workspace,
/// so this never widens reach). `None` runs at the workspace root, as before.
pub(super) fn resolve_exec_cwd(workspace: &str, cwd: Option<&str>) -> String {
    match cwd.filter(|c| !c.trim().is_empty()) {
        None => workspace.to_string(),
        Some(c) if std::path::Path::new(c).is_absolute() => c.to_string(),
        Some(c) => std::path::Path::new(workspace)
            .join(c)
            .to_string_lossy()
            .into_owned(),
    }
}

/// #2773: cwd availability is an execution precondition, not filesystem
/// authority. Callers still enforce their existing containment policy.
pub(super) fn existing_exec_cwd(
    cwd: &std::path::Path,
) -> Result<std::path::PathBuf, (String, ExecOutcome)> {
    let unavailable = |reason: String| {
        (
            format!(
                "error: working directory {} {reason}; no command ran",
                crate::worktree_adoption::task_path_literal(cwd)
            ),
            ExecOutcome::Unavailable,
        )
    };
    let resolved = cwd.canonicalize().map_err(|error| {
        unavailable(if error.kind() == std::io::ErrorKind::NotFound {
            "does not exist".into()
        } else {
            format!("cannot be resolved: {error}")
        })
    })?;
    if !resolved.is_dir() {
        return Err(unavailable("is not a directory".into()));
    }
    Ok(resolved)
}

/// Split a leading `cd <path> &&` (or `cd <path> ;`) off a `run_command`
/// string so the `cd` — a shell **builtin**, not an executable — never reaches
/// the confined exec layer, which would try to `execvp("cd")` and fail (on
/// macOS: `sandbox-exec: execvp() of 'cd' failed`). The models reliably prefix
/// `cd <workspace> && <real command>` out of habit; folding the `cd` into the
/// command's cwd runs the real command where the model meant, and — as a bonus
/// — the OCAP prompt then names the *real* capability (`git checkout -b …`)
/// instead of the opaque `cd … && git …`.
///
/// Only a SINGLE leading `cd` at the very start is folded (not `cd a && cd b`,
/// and not a `cd` deeper in a pipeline — those are left for the shell engine).
/// Folding happens only when the path is followed by a sequential connective
/// (`&&` / `;`) or end-of-string; an unusual `cd x | y` is left whole.
/// Returns `(cd_path, remainder)`; `remainder` is empty for a bare `cd <path>`.
pub(super) fn split_leading_cd(cmd: &str) -> (Option<String>, String) {
    let rest = match cmd.trim_start().strip_prefix("cd") {
        Some(r) if r.starts_with(char::is_whitespace) => r.trim_start(),
        _ => return (None, cmd.to_string()),
    };
    let (path, after) = parse_cd_path(rest);
    if path.is_empty() {
        return (None, cmd.to_string());
    }
    let after = after.trim_start();
    let remainder = if let Some(r) = after.strip_prefix("&&") {
        r.trim_start().to_string()
    } else if let Some(r) = after.strip_prefix(';') {
        r.trim_start().to_string()
    } else if after.is_empty() {
        String::new()
    } else {
        // `cd <path>` followed by something we don't confidently understand
        // (a pipe, `||`, a redirection) — don't fold; hand the whole string to
        // the engine.
        return (None, cmd.to_string());
    };
    (Some(path), remainder)
}

/// Parse the first path token of a `cd` argument: a single/double-quoted string
/// (returned unquoted) or an unquoted run up to the next whitespace. Returns
/// `(path, remainder_after_the_token)`.
fn parse_cd_path(s: &str) -> (String, &str) {
    let first = s.chars().next();
    if let Some(q @ ('"' | '\'')) = first {
        if let Some(end) = s[1..].find(q) {
            return (s[1..=end].to_string(), &s[end + 2..]);
        }
    }
    match s.find(char::is_whitespace) {
        Some(i) => (s[..i].to_string(), &s[i..]),
        None => (s.to_string(), ""),
    }
}

/// #2558 (HANDOFF item 2): `cmd f > f` — the shell truncates `f` before the
/// command reads it, destroying the input. Run 6 of the refactor test lost a
/// file this way (`awk … f > f`). Per #2558 ("make the wrong mutation
/// impossible, don't explain it afterwards"), refuse BEFORE any exec: nothing
/// runs, nothing changes. Called once, at the top of [`exec_confined_command`]
/// — the ONE function both the confined lane and the `--yolo` host-bypass
/// lane route through (the branch between them happens INSIDE it), so a
/// single call site covers both **for model-typed shell text**: `run_command`,
/// the routed-build fallback (whose redirect would be `SHELL_META` and never
/// route in the first place), and the justfile-missing fallback. It does
/// NOT cover `run_confined_build_lane`'s `sh -c <joined>` lane
/// (`build_check_argv`, used by `lifecycle action=build` / the #2541
/// escalation): that runs RESOLVED phase commands from `[lifecycle]`/pack
/// config, not the model's own typed text, and is reachable only if the
/// model edits that config — accepted, not "every shell lane".
///
/// "Reads" = a plain operand of any command in the pipeline, or `< f` —
/// narrowed by two rules (#2560 round 2) so a harmless first instinct is not
/// refused: a [`NON_READING_COMMANDS`] stage (`echo`, `printf`, …) adds no
/// reads at all, and a [`SUBCOMMAND_DISPATCHERS`] stage's FIRST operand (the
/// verb — `build`, `diff`, `test`) is skipped, so `cargo build > build` and
/// `git diff > diff` run. "Writes" = the target of `>`, `>|`, or `>>`
/// (append is unsafe too, for a command that streams) — PLUS every non-flag
/// operand of a `tee` stage, which opens each with `O_TRUNC` at startup
/// regardless of any redirect (`sort f | tee f`). Paths are resolved against
/// `cwd` via [`resolve_exec_cwd`] — the SAME #2551 resolution
/// `run_command`/`lifecycle` already use, not a second one — then
/// lexically normalized (`crate::caveats::lexically_normalize`) so `cat ./f
/// > f` compares equal to `cat f > f`.
///
/// Deliberately NOT a shell parser: a single pipeline of plain tokens, with
/// minimal single/double-quote handling so `sed 's/a/b/' f > f` still reads
/// as `sed`, `f`, `>`, `f`. A token touched by an expansion/glob character
/// (`$` `` ` `` `*` `?` `[` `~`) or an unterminated quote is OPAQUE: it is
/// never treated as a read OR a write target, so an ambiguous form is left
/// exactly as today (never refused, never silently trusted as "different
/// file") rather than risk a false refusal. `&&` / `;` / `||` start a fresh
/// pipeline scope (each side of `f > f.tmp && mv f.tmp f` is checked on its
/// own, so that rewrite is never refused); `|` keeps the same scope (a later
/// stage's write can still collide with an earlier stage's read).
///
/// **Stated limits (#2560 round 2 review) — miss, but no worse than today:**
/// - **Subshells and brace groups**: `(cat f) > f` / `{ cat f; } > f` — `(cat`
///   becomes an opaque-free but wrong "command word", and the brace form
///   splits its own scope at `;`. Out of scope for a single-pipeline parser.
/// - **`dd if=f of=f`**: no redirect operator at all; `of=` truncates unless
///   `conv=notrunc`. Not special-cased — rare for this model.
/// - **Symlinks**: `cat link > f` where `link` points at `f` is lexical-only
///   and invisible here by design (the brief asked for no canonicalization;
///   canonicalizing would also require the path to already exist).
/// - **No general flag-skipping**: only `tee`'s operands and a subcommand
///   dispatcher's first operand are narrowed. A plain `-name`-style flag
///   elsewhere is still a "read" candidate (harmless unless it coincidentally
///   equals the write target, which the review judged not worth chasing).
pub(super) fn same_file_redirect_refusal(cmd: &str, cwd: &str) -> Option<String> {
    let tokens = tokenize(cmd);
    let mut start = 0usize;
    for (idx, tok) in tokens.iter().enumerate() {
        if matches!(tok, RedirectToken::Sep) {
            if let Some(msg) = check_pipeline_redirects(&tokens[start..idx], cmd, cwd) {
                return Some(msg);
            }
            start = idx + 1;
        }
    }
    check_pipeline_redirects(&tokens[start..], cmd, cwd)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RedirectOp {
    In,
    Out,
    OutAppend,
    OutClobber,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum RedirectToken {
    /// Dequoted text, and whether it touched an expansion/glob character or
    /// an unterminated quote (opaque — never a read or write candidate).
    Word(String, bool),
    Redirect(RedirectOp),
    /// `|` — a new stage of the SAME pipeline scope.
    Pipe,
    /// `&&` / `;` / `||` — starts a fresh pipeline scope.
    Sep,
}

/// Characters that mean "this word may not literally be the path it looks
/// like" — a glob, a variable, a command substitution, or a bare `~`. Also
/// applied to a word's DEQUOTED content, so a single-quoted `'*.rs'` (still
/// meant as a real glob) stays opaque too.
const AMBIGUOUS_CHARS: [char; 6] = ['$', '`', '*', '?', '[', '~'];

fn tokenize(cmd: &str) -> Vec<RedirectToken> {
    let chars: Vec<char> = cmd.chars().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c.is_whitespace() {
            i += 1;
            continue;
        }
        if c == '&' && chars.get(i + 1) == Some(&'&') {
            out.push(RedirectToken::Sep);
            i += 2;
            continue;
        }
        if c == '|' && chars.get(i + 1) == Some(&'|') {
            out.push(RedirectToken::Sep);
            i += 2;
            continue;
        }
        if c == ';' {
            out.push(RedirectToken::Sep);
            i += 1;
            continue;
        }
        if c == '|' {
            out.push(RedirectToken::Pipe);
            i += 1;
            continue;
        }
        if c == '>' && chars.get(i + 1) == Some(&'>') {
            out.push(RedirectToken::Redirect(RedirectOp::OutAppend));
            i += 2;
            continue;
        }
        if c == '>' && chars.get(i + 1) == Some(&'|') {
            out.push(RedirectToken::Redirect(RedirectOp::OutClobber));
            i += 2;
            continue;
        }
        if c == '>' {
            out.push(RedirectToken::Redirect(RedirectOp::Out));
            i += 1;
            continue;
        }
        if c == '<' {
            out.push(RedirectToken::Redirect(RedirectOp::In));
            i += 1;
            continue;
        }
        let (word, opaque, consumed) = read_word(&chars[i..]);
        out.push(RedirectToken::Word(word, opaque));
        i += consumed.max(1);
    }
    out
}

/// Read one word starting at `chars[0]` (guaranteed to be a non-whitespace,
/// non-operator char by [`tokenize`]'s dispatch). Stops at whitespace or an
/// operator-starting char; single/double-quoted spans are dequoted inline
/// (their content still checked for [`AMBIGUOUS_CHARS`]). An unterminated
/// quote consumes the rest of the string and marks the word opaque.
fn read_word(chars: &[char]) -> (String, bool, usize) {
    let mut text = String::new();
    let mut opaque = false;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c.is_whitespace() || matches!(c, '>' | '<' | '|' | '&' | ';') {
            break;
        }
        match c {
            '\'' | '"' => {
                let quote = c;
                let mut j = i + 1;
                let mut closed = false;
                while j < chars.len() {
                    if chars[j] == quote {
                        closed = true;
                        break;
                    }
                    j += 1;
                }
                if !closed {
                    opaque = true;
                    text.extend(&chars[i..]);
                    i = chars.len();
                    break;
                }
                text.extend(&chars[i + 1..j]);
                i = j + 1;
            }
            _ if AMBIGUOUS_CHARS.contains(&c) => {
                opaque = true;
                text.push(c);
                i += 1;
            }
            _ => {
                text.push(c);
                i += 1;
            }
        }
    }
    (text, opaque, i)
}

/// One pipeline scope (already split on `&&`/`;`/`||`): collect every read
/// (a non-command-name plain operand, or an `< f` target) and every write
/// (`>`/`>|`/`>>` target), resolve each against `cwd`, and refuse if any
/// write path matches any read path.
/// #2560 round 2 "smallest narrowing": commands that never read a file
/// argument at all — refusing `echo f > f` costs the model's harmless first
/// instinct (#2558 test 1) for zero safety, since `echo` cannot truncate
/// anything it "reads". A stage whose command word is one of these adds NONE
/// of its operands to `reads`.
const NON_READING_COMMANDS: [&str; 5] = ["echo", "printf", "true", "false", ":"];

/// Subcommand DISPATCHERS: their first operand is a verb (`build`, `diff`,
/// `test`), never a path, so `cargo build > build` / `git diff > diff` must
/// not refuse on a coincidental name match. Only the FIRST operand is
/// skipped — a later plain operand (`git diff HEAD~1 file.rs > file.rs`)
/// still counts normally.
const SUBCOMMAND_DISPATCHERS: [&str; 6] = ["cargo", "git", "just", "make", "npm", "go"];

fn check_pipeline_redirects(tokens: &[RedirectToken], cmd: &str, cwd: &str) -> Option<String> {
    let mut reads: Vec<String> = Vec::new();
    let mut writes: Vec<String> = Vec::new();
    let mut at_stage_start = true;
    // The current stage's command word, and how many operands of THIS stage
    // have been seen so far — both reset on `Pipe`, never carried across
    // stages, so the narrowing rules below are per-command, not per-pipeline.
    let mut stage_command: Option<&str> = None;
    let mut operand_index = 0usize;
    let mut i = 0;
    while i < tokens.len() {
        match &tokens[i] {
            RedirectToken::Pipe => {
                at_stage_start = true;
                stage_command = None;
                operand_index = 0;
                i += 1;
            }
            RedirectToken::Sep => unreachable!("pipelines are pre-split on Sep"),
            RedirectToken::Redirect(op) => {
                at_stage_start = false;
                if let Some(RedirectToken::Word(text, false)) = tokens.get(i + 1) {
                    match op {
                        RedirectOp::In => reads.push(text.clone()),
                        RedirectOp::Out | RedirectOp::OutAppend | RedirectOp::OutClobber => {
                            writes.push(text.clone());
                        }
                    }
                    i += 2;
                } else {
                    // Missing or opaque target: never attributed either way.
                    i += 1;
                }
            }
            RedirectToken::Word(text, opaque) => {
                if at_stage_start {
                    stage_command = Some(text.as_str());
                    at_stage_start = false;
                } else if stage_command == Some("tee") {
                    // #2560 round 2: `tee` opens EVERY non-flag operand with
                    // O_TRUNC at startup — `sort f | tee f` is exactly as
                    // destructive as `sort f > f`, so its operands are
                    // WRITES, not reads. `-a` (append) is a flag, not a
                    // path — skipped like any flag — and still refused,
                    // same as `>>`: append is unsafe for a tool that streams.
                    if !opaque && !text.starts_with('-') {
                        writes.push(text.clone());
                    }
                    operand_index += 1;
                } else {
                    let non_reading =
                        stage_command.is_some_and(|c| NON_READING_COMMANDS.contains(&c));
                    let subcommand_slot = operand_index == 0
                        && stage_command.is_some_and(|c| SUBCOMMAND_DISPATCHERS.contains(&c));
                    if !opaque && !non_reading && !subcommand_slot {
                        reads.push(text.clone());
                    }
                    operand_index += 1;
                }
                i += 1;
            }
        }
    }
    // #2560 round 2: `resolve_exec_cwd` joins but does not normalize, so a
    // lexical spelling difference (`cat ./f > f`) missed the guard entirely
    // — `ws/./f` != `ws/f` by string equality. `lexically_normalize` (the
    // same normalizer `caveats::permits_path` already uses for containment)
    // collapses `.`/`..` components on BOTH sides before comparing.
    let normalized =
        |token: &str| crate::caveats::lexically_normalize(&resolve_exec_cwd(cwd, Some(token)));
    // Empty operands and tokenizer placeholders do not name files. In
    // particular, an unsupported descriptor operation must not become cwd
    // through resolve_exec_cwd(None/empty) and collide with a real `.` operand.
    writes
        .iter()
        .filter(|path| !path.is_empty())
        .find_map(|write| {
            let write_path = normalized(write);
            reads
                .iter()
                .any(|read| !read.is_empty() && normalized(read) == write_path)
                .then(|| {
                    format!(
                        "error: refusing to run this command — it reads '{write}' and \
                     also redirects output to '{write}' in the same pipeline. The \
                     shell truncates '{write}' before the command finishes reading \
                     it, destroying the input. Write to a new name and move it into \
                     place instead (e.g. `awk … f > f.tmp && mv f.tmp f`).\n\
                     Refused command: {cmd}"
                    )
                })
        })
}

pub(super) fn confined_dispatch_args(cmd: &str, cwd: &str) -> serde_json::Value {
    let env = venv_env_map();
    serde_json::json!({
        "cmd": cmd,
        "cwd": cwd,
        "env": env,
    })
}

/// Execution route shared by admission, child construction and catalog guidance.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ShellRoute {
    Cmd,
    AmbientBrush,
    BashSh,
    Bridled(crate::ShellEngine),
}

/// Keep command-specific clamps in this decision, rather than inferring the
/// shell from the session's OCAP switch alone. A broker always needs Brush.
#[allow(clippy::too_many_arguments)]
pub(super) fn select_shell_route(
    bypass_enabled: bool,
    has_broker: bool,
    has_lease: bool,
    floor_permits: bool,
    windows: bool,
    windows_cmd: bool,
    runner_available: bool,
    engine: crate::ShellEngine,
) -> ShellRoute {
    if bypass_enabled && !has_broker && !has_lease && floor_permits {
        if windows {
            if windows_cmd || !runner_available {
                ShellRoute::Cmd
            } else {
                ShellRoute::AmbientBrush
            }
        } else {
            ShellRoute::BashSh
        }
    } else {
        ShellRoute::Bridled(if has_broker {
            crate::ShellEngine::Brush
        } else {
            engine
        })
    }
}

fn missing_runner_notice(
    route: ShellRoute,
    opted_out: bool,
    shown: &std::sync::atomic::AtomicBool,
) -> Option<&'static str> {
    (route == ShellRoute::Cmd
        && !opted_out
        && !shown.swap(true, std::sync::atomic::Ordering::Relaxed))
    .then_some("carried brush not installed; using cmd")
}

impl ShellRoute {
    pub(super) fn sentence(self) -> &'static str {
        match self {
            Self::Cmd => "Commands run under cmd.exe /C: chain with &&; POSIX ; and $? are not supported. run_command already returns the exit status — do not echo it.",
            Self::AmbientBrush | Self::BashSh | Self::Bridled(_) => "Commands use POSIX shell syntax; the selected engine may restrict shell constructs.",
        }
    }
}

/// Capture the session-default route. Brokers, leases and exec floors are
/// command-specific: execution re-evaluates them before dispatch.
pub fn run_command_dialect_sentence() -> &'static str {
    select_shell_route(
        ocap_disabled(),
        false,
        false,
        true,
        cfg!(windows),
        crate::config::windows_cmd_enabled(),
        crate::ambient_brush::installed(),
        shell_engine(),
    )
    .sentence()
}

/// Pure session-default guidance with injected platform/authority and an installed runner.
pub fn shell_dialect_sentence(host_bypass: bool, windows: bool) -> &'static str {
    select_shell_route(
        host_bypass,
        false,
        false,
        true,
        windows,
        false,
        true,
        crate::ShellEngine::SafeSubset,
    )
    .sentence()
}

/// The shell engine selected for this dispatch (ADR 0005 D2 seam). An explicit
/// `[shell] engine` / `--shell-engine` choice is published by the CLI through
/// `NEWT_SHELL_ENGINE`, so deep `run_command` dispatch reads it without threading
/// it through every signature. Full-access sessions retain their platform
/// default; otherwise the confined default is resolved below from the current L3
/// fence state rather than cached at startup.
pub(super) fn shell_engine() -> crate::ShellEngine {
    if let Some(engine) = std::env::var("NEWT_SHELL_ENGINE")
        .ok()
        .and_then(|s| s.parse::<crate::ShellEngine>().ok())
    {
        return engine;
    }
    // No engine was published (e.g. a non-CLI entry point that set
    // NEWT_FULL_ACCESS directly). Honor the same supported default as the CLI:
    // host on Linux/macOS, safe-subset where the worker is unavailable.
    if full_access_requested() {
        return crate::full_access_default_engine();
    }
    // #1243 Leg 1: the CONFINED default is L3-gated and resolved HERE, per
    // dispatch — `dispatch_bridled_shell()` calls this on every run_command, so the
    // fence state is re-checked at exec time and never cached at startup (the
    // agent-bridle #239 TLA+ TOCTOU obligation). Brush when a kernel fence
    // enforces on this host; safe-subset's structural refusal otherwise.
    crate::confined_default_engine(crate::ocap_l3_backend().1)
}

/// agent-bridle's tool registry with the `"shell"` tool bound to the selected
/// engine (the ADR 0005 D2 seam: `safe-subset` / `host` / `brush` all honor the
/// same `Tool` contract under the `"shell"` name). `web_fetch` is added
/// unchanged. Mirrors `agent_bridle::registry()` but swaps the shell engine so
/// `[shell] engine = "host"` (or `--full-access`) routes `run_command` to the
/// full-grammar, kernel-jailed sandbox-host engine instead of the safe subset.
/// The b1 sandbox policy every `run_command` shell engine runs under: the
/// default backend confinement PLUS [`agent_bridle::ChildNetworkPolicy::DenyDirect`]
/// — the seccomp `socket()`-family egress deny (agent-bridle 0.7.15) that closes
/// the UDP/DNS/raw/packet leg the Landlock TCP-only net rule misses.
///
/// Applied unconditionally, but **inert unless the caller's `net` caveat is
/// already deny-all** (`net: none`): a granted net scope leaves it untouched (the
/// caller asked for egress), while a hostile / confined `run_command` under
/// `net: none` gets NO off-box socket of any protocol — the live attacker-exec
/// path finally inheriting the same complete egress floor as the
/// `ConstrainedExecutor` callers. Fail-closed: if the seccomp floor cannot be
/// installed, the spawn is refused rather than run with a weaker floor.
fn b1_run_command_sandbox_policy() -> agent_bridle::SandboxPolicy {
    agent_bridle::SandboxPolicy {
        child_network: agent_bridle::ChildNetworkPolicy::DenyDirect,
        ..crate::confined_exec::runtime_sandbox_policy()
    }
}

fn bridle_registry(
    engine: crate::ShellEngine,
    live: Option<std::sync::Arc<LiveOutputRelay>>,
    wall: std::time::Duration,
    held_read_roots: Vec<agent_bridle::HeldReadRoot>,
    execution_lease: Option<std::sync::Arc<dyn Send + Sync>>,
    command_broker: Option<std::sync::Arc<dyn agent_bridle_tool_shell::CommandBroker>>,
) -> agent_bridle::Registry {
    use std::sync::Arc;
    #[cfg(test)]
    let _ = &command_broker;
    let shell: Arc<dyn agent_bridle::Tool> = match engine {
        crate::ShellEngine::SafeSubset => {
            // F20: the wall rides on the limits — see `shell_limits`.
            let mut tool = agent_bridle::ShellTool::with_config(shell_limits(wall))
                .with_sandbox_policy(b1_run_command_sandbox_policy())
                .with_held_read_roots(held_read_roots.clone());
            if let Some(lease) = execution_lease {
                tool = tool.with_execution_lease(lease);
            }
            if let Some(observer) = live.clone() {
                tool = tool.with_output_observer(observer);
            }
            Arc::new(tool)
        }
        crate::ShellEngine::Host => {
            let mut tool = agent_bridle::HostShellTool::new()
                .with_timeout(wall)
                .sandbox_policy(Arc::new(b1_run_command_sandbox_policy()))
                .with_held_read_roots(held_read_roots.clone());
            if let Some(lease) = execution_lease {
                tool = tool.with_execution_lease(lease);
            }
            if let Some(observer) = live.clone() {
                tool = tool.with_output_observer(observer);
            }
            Arc::new(tool)
        }
        crate::ShellEngine::Brush => {
            // Cargo's library-test harness is not the `newt` executable and
            // therefore cannot service bridle's worker re-exec handshake
            // (`--agent-bridle-worker brush`). Keep unit tests on the same
            // confined Tool contract without attempting to re-exec the test
            // harness; the real binary path remains Brush unchanged.
            #[cfg(test)]
            let shell = {
                let mut tool = agent_bridle::ShellTool::with_config(shell_limits(wall))
                    .with_sandbox_policy(b1_run_command_sandbox_policy())
                    .with_held_read_roots(held_read_roots.clone());
                if let Some(lease) = execution_lease {
                    tool = tool.with_execution_lease(lease);
                }
                if let Some(observer) = live {
                    tool = tool.with_output_observer(observer);
                }
                Arc::new(tool) as Arc<dyn agent_bridle::Tool>
            };
            #[cfg(not(test))]
            let shell = {
                // Brush runs in an authenticated worker with static command/file
                // policies. Unsupported targets refuse rather than bypassing its
                // private transport; startup checks that capability.
                let mut tool = agent_bridle::BrushShellTool::new()
                    .with_max_output_bytes(shell_limits(wall).max_output_bytes)
                    .expect("shared shell output limit fits Brush protocol bounds")
                    .with_timeout(wall)
                    .with_sandbox_policy(Arc::new(b1_run_command_sandbox_policy()))
                    .with_held_read_roots(held_read_roots.clone());
                if let Some(lease) = execution_lease {
                    tool = tool.with_execution_lease(lease);
                }
                if let Some(broker) = command_broker {
                    tool = tool.with_command_broker(broker);
                }
                if let Some(observer) = live {
                    tool = tool.with_output_observer(observer);
                }
                Arc::new(tool) as Arc<dyn agent_bridle::Tool>
            };
            shell
        }
    };
    agent_bridle::Registry::builder()
        .tool(shell)
        .tool(Arc::new(agent_bridle::WebFetchTool::new()))
        .build()
}

/// #1176: should an about-to-run command be shadow-recorded? Exactly when it
/// runs UNCONFINED — via either of the two unconfined routes:
/// - `host_bypass` — the `--yolo`/`--disable-ocap` host-shell bypass, or
/// - `full_access` — a `--full-access` session, whose caveats are
///   `Caveats::top()`, so the confined bridle dispatch runs effectively
///   unconfined and would otherwise learn nothing.
///
/// A genuinely confined session (`host_bypass == false` and no full-access) is
/// NOT recorded: its leash is real, so there is no shadow to catch. Pure over
/// the two booleans so the gating is unit-tested without a live shell. Before
/// #1176's full-access parity, only the host-bypass arm recorded — a bare
/// `--full-access` run armed the recorder yet never wrote.
pub(super) fn shadow_records(host_bypass: bool, full_access: bool) -> bool {
    host_bypass || full_access
}

/// Does the caller's effective exec FLOOR permit running `cmd` on the
/// UNCONFINED host shell?
///
/// `None` means the caller found no effective exec floor after composing the
/// session, posture, mode, and persona constraints. The floor therefore
/// imposes nothing and the `--disable-ocap` bypass behaves as it did pre-#307.
///
/// `Some(scope)` ⇒ the bypass may proceed ONLY for a single, simple command
/// whose program (leading token) the scope authorizes. This is deliberately
/// conservative on TWO counts, because the host shell runs `cmd` verbatim with
/// no per-spawn interceptor:
///
/// 1. A **compound** command (containing a shell metacharacter that could chain
///    another program — `&&`, `||`, `;`, `|`, `` ` ``, `$(`, newline, `&`, `>`,
///    `<`) is NOT allowed to bypass. `echo ok && rm -rf /` would otherwise
///    smuggle `rm` past an `echo` grant. It falls through to the confined
///    shell, which gates every spawn.
/// 2. Only the leading token is matched, so a bare allow-listed program runs;
///    anything else is denied.
///
/// The denied command isn't refused outright — it falls to the confined-shell
/// path, which enforces the already-composed effective `caveats`. Every active
/// exec floor therefore keeps its ceiling even under `--yolo`.
pub(super) fn exec_floor_permits(floor: Option<&crate::caveats::Scope<String>>, cmd: &str) -> bool {
    use crate::caveats::ScopeExt as _;
    let Some(scope) = floor else {
        return true; // no effective exec floor ⇒ bypass unchanged
    };
    // Conservative: any shell control/redirection metacharacter that could
    // introduce a second program defeats leading-token matching, so refuse the
    // bypass and let the confined shell gate each spawn.
    const SHELL_META: &[char] = &['&', '|', ';', '`', '$', '\n', '>', '<', '(', ')'];
    if cmd.contains(SHELL_META) {
        return false;
    }
    match cmd.split_ascii_whitespace().next() {
        // An empty command runs nothing; let it through to the normal path.
        None => true,
        Some(prog) => scope.permits(&prog.to_string()),
    }
}

/// INTERIM (#297): run `cmd` on the PLAIN host shell — no leash, no
/// interceptor, no sandbox — and wrap the outcome in an envelope structurally
/// identical to the confined shell's (`{ exit_code, stdout, stderr,
/// sandbox_kind }`, with `denied` / `denials` omitted exactly as the bridle
/// envelope omits them when nothing was denied). [`envelope_denied`] and
/// [`shell_envelope_output`] — and therefore the loop's truncation / denial /
/// exit-code handling — apply to it unchanged.
///
/// A spawn failure surfaces as `Err`, which the caller formats as the same
/// `error: …` string a bridle dispatch failure produces.
/// Run `cmd` through the SAME confined-shell path the `run_command` tool uses —
/// the venv env seam, the `--disable-ocap` host bypass under the #307 exec
/// floor, the agent-bridle confined shell, and the #263 permission-gate re-ask —
/// and render the envelope. Shared by the `run_command` and `lifecycle` (#891)
/// arms so both honor **identical** exec caveats; the central presenter owns
/// the tool-call and completed-result block.
#[cfg(all(test, any(not(windows), feature = "windows-appcontainer")))]
pub(super) async fn dispatch_bridled_shell(
    args: serde_json::Value,
    caveats: &crate::caveats::Caveats,
    sink: Option<std::sync::Arc<dyn crate::agentic::LiveToolOutput>>,
) -> agent_bridle::ToolResult<serde_json::Value> {
    dispatch_bridled_shell_with_floor(
        args,
        caveats,
        sink,
        None,
        None,
        None,
        Vec::new(),
        Default::default(),
    )
    .await
}

/// A prepared build keeps the native build executor's strength floor while
/// the same shell engine evaluates the original source and pipelines once.
#[allow(clippy::too_many_arguments)]
pub(super) async fn dispatch_bridled_build_shell(
    args: serde_json::Value,
    caveats: &crate::caveats::Caveats,
    sink: Option<std::sync::Arc<dyn crate::agentic::LiveToolOutput>>,
    execution_lease: std::sync::Arc<dyn Send + Sync>,
    command_broker: Option<std::sync::Arc<dyn agent_bridle_tool_shell::CommandBroker>>,
    held_read_roots: Vec<agent_bridle::HeldReadRoot>,
    command_budget: crate::RunCommandBudget,
) -> agent_bridle::ToolResult<serde_json::Value> {
    dispatch_bridled_shell_with_floor(
        args,
        caveats,
        sink,
        Some(agent_bridle::AxisEnforcement::Kernel),
        Some(execution_lease),
        command_broker,
        held_read_roots,
        command_budget,
    )
    .await
}

#[allow(clippy::too_many_arguments)]
async fn dispatch_bridled_shell_with_floor(
    mut args: serde_json::Value,
    caveats: &crate::caveats::Caveats,
    sink: Option<std::sync::Arc<dyn crate::agentic::LiveToolOutput>>,
    strength_floor: Option<agent_bridle::AxisEnforcement>,
    execution_lease: Option<std::sync::Arc<dyn Send + Sync>>,
    command_broker: Option<std::sync::Arc<dyn agent_bridle_tool_shell::CommandBroker>>,
    held_read_roots: Vec<agent_bridle::HeldReadRoot>,
    command_budget: crate::RunCommandBudget,
) -> agent_bridle::ToolResult<serde_json::Value> {
    let mut live = LiveOutputSession::start(sink);
    // NOTE (cross-platform review, `unconfined-fallback-on-missing-backend`):
    // run_command dispatches at the DEFAULT (Advisory) strength floor. On a
    // supported platform whose native backend is present (Linux+Landlock,
    // macOS+Seatbelt, Windows+AppContainer) the fs/net fence is kernel-enforced,
    // so this is confined. But where a RESTRICTED fs/net axis has NO native
    // backend at runtime (`best_available_sandbox` = advisory `NoopSandbox`) this
    // route runs ADVISORY (host) rather than refusing — the ConstrainedExecutor
    // callers fail closed there (Kernel floor). A blanket Kernel floor here is
    // WRONG: run_command legitimately restricts `exec`, which Landlock enforces
    // only as `interceptor` (the exec-behavior-bound BOUNDED residual), so a
    // blanket Kernel floor would refuse every exec-restricted command even on
    // Landlock. The correct fix is a PER-AXIS floor at the bridle boundary
    // (fs/net = Kernel, exec = Interceptor-OK); tracked as an ACTIVE deviation.
    // #2732: prepared build work retains its build budget; version/help probes
    // must not lend a following arbitrary command that longer deadline.
    let cmd = args.get("cmd").and_then(serde_json::Value::as_str);
    let wall = command_wall(
        cmd.unwrap_or_default(),
        args.get("timeout_secs").and_then(serde_json::Value::as_u64),
        command_budget,
    );
    // dec1-build-grant round 2 (Reviewer FIX-FIRST, PR #2579): the toolchain
    // read roots for a build-tool command are added ONLY to the caveats used
    // for THIS dispatch, never folded back into the session's standing
    // authority (`widen_caveats` deliberately does not touch `fs_read` for an
    // exec grant — see its doc comment). Call-scoped, exactly like
    // `build_tool_caveats` for the lifecycle build lane.
    // A prepared build already calibrated and admitted its exact fence. Do
    // not re-read operator environment roots after that authority decision.
    let dispatch_caveats = if strength_floor.is_some() {
        caveats.clone()
    } else {
        dispatch_caveats_for_command(cmd.unwrap_or(""), caveats)
    };
    let ShellRoute::Bridled(engine) = select_shell_route(
        false,
        command_broker.is_some(),
        execution_lease.is_some(),
        true,
        cfg!(windows),
        crate::config::windows_cmd_enabled(),
        crate::ambient_brush::installed(),
        shell_engine(),
    ) else {
        unreachable!("bridled dispatch cannot bypass confinement")
    };
    let registry = bridle_registry(
        engine,
        live.as_ref().map(LiveOutputSession::relay),
        wall,
        held_read_roots,
        execution_lease.clone(),
        command_broker,
    );
    let grant = registry.mint_grant(dispatch_caveats);
    // The selected budget is engine configuration, not an extra model field in
    // Brush/Host's private shell schema. SafeSubset uses the same configured default.
    if let Some(args) = args.as_object_mut() {
        args.remove("timeout_secs");
    }
    let result = match strength_floor {
        Some(floor) => {
            registry
                .dispatch_with_strength_floor("shell", args, &grant, floor)
                .await
        }
        None => registry.dispatch("shell", args, &grant).await,
    };
    if let Some(live) = live.as_mut() {
        let ordinary_completion = result
            .as_ref()
            .ok()
            .and_then(|envelope| envelope.get("timed_out"))
            .and_then(serde_json::Value::as_bool)
            != Some(true);
        if result.is_ok() && ordinary_completion {
            live.finish_after_observer();
        } else {
            live.finish();
        }
    }
    result.map(|mut envelope| {
        envelope["timeout_secs"] = wall.as_secs().into();
        envelope
    })
}

/// #2636: the EXACT message emitted only when `run_command` is refused
/// before anything ran, purely for missing declared filesystem authority —
/// the one denial shape a #2628 rerun is allowed to bind to (round1 finding
/// 3). Any other `Denied` result (a broker-bearing runtime refusal, a build
/// fence, a compound command that partially ran) must never enter that slot.
pub(super) const UNGRANTED_FS_AUTHORITY_DENIAL: &str =
    "capability denied: declared filesystem authority was not granted for this command";

/// Parse the entire invocation manifest before any approval can be consumed.
pub(super) fn declared_filesystem_requests(
    args: &serde_json::Value,
    cmd: &str,
    cwd: &str,
) -> Result<Vec<PermissionRequest>, String> {
    let mut requests = Vec::new();
    for (field, kind) in [
        ("fs_read", DenialKind::FsRead),
        ("fs_write", DenialKind::FsWrite),
    ] {
        let Some(value) = args.get(field) else {
            continue;
        };
        let invalid = || {
            format!(
                "error: run_command {field} must be an array of nonempty absolute paths without NUL bytes"
            )
        };
        for value in value.as_array().ok_or_else(invalid)? {
            let target = value.as_str().ok_or_else(invalid)?;
            if target.is_empty()
                || target.contains('\0')
                || !std::path::Path::new(target).is_absolute()
            {
                return Err(invalid());
            }
            if !requests
                .iter()
                .any(|request: &PermissionRequest| request.kind == kind && request.target == target)
            {
                requests.push(PermissionRequest {
                    tool: "run_command".into(),
                    kind,
                    target: target.into(),
                    reason: format!("declared {field} for command {cmd:?} in {cwd:?}"),
                    harness_bound: false,
                });
            }
        }
    }
    Ok(requests)
}

pub(super) fn permits_filesystem_request(
    caveats: &crate::caveats::Caveats,
    request: &PermissionRequest,
) -> bool {
    let scope = match request.kind {
        DenialKind::FsRead => &caveats.fs_read,
        DenialKind::FsWrite => &caveats.fs_write,
        _ => return false,
    };
    crate::caveats::permits_path(scope, &request.target)
}

#[allow(clippy::too_many_arguments)]
pub(super) async fn exec_confined_command(
    cmd: &str,
    // The directory the command runs in (#1159): the workspace root for
    // lifecycle, or a resolved workspace-confined cwd for run_command.
    cwd: &str,
    workspace: &str,
    color: bool,
    tool_output_lines: usize,
    caveats: &crate::caveats::Caveats,
    filesystem_requests: &[PermissionRequest],
    exec_floor: Option<&crate::caveats::Scope<String>>,
    // F19: `&mut Option<&mut dyn PermissionGate>`, not `Option<&mut dyn
    // PermissionGate>` — the double indirection is what lets a caller
    // reborrow (`permission_gate` in the `lifecycle action=run` escalation)
    // for a SECOND sequential confined call in the same turn. The plain
    // `Option<&mut dyn Trait>` shape can't be reborrowed twice: each callee's
    // elided signature ties the trait object's own lifetime bound to the
    // reference's, so a second call can't be typed as "shorter-lived" than
    // the first — see `confirm_unrestricted_fs_mutation`'s param for the
    // same pattern already in this file.
    permission_gate: &mut Option<&mut dyn PermissionGate>,
    tool_offload: bool,
    spill_store: Option<&dyn SpillStore>,
    live_tool_output: Option<std::sync::Arc<dyn crate::agentic::LiveToolOutput>>,
    presentation: &mut dyn ToolPresentation,
    command_budget: crate::RunCommandBudget,
) -> (String, ExecOutcome) {
    exec_confined_command_with_broker(
        cmd,
        cwd,
        workspace,
        color,
        tool_output_lines,
        caveats,
        filesystem_requests,
        exec_floor,
        permission_gate,
        tool_offload,
        spill_store,
        live_tool_output,
        presentation,
        None,
        None,
        &mut None,
        None,
        None,
        None,
        command_budget,
    )
    .await
}

/// Broker-bearing native commands use Brush's runtime external-command hook.
///
/// #2689: a structured exec denial takes the operator to the SAME interactive
/// `permission_gate.ask_with_caveats` prompt as any other exec denial. The
/// retry below replays THIS SAME call — with `command_broker` still
/// attached, so the attribution/signing policy applies to the replay exactly
/// as it would have to the original attempt — ONLY when
/// `requests_are_replay_safe` (reused from `tools.rs`, #2691 round 3) proves
/// every denied request is an EXEC denial AND the denied command is a
/// single simple command: no chain, substitution, pipeline, loop, or
/// redirect that could already have run an earlier stage's effect, or would
/// repeat one on replay. A net denial is never replay-safe — its target is
/// a host, not the command's executable. Anything else records the call-local
/// allow-once grant in the gate's pending-once queue and reports the grant
/// without replaying, so the model's own retry picks it up with no second
/// prompt. This is the model-synchronous retry inside one call; it is
/// distinct from the model-driven `request_permissions`/`PendingRerun`
/// replay in `tools.rs`, which still excludes a commit-broker command
/// (`commit_broker_used`).
#[allow(clippy::too_many_arguments)]
pub(super) async fn exec_confined_command_with_broker(
    cmd: &str,
    cwd: &str,
    workspace: &str,
    color: bool,
    tool_output_lines: usize,
    caveats: &crate::caveats::Caveats,
    filesystem_requests: &[PermissionRequest],
    exec_floor: Option<&crate::caveats::Scope<String>>,
    permission_gate: &mut Option<&mut dyn PermissionGate>,
    tool_offload: bool,
    spill_store: Option<&dyn SpillStore>,
    live_tool_output: Option<std::sync::Arc<dyn crate::agentic::LiveToolOutput>>,
    presentation: &mut dyn ToolPresentation,
    command_broker: Option<std::sync::Arc<dyn agent_bridle_tool_shell::CommandBroker>>,
    execution_lease: Option<agent_bridle_tool_shell::ExecutionLease>,
    // #2636 finding 1 / #2681: typed signal for a structured pre-exec denial
    // — set to the missing authority set whenever a STRUCTURED denial (a
    // missing declared FS request, or an exec/net denial the confined shell
    // reported) is what's returned to the model. Only these paths produce a
    // rerun-eligible slot; child stdout that happens to contain the denial
    // string does not.
    pre_exec_missing: &mut Option<Vec<PermissionRequest>>,
    retry_authorized: Option<&std::sync::OnceLock<()>>,
    timeout_secs: Option<u64>,
    adopted: Option<&crate::worktree_adoption::AdoptedWorktree>,
    command_budget: crate::RunCommandBudget,
) -> (String, ExecOutcome) {
    presentation.execution_command(cmd, cwd);
    // #2759: adoption is not liftable by an exec or filesystem approval.
    // Keep structural refusals out of both prompts and the pending-rerun slot.
    if let Some(policy) = adopted {
        if filesystem_requests.iter().any(|request| {
            request.kind == DenialKind::FsWrite
                && policy.blocked(std::path::Path::new(&request.target))
        }) {
            return (policy.notice(), ExecOutcome::Denied);
        }
    }
    // #2558 (HANDOFF item 2): refuse a same-file redirect (`cmd f > f`)
    // BEFORE either lane below runs anything — this is the single choke
    // point both the confined dispatch and the `--yolo` host-bypass share.
    if let Some(refusal) = same_file_redirect_refusal(cmd, cwd) {
        return with_denial_context((refusal, ExecOutcome::Denied), workspace, cwd, None);
    }

    // Venv injection (#783): the confined shell carries the venv via
    // agent-bridle's structured `env` seam (see `confined_dispatch_args` /
    // `venv_env_map`), NOT by prepending `export …;` to the command — an
    // `export` builtin is not a program, so the safe-subset engine refuses it on
    // a compound command (the #783 root cause). `cmd_with_venv` (the
    // `export …;`-prefixed form) is built ONLY for the host-bypass path below:
    // that runs on a real `/bin/sh` where `export` is a genuine builtin.
    let cmd_with_venv = match venv_cmd_prefix() {
        Some(prefix) => format!("{prefix}{cmd}"),
        None => cmd.to_string(),
    };

    // INTERIM (#297): --disable-ocap / --yolo / NEWT_DISABLE_OCAP=1 — run the
    // command UNCONFINED on the host shell instead of the bridle's confined
    // shell. Nothing is denied here, so the #263 permission gate below is never
    // consulted. #307 FLOOR: a named-permission-preset clamp WINS over the
    // bypass — the unconfined host path is taken ONLY if the floor permits this
    // command's leading token; else it falls through to the confined shell,
    // which enforces the already-clamped `caveats`. `None` keeps the bypass
    // bit-for-bit.
    let route = select_shell_route(
        ocap_disabled(),
        command_broker.is_some(),
        execution_lease.is_some(),
        exec_floor_permits(exec_floor, cmd),
        cfg!(windows),
        crate::config::windows_cmd_enabled(),
        crate::ambient_brush::installed(),
        shell_engine(),
    );
    let host_bypass = !matches!(route, ShellRoute::Bridled(_));

    // #1176: shadow-OCAP — record the authority a leash WOULD have gated on
    // whenever this command runs UNCONFINED: the yolo/disable-ocap host bypass
    // above, OR a --full-access session (its caveats are `Caveats::top()`, so
    // the confined bridle dispatch below runs effectively unconfined and would
    // otherwise learn nothing). A genuinely confined session is not recorded —
    // its leash is real. No-op unless recording is armed (NEWT_FLIGHT_RECORDER).
    // `newt ocap propose` folds the capture into reviewable policy candidates.
    if shadow_records(host_bypass, full_access_requested()) {
        crate::flight_recorder::log_unconfined(cmd);
    }

    if host_bypass {
        static FALLBACK_SHOWN: std::sync::atomic::AtomicBool =
            std::sync::atomic::AtomicBool::new(false);
        if let Some(notice) =
            missing_runner_notice(route, crate::config::windows_cmd_enabled(), &FALLBACK_SHOWN)
        {
            presentation.preview(notice, 1);
        }
        let mut live = LiveOutputSession::start(live_tool_output);
        let run = host_shell_dispatch(
            route,
            if route == ShellRoute::BashSh {
                &cmd_with_venv
            } else {
                // Neither the dedicated runner nor cmd needs a POSIX export
                // prefix. Windows PATH is supplied in the child environment.
                cmd
            },
            cwd,
            live.as_ref().map(LiveOutputSession::relay),
            timeout_secs,
            command_budget,
        )
        .await;
        if let Some(live) = live.as_mut() {
            live.finish();
        }
        return match run {
            Ok(envelope) => host_result(&envelope, |envelope| {
                let mut text = shell_envelope_output(
                    envelope,
                    tool_output_lines,
                    color,
                    tool_offload,
                    spill_store,
                    Some(&mut *presentation),
                );
                if let Some(hint) = super::worktree::creation_failure_hint(cmd, envelope) {
                    text.push_str(hint);
                }
                text
            }),
            Err(e) => (format!("error: {e}"), ExecOutcome::Unavailable),
        };
    }

    // A proactive session grant can change standing authority during this
    // turn. Refresh before spawning: a child filesystem refusal is not a
    // structured denial that can enter the permission-retry path below.
    let refreshed = match permission_gate.as_deref_mut() {
        Some(gate) => match gate.refresh_caveats(caveats) {
            PermissionDecision::Allow(current) => Some(current),
            PermissionDecision::Deny => {
                return with_denial_context(
                    (
                        "capability denied: current permission authority was refused".to_string(),
                        ExecOutcome::Denied,
                    ),
                    workspace,
                    cwd,
                    None,
                );
            }
        },
        None => None,
    };
    let caveats = refreshed.as_ref().unwrap_or(caveats);

    // Bind an operator-approved invocation before inspection: interpreters are
    // deliberately opaque to inspect_shell, but an exact command/cwd retry can
    // still use its exact granted executable paths. Proactive target-only grants
    // retain their existing statically inspected matching behavior below.
    let bound = permission_gate.as_deref_mut().map(|gate| {
        let mut current = gate.apply_command_retry(cmd, cwd, caveats);
        let Ok(inspection) = agent_bridle::inspect_shell(cmd) else {
            return current;
        };
        let commands = inspection.commands;
        for program in commands.iter().filter_map(|c| c.program.as_deref()) {
            current = gate.apply_pending_once(DenialKind::Exec, program, &current);
        }
        current
    });
    let caveats = bound.as_ref().unwrap_or(caveats);

    let missing: Vec<_> = filesystem_requests
        .iter()
        .filter(|request| !permits_filesystem_request(caveats, request))
        .cloned()
        .collect();
    let admitted = if missing.is_empty() {
        None
    } else {
        let decision = permission_gate
            .as_deref_mut()
            .map(|gate| gate.ask_with_caveats(caveats, &missing));
        match decision {
            Some(PermissionDecision::Allow(allowed))
                if filesystem_requests
                    .iter()
                    .all(|request| permits_filesystem_request(&allowed, request)) =>
            {
                Some(allowed)
            }
            _ => {
                *pre_exec_missing = Some(missing);
                return with_denial_context(
                    (UNGRANTED_FS_AUTHORITY_DENIAL.into(), ExecOutcome::Denied),
                    workspace,
                    cwd,
                    Some(caveats),
                );
            }
        }
    };
    let caveats = admitted.as_ref().unwrap_or(caveats);

    if let Some(refusal) = super::native_git::windows_appcontainer_native_git_refusal(cmd, caveats)
    {
        return (format!("error: {refusal}"), ExecOutcome::Unavailable);
    }

    // #783: RAW cmd + venv via the env seam — never the `export …;` prefix,
    // which the confined safe-subset engine refuses.
    let mut dispatch_args = confined_dispatch_args(cmd, cwd);
    dispatch_args["timeout_secs"] = serde_json::json!(timeout_secs);
    let result = match dispatch_bridled_shell_with_floor(
        dispatch_args.clone(),
        caveats,
        live_tool_output.clone(),
        None,
        execution_lease.clone(),
        command_broker.clone(),
        Vec::new(),
        command_budget,
    )
    .await
    {
        // The confined shell ran. Its envelope carries
        // `{ exit_code, stdout, stderr, timed_out, ... }` plus — when the leash
        // refused a capability — the STRUCTURED denial fields
        // `{ denied: true, denials: [{ kind, target, reason }] }`. In free-form
        // mode an out-of-scope command is denied *inside* the shell by the brush
        // interceptor (the command genuinely does not run); we lift that to the
        // capability-denied UX by reading the structured `denied` field — NEVER
        // a stderr grep.
        Ok(envelope) => {
            if envelope_denied(&envelope) {
                // Repair evidence is distinct from the prompted-decision log: keep
                // the redacted raw command + structured refusal even when prompting
                // is off or the operator allows it. This is what lets `newt ocap
                // denials` distinguish a policy gap from a parser/implementation
                // defect instead of repeatedly granting a bogus target.
                crate::denial_journal::record_envelope(
                    cmd,
                    cwd,
                    crate::denial_journal::DenialStage::Initial,
                    &envelope,
                );
                if let Some(notice) = worktree_denial_notice(adopted, &envelope, cwd) {
                    return (notice, ExecOutcome::Denied);
                }
                // #2689: a broker-bearing command (a native Git commit — see
                // `needs_commit_broker`) takes the SAME operator-prompt path
                // as any other exec denial below. It used to return here
                // unconditionally, before `permission_gate.ask_with_caveats`
                // was ever called — so an operator's "allow once" had nothing
                // to land on and a broker-bearing commit could never be let
                // through without a durable grant. The retry a few lines down
                // carries `command_broker` along, so the broker's
                // attribution/signing policy still applies to the replay.
                //
                // #263: an interactive gate may turn this denial into a human grant.
                // ONE consult + ONE re-execution per call: a second denial (a
                // different target reached on the re-run) surfaces as the standard
                // envelope — the model can retry, which prompts afresh.
                //
                // F19/#2541 round 2: REBORROW (`as_deref_mut`), never `take()`. Taking
                // permanently empties the caller's `&mut Option<&mut dyn PermissionGate>`
                // — the exact double indirection `lifecycle_run_with_escalation` relies on
                // to reuse the SAME gate for its second confined call. `take()` here left
                // that second call (`run_confined_build_lane`) with `permission_gate ==
                // None` whenever THIS run's denial had just been allowed and the re-dispatch
                // then timed out: the escalation refused "requires explicit … authority"
                // without ever asking the operator who just said yes. Nothing below this
                // block touches `permission_gate` again, so reborrowing costs nothing here.
                if let Some(gate) = permission_gate.as_deref_mut() {
                    // #905: promptable exec denials OR net-host denials (agent-bridle
                    // #196). On Allow, the re-mint widens the matching axis (net adds
                    // the host to the allow-list), so the proxy admits it on re-run.
                    if let Some(requests) =
                        exec_denial_requests(&envelope).or_else(|| net_denial_requests(&envelope))
                    {
                        if let PermissionDecision::Allow(widened) =
                            gate.ask_with_caveats(caveats, &requests)
                        {
                            // #2691: Allow is not evidence that every requested axis/target
                            // was granted. Never mint a pending grant from an insufficient reply.
                            use crate::caveats::CaveatsExt as _;
                            if !requests.iter().all(|request| match request.kind {
                                DenialKind::Exec => widened.permits_exec(&request.target),
                                DenialKind::Net => widened.permits_net(&request.target),
                                _ => false,
                            }) {
                                return with_denial_context(
                                    ("capability denied: returned authority does not cover the requested targets".into(), ExecOutcome::Denied),
                                    workspace,
                                    cwd,
                                    Some(caveats),
                                );
                            }
                            // #2689/#2691 round 3: this denial fired
                            // mid-dispatch, so an earlier stage of `cmd` may
                            // already have run a real effect, or may be the
                            // ONE effect a whole-command replay would repeat
                            // (see `requests_are_replay_safe`'s doc comment in
                            // `tools.rs` for both measured shapes — reused
                            // here rather than a second predicate). Replay
                            // only when EVERY denied request is an EXEC
                            // denial AND provably a single simple command
                            // naming it; a net denial's target is a host, not
                            // the command's executable, and never auto-
                            // replays even when it coincidentally shares a
                            // name with the program. Otherwise hold the grant
                            // in the gate's pending-once queue for the
                            // model's own next matching call instead of
                            // spending it on a replay that could duplicate an
                            // effect.
                            if !requests_are_replay_safe(&requests, cmd) {
                                if requests
                                    .iter()
                                    .all(|request| request.kind == DenialKind::Exec)
                                {
                                    gate.queue_command_retry(cmd, cwd, &requests);
                                    if let Some(ready) = retry_authorized {
                                        let _ = ready.set(());
                                    }
                                } else {
                                    for request in &requests {
                                        gate.queue_pending_once(request.kind, &request.target);
                                    }
                                }
                                let granted = requests
                                    .iter()
                                    .map(|request| {
                                        permission_granted_result(
                                            request.kind.as_str(),
                                            &request.target,
                                        )
                                    })
                                    .collect::<Vec<_>>()
                                    .join("\n");
                                return with_denial_context(
                                    (granted, ExecOutcome::Denied),
                                    workspace,
                                    cwd,
                                    Some(&widened),
                                );
                            }
                            if !filesystem_requests
                                .iter()
                                .all(|request| permits_filesystem_request(&widened, request))
                            {
                                return with_denial_context(
                                    ("capability denied: declared filesystem authority was not retained for this command".into(), ExecOutcome::Denied),
                                    workspace,
                                    cwd,
                                    None,
                                );
                            }
                            if let Some(refusal) =
                                super::native_git::windows_appcontainer_native_git_refusal(
                                    cmd, &widened,
                                )
                            {
                                return (format!("error: {refusal}"), ExecOutcome::Unavailable);
                            }
                            // Preserve both the broker policy and recovery lease on
                            // retry: approval does not remove either ownership boundary.
                            let retried = match dispatch_bridled_shell_with_floor(
                                dispatch_args,
                                &widened,
                                live_tool_output,
                                None,
                                execution_lease.clone(),
                                command_broker,
                                Vec::new(),
                                command_budget,
                            )
                            .await
                            {
                                Ok(env2) if envelope_denied(&env2) => {
                                    crate::denial_journal::record_envelope(
                                        cmd,
                                        cwd,
                                        crate::denial_journal::DenialStage::AfterGrant,
                                        &env2,
                                    );
                                    (
                                        worktree_denial_notice(adopted, &env2, cwd).unwrap_or_else(
                                            || denied_run_command_result(&env2, color),
                                        ),
                                        ExecOutcome::Denied,
                                    )
                                }
                                Ok(env2) => confined_result(
                                    cmd,
                                    &env2,
                                    &widened,
                                    color,
                                    |envelope| {
                                        shell_envelope_output(
                                            envelope,
                                            tool_output_lines,
                                            color,
                                            tool_offload,
                                            spill_store,
                                            Some(&mut *presentation),
                                        )
                                    },
                                    command_budget,
                                ),
                                Err(e) => dispatch_error_result(e),
                            };
                            return with_denial_context(retried, workspace, cwd, Some(&widened));
                        }
                    }
                }
                // #2681: no gate, a non-exec-shaped denial, or the gate
                // declined — the plain denial below is what the model
                // receives, so an exec denial is replay-eligible exactly
                // like the FS pre-flight check already is above. A `None`
                // here (not exec-only, or no denials) leaves the slot
                // untouched, matching the FS path's "only a real miss
                // populates it" shape.
                if let Some(requests) = exec_denial_requests(&envelope) {
                    *pre_exec_missing = Some(requests);
                }
            }
            confined_result(
                cmd,
                &envelope,
                caveats,
                color,
                |envelope| {
                    shell_envelope_output(
                        envelope,
                        tool_output_lines,
                        color,
                        tool_offload,
                        spill_store,
                        Some(&mut *presentation),
                    )
                },
                command_budget,
            )
        }
        // An argv-mode leash denial, or an error from inside the tool — surface
        // the reason; the dispatch error Display is safe to show.
        Err(e) => dispatch_error_result(e),
    };
    with_denial_context(result, workspace, cwd, Some(caveats))
}

/// Preserve the dispatch error alongside the execution class returned to the
/// tool-event funnel. Both initial dispatch and the existing grant retry use it.
pub(super) fn dispatch_error_result(error: agent_bridle::ToolError) -> (String, ExecOutcome) {
    let outcome = if matches!(error, agent_bridle::ToolError::Denied { .. }) {
        ExecOutcome::Denied
    } else {
        ExecOutcome::Unavailable
    };
    (format!("error: {error}"), outcome)
}

fn with_denial_context(
    (mut text, outcome): (String, ExecOutcome),
    workspace: &str,
    cwd: &str,
    caveats: Option<&crate::caveats::Caveats>,
) -> (String, ExecOutcome) {
    if outcome == ExecOutcome::Denied {
        text.push('\n');
        text.push_str(&denial_context(workspace, Some(cwd), caveats));
    }
    (text, outcome)
}

/// #2315: the class of a completed envelope from its own facts — structured
/// denial, then the `timed_out` flag (NOT exit 124, which a check wrapped in
/// GNU `timeout` returns on its own), then the exit status.
pub(super) fn envelope_outcome(envelope: &serde_json::Value) -> ExecOutcome {
    if envelope_denied(envelope) {
        ExecOutcome::Denied
    } else if envelope
        .get("timed_out")
        .and_then(serde_json::Value::as_bool)
        == Some(true)
    {
        ExecOutcome::TimedOut
    } else if envelope
        .get("exit_code")
        .and_then(serde_json::Value::as_i64)
        == Some(0)
    {
        ExecOutcome::Passed
    } else {
        ExecOutcome::Failed
    }
}

/// The confined lane's result for an envelope no grant widened: each rendering
/// is paired with the class of the branch that chose it, so the class and the
/// text the model reads cannot disagree.
pub(super) fn confined_result(
    cmd: &str,
    envelope: &serde_json::Value,
    caveats: &crate::caveats::Caveats,
    color: bool,
    render: impl FnOnce(&serde_json::Value) -> String,
    command_budget: crate::RunCommandBudget,
) -> (String, ExecOutcome) {
    if envelope_denied(envelope) {
        return (
            denied_run_command_result(envelope, color),
            ExecOutcome::Denied,
        );
    }
    // #2274: a 127 with no structured denial is an ABSENCE, not an
    // ordinary failure. Name it before it renders as the ambiguous
    // `error: command exited 127`, which is indistinguishable from a
    // broken machine. Returns None for everything else, so ordinary
    // output and ordinary failures fall through untouched.
    if let Some(refusal) = absent_binary_refusal(envelope, &caveats.exec) {
        return (refusal, ExecOutcome::Unavailable);
    }
    // A later pipeline or `;` stage sets the exit code, so a missing `rg` in
    // `rg … | head` exits 0 and a live run showed only brush's bare
    // `command not found: rg`. Keep the output, and name the absence too.
    let absent = absent_program_note(envelope, &caveats.exec);
    // #2273 → #2629 round 2: a 126 with no structured denial gets a note that
    // a refusal MAY have happened and that the target and axis are unknown.
    // It is not classified as a denial and names no grant; see
    // [`unstructured_exit_126_note`] for why the renderer it replaces could
    // not be trusted to.
    let unstructured_126 = unstructured_exit_126_note(envelope);
    // #2629 (revised): a child exec the sandbox refused (e.g. git's own
    // `fatal: cannot exec 'branch': Permission denied`) is neither 126 nor 127
    // at the TOP level — the parent ran fine, only its internal spawn of a
    // helper failed, so it reaches the model as UNSTRUCTURED stderr with no
    // axis or target. That refusal is invisible to the interceptor's `denials`
    // array (only the top-level spawn is instrumented, see #2421), and the
    // parent's own exit code is neither 126 nor 127, so there is NO trusted
    // sandbox refusal evidence to key a structured denial off. Per the review
    // on #2633, child-controlled stderr is not authoritative and must not be
    // promoted to a `capability denied` assertion or used to pick an exec-
    // grant target, so the raw stderr passes through unannotated and the
    // honest outcome (Failed) is kept. A structured, invocation-bound refusal
    // from the leash/interceptor seam (#2421) is what would be needed before
    // this can be rendered as a named denial.
    let outcome = envelope_outcome(envelope);
    let mut text = render(envelope);
    if let Some(hint) = super::worktree::creation_failure_hint(cmd, envelope) {
        text.push_str(hint);
    }
    if let Some(note) = absent {
        text.push('\n');
        text.push_str(&note);
    }
    if let Some(note) = unstructured_126 {
        text.push_str(note);
    }
    if outcome == ExecOutcome::TimedOut {
        text.push_str(&timed_out_note(
            envelope
                .get("timeout_secs")
                .and_then(serde_json::Value::as_u64)
                .map(std::time::Duration::from_secs)
                .unwrap_or_else(|| dispatch_wall(cmd, command_budget)),
            command_budget,
        ));
    }
    (text, outcome)
}

/// How long `lifecycle action=build` may run: the sanctioned lane for work that
/// outlives the `run_command` wall.
pub(super) const LIFECYCLE_BUILD_TIMEOUT: std::time::Duration =
    std::time::Duration::from_secs(30 * 60);

/// The literal call the coaching shows, so a model copies a valid shape instead
/// of inventing `phase="build"`.
const LIFECYCLE_BUILD_CALL: &str = r#"{"action":"build","phase":"test"}"#;

pub(super) const RUN_COMMAND_MAX_SECS: u64 = crate::RunCommandBudget::MAX_SECS;

#[cfg(test)]
pub(super) fn command_budget_seconds(configured: Option<&str>, requested: Option<u64>) -> u64 {
    crate::RunCommandBudget::from_configured(configured).seconds(requested)
}

/// The selected wall must also be the safe-subset engine's default, not only its ceiling.
pub(super) fn shell_limits(wall: std::time::Duration) -> agent_bridle::LimitsPolicy {
    let default = agent_bridle::LimitsPolicy::default();
    agent_bridle::LimitsPolicy {
        default_timeout_secs: wall.as_secs(),
        max_timeout_secs: wall.as_secs().max(default.max_timeout_secs),
        ..default
    }
}

pub(super) fn command_wall(
    cmd: &str,
    requested: Option<u64>,
    command_budget: crate::RunCommandBudget,
) -> std::time::Duration {
    if super::build_shell::has_build_work(cmd) {
        requested
            .filter(|secs| *secs > 0)
            .map(|secs| std::time::Duration::from_secs(command_budget.seconds(Some(secs))))
            .unwrap_or(LIFECYCLE_BUILD_TIMEOUT)
    } else {
        std::time::Duration::from_secs(command_budget.seconds(requested))
    }
}

pub(super) fn dispatch_wall(
    cmd: &str,
    command_budget: crate::RunCommandBudget,
) -> std::time::Duration {
    command_wall(cmd, None, command_budget)
}

/// What the `run_command` description tells the model about its wall, up front.
/// One owner with [`timed_out_note`], so the two cannot disagree (U6).
pub(super) fn run_command_limit_sentence(command_budget: crate::RunCommandBudget) -> String {
    format!(
        "Ordinary calls are killed after {} seconds (wall clock); classified builds get 30 minutes. Override with timeout_secs up to \
         {} seconds; the result carries the exit code. For an offline build use \
         `lifecycle` action=build, i.e. call the tool with {LIFECYCLE_BUILD_CALL} (`phase` is \
         never `build`), or narrow the command (one test filter, one crate).",
        command_budget.seconds(None),
        RUN_COMMAND_MAX_SECS
    )
}

/// Appended to a timed-out confined result: the limit, that the command was
/// killed, and the lane for long builds. `wall` is the clock that actually
/// applied to this call (F20: a build-tool command gets the build wall, not
/// the default) — named explicitly, so a reader can tell why a call ran for
/// minutes instead of assuming the default 60s.
///
/// `pub(super)` (#2541 follow-up): `tools.rs`'s `escalation_result` strips
/// this exact suffix from a timed-out first run's text when the escalation
/// it recommends was just DECLINED — a result must carry ONE recommendation,
/// never this note's "use lifecycle action=build" immediately followed by
/// "build authority was declined".
pub(super) fn timed_out_note(
    wall: std::time::Duration,
    command_budget: crate::RunCommandBudget,
) -> String {
    let default = std::time::Duration::from_secs(command_budget.seconds(None));
    let wall_note = if wall == default {
        format!("{}s wall", wall.as_secs())
    } else if wall == LIFECYCLE_BUILD_TIMEOUT {
        format!(
            "{}s build-lane wall (not the default {}s)",
            wall.as_secs(),
            default.as_secs()
        )
    } else {
        format!(
            "{}s wall (per-call budget; default {}s)",
            wall.as_secs(),
            default.as_secs()
        )
    };
    // A build command already had the build lane's 30 minutes: the only
    // useful advice left is to narrow it.
    if wall == LIFECYCLE_BUILD_TIMEOUT {
        return format!(
            "\n(the command hit the {wall_note} and was killed; the output above is partial. \
             Narrow the command: one crate, one test filter.)"
        );
    }
    format!(
        "\n(the command hit the {wall_note} and was killed; the output above is partial. For a \
         build or full test run use `lifecycle` action=build, i.e. call the tool with \
         {LIFECYCLE_BUILD_CALL} ({}-minute limit, confined, offline; `phase` is the phase to run, not `build`), or \
         narrow the command.)",
        LIFECYCLE_BUILD_TIMEOUT.as_secs() / 60
    )
}

/// The host lane's result (`--unsafe-host-exec`). Same rule as the confined
/// lane: a 127 is `unavailable` only when the shell names the program it could
/// not find AND that program does not resolve on this host. Any other 127 (a
/// bare `exit 127`, a check script's own status) failed and stays repairable.
pub(super) fn host_result(
    envelope: &serde_json::Value,
    render: impl FnOnce(&serde_json::Value) -> String,
) -> (String, ExecOutcome) {
    let outcome = match envelope_outcome(envelope) {
        ExecOutcome::Failed
            if envelope
                .get("exit_code")
                .and_then(serde_json::Value::as_i64)
                == Some(127)
                && host_named_missing(envelope)
                    .is_some_and(|prog| host_path_lookup(prog).is_none()) =>
        {
            ExecOutcome::Unavailable
        }
        outcome => outcome,
    };
    (render(envelope), outcome)
}

/// How the host shells [`host_shell_output`] runs (bash, else sh) name a
/// program they could not find: `bash: line 1: X: command not found`,
/// `sh: 1: X: not found`. A line must carry the shell's own prefix, so a
/// program printing a look-alike is not read as the shell.
const HOST_NOT_FOUND: [(&str, &str); 2] =
    [("bash: ", ": command not found"), ("sh: ", ": not found")];

/// The program the host shell last reported as not found. Stderr only NAMES
/// it; [`host_result`] decides on the exit code and resolution.
fn host_named_missing(envelope: &serde_json::Value) -> Option<&str> {
    let stderr = envelope.get("stderr")?.as_str()?;
    stderr.lines().rev().find_map(|line| {
        HOST_NOT_FOUND.iter().find_map(|(prefix, suffix)| {
            line.strip_prefix(prefix)?
                .strip_suffix(suffix)?
                .rsplit(": ")
                .next()
        })
    })
}

pub(super) async fn host_shell_dispatch(
    route: ShellRoute,
    cmd: &str,
    cwd: &str,
    live: Option<std::sync::Arc<LiveOutputRelay>>,
    timeout_secs: Option<u64>,
    command_budget: crate::RunCommandBudget,
) -> std::io::Result<serde_json::Value> {
    let wall = command_wall(cmd, timeout_secs, command_budget);
    let run = if timeout_secs.is_none() && wall != LIFECYCLE_BUILD_TIMEOUT {
        host_shell_output(route, cmd, cwd, live, command_budget).await?
    } else {
        host_shell_output_with_timeout(route, cmd, cwd, live, wall).await?
    };
    Ok(serde_json::json!({
        "exit_code": run.exit_code,
        "timeout_secs": wall.as_secs(),
        "stdout": decode_shell_stream(&run.stdout),
        "stderr": decode_shell_stream(&run.stderr),
        // Same `timed_out` flag the confined bridle envelope carries, so the
        // host-bypass path can never wedge the session on a hung child (#297).
        "timed_out": run.timed_out,
        // Honest provenance, same field the bridle envelope always carries:
        // nothing sandboxed this run.
        "sandbox_kind": "none",
    }))
}

/// Result of a host-bypass shell run. Unlike a raw [`std::process::Output`] this
/// carries an explicit `timed_out` flag so the dispatch layer can emit the same
/// envelope shape the confined path does when a child is killed for running long.
pub(super) struct HostShellRun {
    pub(super) exit_code: i64,
    pub(super) stdout: Vec<u8>,
    stderr: Vec<u8>,
    pub(super) timed_out: bool,
}

/// The unsafe host bypass uses the same configurable, capped command budget.
fn host_exec_timeout(command_budget: crate::RunCommandBudget) -> std::time::Duration {
    std::time::Duration::from_secs(command_budget.seconds(None))
}

pub(super) fn decode_shell_stream(bytes: &[u8]) -> String {
    match std::str::from_utf8(bytes) {
        Ok(text) => text.to_string(),
        Err(_) => repair_bsd_cat_v_utf8(bytes)
            .unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned()),
    }
}

/// macOS/BSD `cat -v` is not Unicode-aware: for a UTF-8 glyph such as `─`
/// (`e2 94 80`) it emits the lead byte raw (`e2`) and renders only the
/// continuation bytes as ASCII meta-control notation (`M-^TM-^@`). That byte
/// stream is invalid UTF-8, so a plain lossy decode becomes `�M-^TM-^@`.
///
/// Repair only that precise shape. This keeps ordinary valid UTF-8 untouched and
/// leaves unrelated binary output on the existing lossy fallback.
fn repair_bsd_cat_v_utf8(bytes: &[u8]) -> Option<String> {
    let mut repaired = Vec::with_capacity(bytes.len());
    let mut changed = false;
    let mut i = 0;
    while i < bytes.len() {
        let lead = bytes[i];
        let Some(cont_count) = utf8_continuation_count(lead) else {
            repaired.push(lead);
            i += 1;
            continue;
        };

        let mut seq = Vec::with_capacity(cont_count + 1);
        seq.push(lead);
        let mut j = i + 1;
        let mut ok = true;
        for _ in 0..cont_count {
            match parse_cat_v_meta_byte(bytes, j) {
                Some((cont, next)) if (0x80..=0xbf).contains(&cont) => {
                    seq.push(cont);
                    j = next;
                }
                _ => {
                    ok = false;
                    break;
                }
            }
        }

        if ok && std::str::from_utf8(&seq).is_ok() {
            repaired.extend_from_slice(&seq);
            changed = true;
            i = j;
        } else {
            repaired.push(lead);
            i += 1;
        }
    }

    changed.then(|| String::from_utf8(repaired).ok()).flatten()
}

fn utf8_continuation_count(lead: u8) -> Option<usize> {
    match lead {
        0xc2..=0xdf => Some(1),
        0xe0..=0xef => Some(2),
        0xf0..=0xf4 => Some(3),
        _ => None,
    }
}

fn parse_cat_v_meta_byte(bytes: &[u8], start: usize) -> Option<(u8, usize)> {
    if start + 2 > bytes.len() || &bytes[start..start + 2] != b"M-" {
        return None;
    }
    let pos = start + 2;
    match bytes.get(pos).copied()? {
        b'^' => {
            let c = bytes.get(pos + 1).copied()?;
            let low = if c == b'?' {
                0x7f
            } else if (b'@'..=b'_').contains(&c) {
                c - b'@'
            } else {
                return None;
            };
            Some((low | 0x80, pos + 2))
        }
        c if (0x20..=0x7e).contains(&c) => Some((c | 0x80, pos + 1)),
        _ => None,
    }
}

async fn drain_host_pipe<R: tokio::io::AsyncRead + Unpin>(
    mut reader: R,
    live: Option<std::sync::Arc<LiveOutputRelay>>,
    stream: crate::agentic::ToolOutputStream,
) -> std::io::Result<Vec<u8>> {
    use tokio::io::AsyncReadExt as _;

    let mut output = Vec::new();
    let mut chunk = [0u8; 8 * 1024];
    loop {
        let read = reader.read(&mut chunk).await?;
        if read == 0 {
            return Ok(output);
        }
        if let Some(live) = live.as_ref() {
            live.write(stream, &chunk[..read]);
        }
        output.extend_from_slice(&chunk[..read]);
    }
}

/// INTERIM (#297) host shell selection: `bash -c` with an `sh -c` fallback
/// when bash is absent — the same sh-compatible free-form mode the confined
/// shell ran, so [`venv_cmd_prefix`]'s `export …;` prefix works unchanged.
///
/// Hardened (#297) so a hung child can never wedge the turn:
/// - `kill_on_drop(true)` + `process_group(0)` (own process group) so the whole
///   child *tree* dies when we drop the handle, not just the immediate `bash`.
/// - stdin redirected from `/dev/null` so a child that reads stdin sees EOF
///   instead of blocking forever waiting on a tty the agent can't feed.
/// - a [`host_exec_timeout`] wall-clock ceiling: on expiry the child is killed
///   and we return `timed_out: true` with exit code 124, matching the confined
///   path's envelope shape.
#[cfg(not(windows))]
pub(super) async fn host_shell_output(
    route: ShellRoute,
    cmd: &str,
    cwd: &str,
    live: Option<std::sync::Arc<LiveOutputRelay>>,
    command_budget: crate::RunCommandBudget,
) -> std::io::Result<HostShellRun> {
    host_shell_output_with_timeout(route, cmd, cwd, live, host_exec_timeout(command_budget)).await
}

/// newt's control-plane env vars that must NEVER flow into a host-shell child
/// (#8 / invariant 9). Two classes, both newt-internal:
///
/// - **authority switches** — an inherited `NEWT_DISABLE_OCAP` /
///   `NEWT_FULL_ACCESS` / `NEWT_UNSAFE_HOST_EXEC` / … would silently re-assert
///   authority the session did not grant: a `newt` spawned by a Yolo child would
///   re-derive Yolo from the env twin instead of a fresh operator decision (the
///   authority-switch-survives-one-hop hole);
/// - **newt's own secrets** — `NEWT_AGENT_KEY` (the capability envelope),
///   `NEWT_OPERATOR_KEY`, and `NEWT_TOKEN_PASSPHRASE` (the encrypted-token-store
///   unlock) would let the child forge capabilities or decrypt the token store.
///
/// Knowledge in data (three Cs): a new `NEWT_` control switch is added here. The
/// child KEEPS the operator's *general* environment — the `--full-access` /
/// `--disable-ocap` lane is the operator's explicit "run with my ambient
/// authority" opt-out, so provider credentials etc. are their deliberate grant;
/// only newt's OWN control plane is excised.
pub(super) const CHILD_STRIPPED_AUTHORITY_ENV: &[&str] = &[
    "NEWT_DISABLE_OCAP",
    "NEWT_FULL_ACCESS",
    "NEWT_UNSAFE_HOST_EXEC",
    "NEWT_BENCH_OCAP",
    "NEWT_SHELL_ENGINE",
    "NEWT_WINDOWS_CMD",
    "NEWT_SHELL_ENV_PASSTHROUGH",
    "NEWT_WRITE_PATHS",
    "NEWT_READ_PATHS",
    "NEWT_EXEC_PATHS",
    "NEWT_VENV",
    "NEWT_NO_ROUTE",
    "NEWT_AGENT_KEY",
    "NEWT_OPERATOR_KEY",
    "NEWT_TOKEN_PASSPHRASE",
];

/// Excise newt's whole control plane ([`CHILD_STRIPPED_AUTHORITY_ENV`]) from a
/// host-shell child. `env_remove` marks each key removed in the child's env plan
/// whether or not it is currently set, so no authority switch or newt secret can
/// reach the child regardless of the ambient environment.
fn strip_child_authority_env(c: &mut tokio::process::Command) {
    for key in CHILD_STRIPPED_AUTHORITY_ENV {
        c.env_remove(key);
    }
}

/// Build the host-shell child command, stripping newt's whole control plane
/// (authority switches + newt's own secrets, [`strip_child_authority_env`]) so
/// none can flow into the child and re-assert authority the session did not
/// grant it or leak newt's credentials (#8 / step-7.1a, invariant 9). The child
/// inherits the rest of the environment (the Yolo lane's explicit ambient-
/// authority grant). Own process group (setsid-equivalent) + `kill_on_drop` so a
/// hung or tty-stealing child is reaped as a whole tree.
pub(super) fn host_shell_command(
    route: ShellRoute,
    fallback: bool,
    cmd: &str,
    cwd: &str,
) -> std::io::Result<tokio::process::Command> {
    let executable = if route == ShellRoute::AmbientBrush {
        std::env::current_exe()?
    } else {
        std::path::PathBuf::new()
    };
    host_shell_command_at(route, fallback, cmd, cwd, &executable)
}

fn host_shell_command_at(
    route: ShellRoute,
    fallback: bool,
    cmd: &str,
    cwd: &str,
    executable: &std::path::Path,
) -> std::io::Result<tokio::process::Command> {
    use std::ffi::OsStr;
    use std::process::Stdio;
    let runner = crate::ambient_brush::runner_path(executable);
    let (program, flag): (&OsStr, &str) = match route {
        ShellRoute::Cmd => (OsStr::new("cmd"), "/C"),
        ShellRoute::AmbientBrush => (runner.as_os_str(), ""),
        ShellRoute::BashSh => (OsStr::new(if fallback { "sh" } else { "bash" }), "-c"),
        ShellRoute::Bridled(_) => {
            return Err(std::io::Error::other(
                "bridled route cannot construct an ambient child",
            ))
        }
    };
    let mut c = tokio::process::Command::new(program);
    if route != ShellRoute::AmbientBrush {
        c.arg(flag);
    }
    if route == ShellRoute::AmbientBrush {
        let tools = dunce::simplified(executable)
            .parent()
            .ok_or_else(|| std::io::Error::other("executable has no parent"))?
            .join("tools");
        let mut paths = vec![tools];
        // Windows PATH uses semicolons, not a POSIX export prefix. Preserve
        // the operator's virtualenv using the native executable directory.
        if let Some(venv) =
            std::env::var_os("NEWT_VENV").or_else(|| std::env::var_os("VIRTUAL_ENV"))
        {
            paths.push(std::path::Path::new(&venv).join(if cfg!(windows) {
                "Scripts"
            } else {
                "bin"
            }));
            c.env("VIRTUAL_ENV", venv);
        }
        if let Some(path) = std::env::var_os("PATH") {
            paths.extend(std::env::split_paths(&path));
        }
        let path = std::env::join_paths(paths).map_err(std::io::Error::other)?;
        c.env("PATH", path);
    } else if route == ShellRoute::BashSh {
        c.arg(agent_bridle_tool_shell::with_posix_command_discovery(cmd));
    } else {
        c.arg(cmd);
    }
    c.current_dir(cwd)
        .stdin(if route == ShellRoute::AmbientBrush {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    #[cfg(not(windows))]
    c.process_group(0);
    strip_child_authority_env(&mut c);
    Ok(c)
}

#[cfg(not(windows))]
pub(super) async fn host_shell_output_with_timeout(
    route: ShellRoute,
    cmd: &str,
    cwd: &str,
    live: Option<std::sync::Arc<LiveOutputRelay>>,
    timeout: std::time::Duration,
) -> std::io::Result<HostShellRun> {
    async fn run_one(
        mut child: tokio::process::Child,
        live: Option<std::sync::Arc<LiveOutputRelay>>,
        timeout: std::time::Duration,
    ) -> std::io::Result<HostShellRun> {
        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| std::io::Error::other("host shell stdout was not piped"))?;
        let stderr = child
            .stderr
            .take()
            .ok_or_else(|| std::io::Error::other("host shell stderr was not piped"))?;
        let completed = async {
            let (status, stdout, stderr) = tokio::try_join!(
                child.wait(),
                drain_host_pipe(
                    stdout,
                    live.clone(),
                    crate::agentic::ToolOutputStream::Stdout
                ),
                drain_host_pipe(stderr, live, crate::agentic::ToolOutputStream::Stderr),
            )?;
            Ok::<_, std::io::Error>((status, stdout, stderr))
        };
        match tokio::time::timeout(timeout, completed).await {
            Ok(Ok((status, stdout, stderr))) => Ok(HostShellRun {
                exit_code: status.code().unwrap_or(-1) as i64,
                stdout,
                stderr,
                timed_out: false,
            }),
            Ok(Err(e)) => Err(e),
            Err(_elapsed) => Ok(HostShellRun {
                exit_code: 124,
                stdout: Vec::new(),
                stderr: format!(
                    "command exceeded {}s host-shell timeout and was killed\n",
                    timeout.as_secs()
                )
                .into_bytes(),
                timed_out: true,
            }),
        }
    }

    match host_shell_command(route, false, cmd, cwd)?.spawn() {
        Ok(child) => run_one(child, live, timeout).await,
        Err(e) if route == ShellRoute::BashSh && e.kind() == std::io::ErrorKind::NotFound => {
            run_one(
                host_shell_command(route, true, cmd, cwd)?.spawn()?,
                live,
                timeout,
            )
            .await
        }
        Err(e) => Err(e),
    }
}

/// Windows ambient selection: supervised Brush by default, cmd on explicit
/// opt-out. Both use the existing command wall and live output drain.
#[cfg(windows)]
pub(super) async fn host_shell_output(
    route: ShellRoute,
    cmd: &str,
    cwd: &str,
    live: Option<std::sync::Arc<LiveOutputRelay>>,
    command_budget: crate::RunCommandBudget,
) -> std::io::Result<HostShellRun> {
    host_shell_output_with_timeout(route, cmd, cwd, live, host_exec_timeout(command_budget)).await
}

#[cfg(windows)]
pub(super) async fn host_shell_output_with_timeout(
    route: ShellRoute,
    cmd: &str,
    cwd: &str,
    live: Option<std::sync::Arc<LiveOutputRelay>>,
    timeout: std::time::Duration,
) -> std::io::Result<HostShellRun> {
    let cmd_builder = host_shell_command(route, false, cmd, cwd)?;
    supervise_windows_shell(
        cmd_builder,
        (route == ShellRoute::AmbientBrush).then_some(cmd),
        live,
        timeout,
    )
    .await
}

#[cfg(windows)]
async fn supervise_windows_shell(
    mut cmd_builder: tokio::process::Command,
    script: Option<&str>,
    live: Option<std::sync::Arc<LiveOutputRelay>>,
    timeout: std::time::Duration,
) -> std::io::Result<HostShellRun> {
    use tokio::io::AsyncWriteExt;
    let mut child = cmd_builder.spawn()?;
    // The runner waits on stdin. No command can start before job assignment.
    // Closing this non-inherited handle kills the entire tree on every exit,
    // including timeout and future cancellation. Refuse if assignment fails.
    let _job = if script.is_some() {
        Some(
            crate::confined_exec::WindowsJob::for_process(
                child
                    .raw_handle()
                    .ok_or_else(|| std::io::Error::other("missing child handle"))?,
            )
            .ok_or_else(|| std::io::Error::other("cannot supervise ambient Brush process tree"))?,
        )
    } else {
        None
    };
    let mut stdin = child.stdin.take();
    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| std::io::Error::other("host shell stdout was not piped"))?;
    let stderr = child
        .stderr
        .take()
        .ok_or_else(|| std::io::Error::other("host shell stderr was not piped"))?;
    let completed = async {
        if let Some(script) = script {
            let mut input = stdin
                .take()
                .ok_or_else(|| std::io::Error::other("Brush stdin was not piped"))?;
            let encoded = serde_json::to_vec(script).map_err(std::io::Error::other)?;
            input.write_all(&encoded).await?;
            input.shutdown().await?;
            drop(input);
        }
        let (status, stdout, stderr) = tokio::try_join!(
            child.wait(),
            drain_host_pipe(
                stdout,
                live.clone(),
                crate::agentic::ToolOutputStream::Stdout
            ),
            drain_host_pipe(stderr, live, crate::agentic::ToolOutputStream::Stderr),
        )?;
        Ok::<_, std::io::Error>((status, stdout, stderr))
    };
    match tokio::time::timeout(timeout, completed).await {
        Ok(Ok((status, stdout, stderr))) => Ok(HostShellRun {
            exit_code: status.code().unwrap_or(-1) as i64,
            stdout,
            stderr,
            timed_out: false,
        }),
        Ok(Err(e)) => Err(e),
        Err(_elapsed) => Ok(HostShellRun {
            exit_code: 124,
            stdout: Vec::new(),
            stderr: format!(
                "command exceeded {}s host-shell timeout and was killed\r\n",
                timeout.as_secs()
            )
            .into_bytes(),
            timed_out: true,
        }),
    }
}

/// Whether a confined-shell envelope carries the STRUCTURED `denied: true`
/// flag — the leash's machine-readable signal that the brush interceptor
/// refused an exec / open inside the free-form command. Reads the structured
/// field agent-bridle emits; it does NOT parse stdout/stderr (the old stderr
/// string-match was fragile — a command that merely *printed* a denial-like
/// phrase could be misread, and any wording drift would silently break
/// detection).
pub(super) fn envelope_denied(envelope: &serde_json::Value) -> bool {
    envelope
        .get("denied")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
}

/// Build a human-readable denial message from the envelope's structured
/// `denials: [{ kind, target, reason }]` list, joining each entry's `reason`.
/// Falls back to a generic message when the list is missing or empty.
pub(super) fn envelope_denial_reason(envelope: &serde_json::Value) -> String {
    let reasons: Vec<String> = envelope
        .get("denials")
        .and_then(serde_json::Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(|d| d.get("reason").and_then(serde_json::Value::as_str))
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default();
    if reasons.is_empty() {
        "denied: the capability leash refused an operation".to_string()
    } else {
        reasons.join("; ")
    }
}

/// The standard `run_command` capability-denial result, composed EXACTLY ONCE:
/// a single `capability denied: <bare reason>. <recovery hint>` for the model.
///
/// #775 (§2.5): the model-facing message is ONE clean level. Two earlier defects
/// are removed:
///
/// 1. The bare denial `reason` (a full sentence from the leash, e.g.
///    `exec of "export" is not within the granted authority`) is NO LONGER
///    stuffed into the old `print_denied` bare `'{target}'` slot. Doing so produced
///    the garbled `capability denied: exec does not permit '<whole reason
///    sentence> - add it via …>'` — a denial sentence nested inside another.
///    That notice path received only the BARE command target, matching its
///    `{axis} does not permit '{target}'` contract (the same shape the fs path
///    uses via [`super::denied_fs_result`]).
/// 2. The stale `extra_exec` config hint is gone from the model-facing message.
///    #721 superseded "edit your `[tui.permissions]` config" with the
///    model-actionable [`denial_recovery_hint`] (`request_permissions`), so the
///    model now sees the bare reason once plus that hint — never a config edit
///    it cannot perform mid-turn.
///
/// The #263 prompt path still falls back here on deny (and on a second denial
/// after a re-execution).
pub(super) fn denied_run_command_result(envelope: &serde_json::Value, _color: bool) -> String {
    let recovery = denial_recovery_hints(envelope)
        .map(|hints| hints.join(" "))
        .unwrap_or_else(|| {
            "No actionable capability grant is identified. Take a different approach within your current authority.".into()
        });
    format!(
        "capability denied: {}. {}",
        envelope_denial_reason(envelope),
        recovery
    )
}

/// #2759: use only trusted denial metadata, never output or a generic Denied
/// outcome. An actual blocked write outranks any exec misses in the same batch.
pub(super) fn worktree_denial_notice(
    adopted: Option<&crate::worktree_adoption::AdoptedWorktree>,
    envelope: &serde_json::Value,
    cwd: &str,
) -> Option<String> {
    let policy = adopted?;
    if !envelope_denied(envelope) {
        return None;
    }
    envelope
        .get("denials")?
        .as_array()?
        .iter()
        .any(|denial| {
            let write = match denial.get("kind").and_then(serde_json::Value::as_str) {
                Some("fs_write") => true,
                Some("open") => {
                    denial
                        .get("reason")
                        .and_then(serde_json::Value::as_str)
                        .and_then(open_denial_axis)
                        == Some("fs_write")
                }
                _ => false,
            };
            write
                && denial
                    .get("target")
                    .and_then(serde_json::Value::as_str)
                    .is_some_and(|path| {
                        !path.is_empty()
                            // A Windows canonical prefix contains '?', which
                            // is syntax rather than a filename wildcard.
                            && !std::path::Path::new(path).components().any(|component| {
                                matches!(component, std::path::Component::Normal(part)
                                    if part.to_string_lossy().contains(['*', '?', '[']))
                            })
                            && policy.blocked(&std::path::Path::new(cwd).join(path))
                    })
        })
        .then(|| policy.notice())
}

/// Preserve each grantable denial's axis and target. A structural or opaque
/// refusal makes the batch ungrantable; never guess an axis or join targets.
///
/// #2629: agent-bridle's structured kinds are `exec` / `open` / `net`
/// (`DenialKind`, vendored `envelope.rs`) — there is no `fs_write` kind on the
/// wire. A refused shell redirect or `source` arrives as `open`, and dropping
/// it as ungrantable left the model with no target to ask for, so it probed
/// (the touch/mkdir loops of #2631). The axis is read from the LEASH's own
/// reason ([`open_denial_axis`]); the target brush hands the interceptor is
/// already the absolute path. Neither comes from the child's output (#2633).
pub(super) fn denial_recovery_hints(envelope: &serde_json::Value) -> Option<Vec<String>> {
    let denials = envelope
        .get("denials")?
        .as_array()
        .filter(|rows| !rows.is_empty())?;
    denials
        .iter()
        .map(|denial| {
            let kind = denial.get("kind")?.as_str()?;
            let reason = denial.get("reason").and_then(serde_json::Value::as_str);
            if reason.is_some_and(is_structural_refusal) {
                return None;
            }
            let target = denial
                .get("target")?
                .as_str()
                .filter(|target| !target.trim().is_empty())?;
            let axis = match kind {
                "exec" | "fs_read" | "fs_write" | "net" => kind,
                // Brush hands the interceptor the absolute path, but the
                // safe-subset engine's pre-check records the redirect literal
                // as typed (relative) or a glob pattern. A grant of either is
                // inserted verbatim and never covers the retry — the loop
                // change (#2629) exists to remove — so fail closed to the
                // no-grant text. Same absolute-only rule as
                // `declared_filesystem_requests`.
                "open"
                    if std::path::Path::new(target).is_absolute()
                        && !target.contains(['*', '?', '[']) =>
                {
                    open_denial_axis(reason?)?
                }
                _ => return None,
            };
            Some(denial_recovery_hint(axis, target))
        })
        .collect()
}

/// The fs axis an `open` denial refused on, as the leash itself states it.
/// The recorded reason is `ToolError`'s Display, `denied: ` + the message
/// `ToolContext::check_path` (vendored `context.rs`) wrote: `"{op} of {path}
/// (resolved {canon}) is not within the granted fs_{op} scope"`, or `"{op} of
/// {path:?} denied: cannot canonicalize (…)"` when no ancestor resolves; `op`
/// is `read` or `write`. This is the leash's structured `reason` field, not
/// child stderr — but it IS text matching on a library-generated string, not
/// a typed field: bridle's `Denial` is `{kind, target, reason}` and carries no
/// axis for `open` (vendored `envelope.rs`). Kept as narrow as that string
/// allows: the VERB decides, because it precedes the model's own path text;
/// the suffix, when present, must agree (a path spelled `…/fs_write…` in a
/// read refusal must not steer the axis). Anything else (`/dev/fd`
/// reservations, the fail-closed no-caveats default, a cancelled run) names
/// no axis and stays ungrantable. If bridle ever exposes the axis as a field,
/// read that and delete this.
fn open_denial_axis(reason: &str) -> Option<&'static str> {
    let reason = reason.strip_prefix("denied: ").unwrap_or(reason);
    let reason = reason.trim_end_matches('.');
    let (axis, other) = if reason.starts_with("write of ") {
        ("fs_write", "fs_read")
    } else if reason.starts_with("read of ") {
        ("fs_read", "fs_write")
    } else {
        return None;
    };
    (!reason.ends_with(&format!("is not within the granted {other} scope"))).then_some(axis)
}

/// #2274 — absence must never be ambiguous.
///
/// A binary the carried userland does not carry used to reach the model as
/// `error: command exited 127` wrapped around brush's own `command not found:
/// X`, which is indistinguishable from a broken machine. That ambiguity is why
/// the confined profile read as flakiness for six months instead of as policy.
///
/// Three states hide behind that one rendering, and the right next move differs
/// in each, so the model must be able to tell them apart:
///
/// | state | envelope | remedy |
/// |---|---|---|
/// | denied by a grant | `denied:true` + `denials[kind=exec]`, exit 126 | ask for the grant |
/// | not carried, on the host | exit 127, no denials, host PATH resolves | build authority for project validation, or direct `exec:<abs path>` |
/// | not on this host at all | exit 127, no denials, host PATH misses | no grant can help |
///
/// Discrimination is STRUCTURED — the exit code plus the `denials` array — the
/// same rule [`envelope_denied`] follows, and for the same reason: a command
/// that merely *prints* a denial-like phrase must not be misread. Exit 127 is
/// brush's `CommandNotFound`; a refusal the interceptor actually made carries
/// `denials` and is exit 126, so it is excluded here and left to
/// [`denied_run_command_result`].
///
/// An absence also needs brush to NAME the program it could not find (#2315).
/// A 127 it did not attribute (a `make` recipe, a test harness returning 127)
/// is a check failing on its own terms: refusing it as an absence would route
/// a repairable failure to the no-edit-can-help guidance.
///
/// Returns `None` for anything that is not an absence, leaving ordinary output
/// and ordinary failures untouched.
///
/// Only newt can answer the last row. brush runs behind the fence, where a PATH
/// probe would be answering about the fence rather than about the host; newt's
/// own process is never Landlocked, so it can resolve the real host PATH and
/// separate "installed, but not reachable from in here" from "not installed".
pub(crate) fn absent_binary_refusal(
    envelope: &serde_json::Value,
    exec: &crate::caveats::Scope<String>,
) -> Option<String> {
    // 127 = brush's `ExecutionExitCode::NotFound`: the program was never
    // resolved, so the interceptor was never consulted.
    if envelope
        .get("exit_code")
        .and_then(serde_json::Value::as_i64)
        != Some(127)
    {
        return None;
    }
    absent_program_note(envelope, exec)
}

/// The absence message for the program brush named in `command not found: X`,
/// whatever the envelope's exit code. `None` for a structured denial.
///
/// #2629 round 3: `prog` comes from the CHILD's own stderr, which a permitted
/// script can forge — print `command not found: /usr/bin/git` and exit
/// whatever code it likes. The renderer this replaces resolved that name on
/// the host and, when found, pasted the resolved absolute path into an
/// "ask the operator for exec:<abs>" recommendation. The host lookup proves
/// the PATH exists; it proves nothing about what the confined child actually
/// ran, so the child's own chosen text was picking which host path the
/// operator got coached to authorize. The lookup still selects which of the
/// two generic sentences below applies (a real distinction for
/// [`run_command_result_is_denial`]'s grant-gap classification), but its
/// resolved path is never interpolated into either one. Only a trusted,
/// invocation-bound refusal (the leash's `denials`) may name a target.
fn absent_program_note(
    envelope: &serde_json::Value,
    exec: &crate::caveats::Scope<String>,
) -> Option<String> {
    // A structured refusal is a DENIAL, not an absence. Relabelling one as the
    // other would send the model to the wrong remedy.
    if structured_denials_present(envelope) {
        return None;
    }

    let prog = named_program(envelope, "command not found: ")?.to_string();
    let granted = granted_host_binaries(exec);

    // The host probe only picks WHICH generic sentence applies; its resolved
    // path is deliberately discarded, never rendered.
    Some(if host_path_lookup(&prog).is_some() {
        format!(
            "error: {prog}: {ABSENT_BINARY_MARKER}.\n  \
             granted host binaries: {granted}\n  \
             For project compiler/test validation, if lifecycle is advertised, prefer lifecycle action=build \
             for the appropriate project phase: it requests explicit offline build authority.\n  \
             The shell's own report named this program; that text is not trusted evidence of what the \
             confined child actually ran, so no specific path is named here. If direct execution would \
             genuinely help, ask the operator via request_permissions rather than guessing a target; do \
             not retry a declined grant."
        )
    } else {
        // Deliberately NO grant coaching here: granting exec for a binary that
        // is not installed is a no-op, and teaching the model to ask for one is
        // exactly the futile loop the denial journal exists to detect.
        format!(
            "error: {prog}: {ABSENT_BINARY_MARKER}, and {NOT_ON_HOST_MARKER}.\n  \
             granted host binaries: {granted}\n  \
             no grant can supply it - install it on the host, or use a carried tool."
        )
    })
}

/// The phrase every absent-binary refusal carries. The loop's exec-denial
/// accounting uses this shared marker to distinguish a requestable host-binary
/// grant from a binary that is not installed, without prescribing a repair.
pub(crate) const ABSENT_BINARY_MARKER: &str = "not in this profile's carried userland";

/// The suffix that separates "absent here but installed on the host" (a grant
/// gap) from "not installed at all" (no grant can help). One constant, for the
/// same renderer/classifier drift reason as [`ABSENT_BINARY_MARKER`] (#2304).
pub(crate) const NOT_ON_HOST_MARKER: &str = "not installed on this host";

/// Whether the envelope carries a structured refusal: the leash's `denied`
/// flag or a non-empty `denials` array. Every "is this an absence / an
/// unstructured failure?" classifier runs this first, so none of them can
/// relabel a refusal the interceptor actually made.
fn structured_denials_present(envelope: &serde_json::Value) -> bool {
    envelope_denied(envelope)
        || envelope
            .get("denials")
            .and_then(serde_json::Value::as_array)
            .is_some_and(|d| !d.is_empty())
}

/// #2273 → #2629 round 2: exit 126 with no structured denial stays an
/// UNSTRUCTURED failure.
///
/// brush exits 126 when it found a program but could not execute it. Behind
/// the fence that is either the KERNEL refusing an exec the interceptor had
/// admitted (`~/.cargo/bin` outside the read roots is #2273's own transcript)
/// or an ordinary shell failure (a missing execute bit, a script without a
/// shebang) — and the envelope cannot tell the two apart, because a kernel
/// refusal is never recorded in `denials` (that seam is #2421). The renderer
/// this replaces tried to tell them apart anyway: it took the program from
/// brush's `failed to execute command '<x>'` stderr line (else the leading
/// argv token), resolved it on the host, and when the path lay outside the
/// read grant asserted `capability denied` and named the grant to ask for.
/// Every one of those inputs is child-controlled — a permitted script can
/// print that exact line and `exit 126` — so the denial and its target came
/// from text the model, or whatever it ran, had chosen. That is the trust
/// boundary [`envelope_denied`] holds (#2633), and a host existence or mode
/// check authenticates neither the failed invocation nor a refusal.
///
/// So the note says only what the envelope proves: a refusal MAY have
/// happened, the target and axis are unknown, and no grant is named. The
/// child's own output stays in front of it, and the outcome is the envelope's
/// own (`Failed`), not `Denied`. The one thing that mints a target is the
/// leash's structured `denials`, which [`denied_run_command_result`] renders
/// before this is reached.
pub(super) fn unstructured_exit_126_note(envelope: &serde_json::Value) -> Option<&'static str> {
    (envelope
        .get("exit_code")
        .and_then(serde_json::Value::as_i64)
        == Some(126)
        && !structured_denials_present(envelope))
    .then_some(UNSTRUCTURED_EXIT_126_NOTE)
}

/// Appended to an exit-126 result that carries no structured denial. Spells
/// out none of newt's denial vocabulary (`capability denied`, `does not
/// permit`, `not within the granted authority`), none of the OS's
/// (`permission denied`), and never the name of the grant tool, so
/// `run_command_result_is_denial` grounds a denial claim only on what the
/// CHILD printed and no consumer can read a grant request out of this note.
pub(crate) const UNSTRUCTURED_EXIT_126_NOTE: &str = "\n(exit 126: the shell found a command but \
    could not execute it. No structured denial was recorded, so whether the sandbox refused it is \
    unknown, and so are the path and the axis it would have refused on; a missing execute bit or \
    a script without a shebang exits 126 as well. Nothing here names a grant to ask for: do not \
    infer one from the text above. Check the file's mode and interpreter line first; if both are \
    right, report exactly what was run to the operator rather than guessing a grant.)";

/// Which program brush failed on, as brush names it in its own error:
/// `command not found: X` for 127. That is the authoritative answer for a
/// compound command, where the leading token (`cd newt-core && cargo test`)
/// is not the one that failed (#2304). The LAST occurrence wins: the exit
/// status belongs to the command that ran last. `None` when brush named
/// nothing, because an unnamed 127 is not an absence (#2315).
///
/// Reading stderr is acceptable HERE and not in [`envelope_denied`] because
/// the one caller is already fenced behind the structured exit-127-and-no-
/// denials test and the text it picks is an ABSENCE advisory, not a refusal:
/// `envelope_denied` decides whether authority was refused; this only picks
/// which program the advisory is about. The exit-126 path stopped reading it
/// (#2629 round 2): there the name would have chosen a grant TARGET, and a
/// target comes only from the leash's structured `denials`, never from text
/// the child controls.
fn named_program<'a>(envelope: &'a serde_json::Value, marker: &str) -> Option<&'a str> {
    envelope
        .get("stderr")
        .and_then(serde_json::Value::as_str)
        .and_then(|stderr| stderr.rfind(marker).map(|at| &stderr[at + marker.len()..]))
        .and_then(|rest| rest.split(['\'', '\n']).next())
        .map(str::trim)
        .filter(|name| !name.is_empty())
}

/// F32/#2537, PR #2577 round 3 (Shawn): when the confined shell is about to
/// run a bare `git …` command in the session's OWN repository on a
/// non-default branch, widen the caveats passed to THIS ONE dispatch with
/// kernel WRITE on the worktree's own gitdir and the common `objects/`
/// directory (`own_gitdir_shell_write_grant` — round 3 narrowed the grant to
/// exactly those two directories; round 4 bound it to the identity resolved
/// at session start rather than a live re-resolve, see that function's doc
/// comment). This unblocks a confined-shell `git add` under the real kernel
/// fence (a file-level Landlock rule cannot carry the
/// `MAKE_REG`/`REFER`/`REMOVE_FILE` rights `index.lock` create+rename and
/// object insertion need — a directory rule can).
/// The incoming session must already permit writing the workspace root.
/// A cached repository identity alone cannot authorize metadata writes for a
/// read-only session or a grant limited to another path or an individual file.
///
/// Deliberately scoped to a SIMPLE `git` invocation, not folded into the
/// session `fs_write` scope: `write_file`/`edit_file` on git metadata stay
/// refused (`caveats::apply_cli_fs_grants` never grants this), and a shell
/// `git commit` is refused outright before reaching here
/// (`run_command_creates_shell_git_commit`), so this widening never needs to
/// cover a ref move — `refuse_if_default_branch` in `newt-git` is what
/// prevents that, at the one place a commit can actually land. A compound
/// command (`git add && rm -rf /`) is not "leading program `git`" in the
/// sense that matters here either way — it still runs through the confined
/// engine, which gates each spawn on these SAME (possibly widened) caveats,
/// so a second program in the pipeline gets the same widened `fs_write` too;
/// that is the accepted trade-off Shawn signed off on (a confined-shell
/// `rm -rf <common>/objects` becomes possible on a non-default branch — see
/// `RESULT-dec2-own-gitdir.md`), not an oversight.
///
/// Mirrors the shape a sibling PR's `dispatch_caveats_for_command` (build
/// tools) uses — a separate function, called at the same call site, so the
/// two compose without conflict.
pub(super) fn dispatch_caveats_for_git_shell(
    cmd: &str,
    workspace: &str,
    caveats: &crate::caveats::Caveats,
) -> crate::caveats::Caveats {
    if leading_program(cmd) != Some("git")
        || !crate::caveats::permits_path(&caveats.fs_write, workspace)
    {
        return caveats.clone();
    }
    // Round 4, Blocker 1: NOT `own_gitdir_grants` — that re-resolves via a
    // live `rev-parse`, which follows model-writable pointers (the workspace
    // `.git` gitlink, `<gitdir>/commondir`). This bounds the write grant to
    // the identity cached at session start.
    let write = crate::git_hardening::own_gitdir_shell_write_grant(std::path::Path::new(workspace));
    if write.is_empty() {
        return caveats.clone();
    }
    let mut widened = caveats.clone();
    widened.fs_write = match &widened.fs_write {
        crate::caveats::Scope::All => crate::caveats::Scope::All,
        crate::caveats::Scope::Only(set) => {
            crate::caveats::Scope::only(set.iter().cloned().chain(write))
        }
    };
    // Real git ALWAYS tries to read the system config (`/etc/gitconfig`),
    // regardless of repo/branch — not just on a host that happens to have
    // one. Landlock's base read allowlist does not include it (CI caught
    // this: a Landlock-confined `git add` on a runner that ships
    // `/etc/gitconfig` failed with "unknown error occurred while reading
    // the configuration files", exit 128 — this environment's sandbox
    // silently worked only because it has no such file). One extra,
    // non-secret, well-known system path, granted only on this ONE widened
    // dispatch, same as the write grant above.
    widened.fs_read = match &widened.fs_read {
        crate::caveats::Scope::All => crate::caveats::Scope::All,
        crate::caveats::Scope::Only(set) => crate::caveats::Scope::only(
            set.iter()
                .cloned()
                .chain(std::iter::once("/etc/gitconfig".to_string())),
        ),
    };
    widened
}

/// The leading program of `cmd`: `FOO=bar prog ...` - an env assignment is not
/// the program.
pub(super) fn leading_program(cmd: &str) -> Option<&str> {
    cmd.split_ascii_whitespace().find(|tok| !tok.contains('='))
}

/// dec1-build-grant round 2 (Reviewer FIX-FIRST, PR #2579): the caveats for
/// ONE confined-shell dispatch — `caveats` as-is, unless `cmd`'s leading
/// program is a build tool (`confined_exec::is_build_tool_exec`), in which
/// case its toolchain read roots (`confined_exec::toolchain_read_roots`) are
/// added to `fs_read`. Call-scoped and NEVER returned to the permission
/// gate: `widen_caveats` deliberately leaves an exec grant's `fs_read`
/// untouched, because its result feeds `recalled_caveats` — the caveats
/// checked for every tool the model calls this session, including
/// `read_file`. Widening the SESSION's `fs_read` from an `exec:cargo` grant
/// would let `read_file` read `$CARGO_HOME/credentials.toml` for the rest of
/// the session; widening only this one dispatch's caveats lets the SPAWNED
/// cargo process resolve its own toolchain and nothing else gains the read.
fn dispatch_caveats_for_command(
    cmd: &str,
    caveats: &crate::caveats::Caveats,
) -> crate::caveats::Caveats {
    let mut widened = caveats.clone();
    // #2596 round 3: a host-scoped `net` grant (from `[tui.permissions] net =
    // [...]` or a session-widened net prompt) is `Unknown` to agent-bridle
    // 0.8's admission on every backend and refuses the WHOLE spawn (L3
    // BOUND) — not just the network. Narrow it to `net: none`, which the
    // shell's `DenyDirect` sandbox policy (`confined_exec::runtime_sandbox_policy`)
    // can bind on Linux (measured). On macOS, Seatbelt still refuses a
    // restricted `net` scope; a separate agent-bridle fix is under way. On
    // Windows, AppContainer can bind `net:none` but restricted exec can still
    // refuse; unvalidated here. Fail-closed posture on non-Linux backends is
    // preserved. See
    // `caveats::spawn_net_scope` doc comment for why narrowing loses nothing
    // a spawned shell child could enforce anyway.
    widened.net = crate::caveats::spawn_net_scope(&widened.net);
    if let crate::caveats::Scope::Only(exec) = &mut widened.exec {
        let twins = crate::confined_exec::developer_exec_twins(exec.iter());
        exec.extend(twins);
    }
    if leading_program(cmd).is_some_and(crate::confined_exec::is_build_tool_exec) {
        if let crate::caveats::Scope::Only(reads) = &mut widened.fs_read {
            reads.extend(crate::confined_exec::toolchain_read_roots());
        }
    }
    widened
}

/// The exec grants in force, for the refusal's second line. Naming what IS
/// granted turns "no" into a question the operator can answer in one line.
fn granted_host_binaries(exec: &crate::caveats::Scope<String>) -> String {
    match exec {
        crate::caveats::Scope::All => "(unrestricted)".to_string(),
        crate::caveats::Scope::Only(set) if set.is_empty() => "(none)".to_string(),
        crate::caveats::Scope::Only(set) => set
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>()
            .join(", "),
    }
}

/// Resolve `prog` against the REAL host PATH.
///
/// Sound because newt's own process is never Landlocked - the fence is applied
/// on the spawning thread immediately before the child starts (agent-bridle's
/// `ConfinedCommand::spawn_authorized`), never to newt itself. This therefore
/// answers "is it installed on this host", which is exactly the question the
/// confined child cannot answer about itself.
fn host_path_lookup(prog: &str) -> Option<String> {
    fn executable(p: &std::path::Path) -> bool {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
        }
        #[cfg(not(unix))]
        {
            p.is_file()
        }
    }

    // An explicit path is already the answer; PATH is not consulted for it.
    if prog.contains('/') || prog.contains('\\') {
        return executable(std::path::Path::new(prog)).then(|| prog.to_string());
    }
    std::env::split_paths(&std::env::var_os("PATH")?)
        .map(|dir| dir.join(prog))
        .find(|cand| executable(cand))
        .map(|p| p.display().to_string())
}

/// The standard `run_command` success path: return stdout/stderr, or `(exit N)`
/// when the command produced no output. Factored verbatim so
/// the #263 re-execution path shares one formatter with the first dispatch.
pub(super) fn shell_envelope_output(
    envelope: &serde_json::Value,
    tool_output_lines: usize,
    color: bool,
    tool_offload: bool,
    spill_store: Option<&dyn SpillStore>,
    presentation: Option<&mut dyn ToolPresentation>,
) -> String {
    shell_envelope_output_with_view(
        envelope,
        None,
        tool_output_lines,
        color,
        tool_offload,
        spill_store,
        presentation,
    )
}

/// Keep the captured envelope intact when the caller selects a smaller view.
/// Retention and model-budget capping share the normal command-output path.
pub(super) fn shell_envelope_output_with_view(
    envelope: &serde_json::Value,
    view: Option<&str>,
    _tool_output_lines: usize,
    _color: bool,
    tool_offload: bool,
    spill_store: Option<&dyn SpillStore>,
    presentation: Option<&mut dyn ToolPresentation>,
) -> String {
    let mut presentation = presentation;
    if let Some(presentation) = presentation.as_deref_mut() {
        presentation.execution_result(envelope);
    }
    let stdout = envelope
        .get("stdout")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let stderr = envelope
        .get("stderr")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let truncated_streams = match (
        envelope
            .get("stdout_truncated")
            .and_then(serde_json::Value::as_bool)
            == Some(true),
        envelope
            .get("stderr_truncated")
            .and_then(serde_json::Value::as_bool)
            == Some(true),
    ) {
        (true, true) => Some("stdout and stderr"),
        (true, false) => Some("stdout"),
        (false, true) => Some("stderr"),
        (false, false) => None,
    };
    let capture_notice = truncated_streams
        .map(|streams| format!("[{streams} capture truncated; omitted bytes are unavailable]"));
    let annotate_capture = |text: &str| match &capture_notice {
        Some(notice) => format!("{notice}\n{text}"),
        None => text.to_owned(),
    };
    let out = annotate_capture(&format!("{stdout}{stderr}"));
    let selected = view.map(annotate_capture);
    let view = selected.as_deref().unwrap_or(&out);
    let selected_view = view != out;
    // #1969: the exit code decides success, not the shape of the output.
    //
    // This used to be consulted ONLY when the output was empty, so every
    // command that failed LOUDLY — which is every failing compile — returned
    // a non-empty string with no failure marker and was classified by
    // `tool_result_ok`'s prefix test as a success. Three consumers read that
    // one bit: the turn's `ToolEvent` ledger, `RepeatCallGuard` (which
    // memoizes a `Failure` only for `!ok`, so the per-run steer never fired
    // on a repeated failing build), and `loop_watch::repeated_failure`.
    //
    // The marker is a prefix rather than a suffix because that is what
    // `tool_result_ok` reads, and it names the code because "it failed" with
    // no evidence is the claim this repo keeps refusing to accept elsewhere.
    // The diagnostics follow it untouched — the model still needs them.
    let code = envelope
        .get("exit_code")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(-1);
    let mark_failure = |payload: String| {
        if code == 0 {
            payload
        } else {
            format!("error: command exited {code}\n{payload}")
        }
    };
    if out.trim().is_empty() {
        // A failing command that printed nothing needs no second rendering of
        // its own code: the marker already carries it.
        return if code == 0 {
            format!("(exit {code})")
        } else {
            format!("error: command exited {code}")
        };
    }
    {
        // The terminal follows the selected output before the model-facing
        // token cap or spill teaser is applied.
        if let Some(presentation) = presentation {
            presentation.override_result(view.to_owned());
        }
        // #726/#945: the MODEL-facing payload is capped by the shared TOKEN
        // budget using head+tail. When tool_offload is on, spill the FULL
        // redacted output before capping so the true tail and elided middle stay
        // recoverable via memory_fetch("spill:<id>") and grep.
        //
        // The spill decision sizes with the SAME conservative estimator the cap
        // uses (via `should_spill_full_output` → `cap_estimator`, not the 4 c/t
        // context default) — otherwise output between the conservative cap
        // (3 c/t) and the looser default (4 c/t) gets head/tail-truncated by the
        // cap yet judged "under budget" by the spill gate, so its elided middle
        // is never spilled and becomes unrecoverable. One shared owner keeps
        // "will the cap truncate?" and "should we spill?" from ever diverging.
        let max_tokens = max_output_tokens();
        let est = output_budget::cap_estimator();
        let should_spill = (tool_offload && selected_view)
            || output_budget::should_spill_full_output(
                out.len(),
                out.chars().count(),
                max_tokens,
                tool_offload,
            );
        let mut capped = if should_spill {
            match spill_store {
                Some(store) => {
                    let (id, redacted) = content_spill::store_redacted_full(
                        &out,
                        Some("run_command".to_string()),
                        store,
                    );
                    let redacted = if selected_view {
                        crate::agentic::compress::redact_secrets(view)
                    } else {
                        redacted
                    };
                    let teaser_tokens = est
                        .tokens_for_chars(content_spill::TOOL_RESULT_SPILL_CAP.saturating_sub(512));
                    match id {
                        // Committed: cap with the `spill:<id>` retrieval handle.
                        Some(id) => cap_model_output_with_handle(
                            &redacted,
                            max_tokens.min(teaser_tokens),
                            output_head_tokens(),
                            Some(&id),
                        ),
                        // Commit failed: fail closed — cap the redacted output with
                        // NO handle rather than promise a `spill:<id>` that resolves
                        // to nothing (BHV-SPILL-001).
                        None => cap_model_output(&redacted, max_tokens),
                    }
                }
                None => cap_model_output(view, max_tokens),
            }
        } else {
            cap_model_output(view, max_tokens)
        };
        // A tiny or tail-only presentation budget cannot erase the fact that
        // capture itself was incomplete. The retained source also carries it.
        if let Some(notice) = &capture_notice {
            if !capped.contains(notice) {
                capped.push('\n');
                capped.push_str(notice);
            }
        }
        // #898: if this command's output carries a forge "open a pull/merge
        // request" URL (git prints it on push of a new branch), append an
        // explicit next-step hint so the model opens the PR instead of stalling.
        // Detected from the UNcapped output so a long push log can't truncate the
        // URL away, and appended AFTER the cap so the hint always survives.
        mark_failure(match pr_creation_url(view) {
            Some(url) => format!("{capped}{}", pr_next_step_hint(url)),
            None => capped,
        })
    }
}

/// #898: the forge "open a pull/merge request" URL that git prints on `push` of
/// a new branch — GitHub `…/pull/new/<branch>` (or a `…/compare/…` link) and
/// GitLab `…/merge_requests/new…`. Returned so [`shell_envelope_output`] can
/// append a next-step hint: models routinely push and then stall instead of
/// opening the PR (issue #898). Scans whitespace-split tokens because git emits
/// the URL on its own `remote:`-prefixed line.
pub(super) fn pr_creation_url(output: &str) -> Option<&str> {
    output.split_whitespace().find(|tok| {
        tok.starts_with("https://")
            && (tok.contains("/pull/new/")
                || tok.contains("/merge_requests/new")
                || tok.contains("/compare/"))
    })
}

/// The next-step hint appended after a push whose output carries a PR-creation
/// URL (#898). Names the concrete `gh` command AND the tool boundary — the
/// embedded `git` tool cannot push or open PRs — so the model proceeds through
/// run_command + `gh` instead of looping back to the pushless git tool.
fn pr_next_step_hint(url: &str) -> String {
    format!(
        "\n\n[newt] A branch was pushed. To open a pull request now, call \
         run_command with `gh pr create --fill` (the `gh` CLI is available; the \
         `git` tool cannot push or open PRs). Or open this URL: {url}"
    )
}

/// Lift a confined-shell denial envelope into promptable #263 requests.
///
/// Returns `Some` only when EVERY structured denial entry is an `exec` kind
/// with a non-empty target — the case the human can meaningfully grant (the
/// exact executable target). Any other kind
/// (e.g. an `open` refused inside the shell) keeps the standard denial — which
/// since #2629 names the fs axis and exact path to ask for (see
/// [`open_denial_axis`]); prompting the operator for an `open` is a separate
/// change.
/// #1150: a STRUCTURAL refusal is a can't, not a may-not — the confined shell
/// engine cannot interpret the construct (`$(...)`, backgrounding `&`, heredocs,
/// fd duplication), so NO grant unlocks it. Offering "allow once / session /
/// always" for one is a grant→denial contradiction that destroys trust in the
/// whole permission loop (the operator grants, the engine denies anyway). We
/// detect it by the stable markers agent-bridle's `Refusal::Display` emits, so
/// these fall through to the plain denial (which already names the --yolo
/// escape) with no grant menu.
fn is_structural_refusal(reason: &str) -> bool {
    reason.contains("refused by design:")
        || reason.contains("dynamic construct the confined shell")
        || reason.contains("not yet supported by the confined shell")
}

pub(super) fn exec_denial_requests(envelope: &serde_json::Value) -> Option<Vec<PermissionRequest>> {
    let denials = envelope.get("denials")?.as_array()?;
    if denials.is_empty() {
        return None;
    }
    let mut requests = Vec::with_capacity(denials.len());
    for d in denials {
        if d.get("kind")?.as_str()? != "exec" {
            return None;
        }
        // A structural refusal anywhere in the batch: grants are meaningless,
        // so surface the plain denial for the whole call (#1150).
        if d.get("reason")
            .and_then(serde_json::Value::as_str)
            .is_some_and(is_structural_refusal)
        {
            return None;
        }
        let target = d.get("target")?.as_str().filter(|t| !t.is_empty())?;
        requests.push(PermissionRequest {
            tool: "run_command".to_string(),
            kind: DenialKind::Exec,
            target: target.to_string(),
            reason: d
                .get("reason")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string(),
            harness_bound: false,
        });
    }
    Some(requests)
}

/// #905: lift a confined-shell NET denial envelope into promptable #263 requests
/// — the `net`-axis sibling of [`exec_denial_requests`]. agent-bridle #196
/// surfaces a refused CONNECT host as `Denial { kind: "net", target: <host> }`
/// (with `denied: true`), so when the operator's `net` allow-list refuses a host
/// the shell reached (e.g. `git push` to `github.com`), this turns each into a
/// `PermissionRequest { kind: Net, target: host }` the gate can prompt per-host.
///
/// Returns `Some` only when EVERY denial is a `net` kind with a non-empty host
/// target — the case a grant is meaningful (add the host to the net allow-list).
/// A mixed or non-net batch returns `None` and keeps the standard denial.
pub(super) fn net_denial_requests(envelope: &serde_json::Value) -> Option<Vec<PermissionRequest>> {
    let denials = envelope.get("denials")?.as_array()?;
    if denials.is_empty() {
        return None;
    }
    let mut requests = Vec::with_capacity(denials.len());
    for d in denials {
        if d.get("kind")?.as_str()? != "net" {
            return None;
        }
        let host = d.get("target")?.as_str().filter(|t| !t.is_empty())?;
        requests.push(PermissionRequest {
            tool: "run_command".to_string(),
            kind: DenialKind::Net,
            target: host.to_string(),
            reason: d
                .get("reason")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string(),
            harness_bound: false,
        });
    }
    Some(requests)
}

#[cfg(test)]
mod dispatch_caveats_tests {
    use super::*;
    use crate::caveats::{Caveats, CaveatsExt as _, CountBound, Scope};

    fn base(ws: &str) -> Caveats {
        Caveats {
            fs_read: Scope::only([ws.to_string()]),
            fs_write: Scope::only([ws.to_string()]),
            exec: Scope::only(["cargo".to_string()]),
            net: Scope::none(),
            max_calls: CountBound::Unlimited,
            valid_for_generation: Scope::All,
        }
    }

    /// dec1-build-grant round 2, red test (b): the shell-lane dispatch
    /// caveats for a build-tool command include its toolchain read root —
    /// call-scoped, so `read_file` (which checks the SESSION's caveats, not
    /// this dispatch's) never sees it. Would fail before the fix:
    /// `dispatch_caveats_for_command` did not exist; `dispatch_bridled_shell`
    /// passed the raw session `caveats` straight through, unable to read
    /// `$RUSTUP_HOME`.
    #[test]
    fn a_build_tool_command_gets_its_toolchain_read_root_for_this_dispatch_only() {
        // Pins the toolchain-home resolution so the
        // assertion does not depend on the machine running the suite.
        // Platform-absolute (a POSIX `/fake-home` is not absolute on Windows),
        // and under the process-env lock like every other env-pinning test.
        let _env = crate::process_env::lock();
        let fake = std::env::temp_dir().join("fake-home").join(".rustup");
        let fake = fake.to_string_lossy().into_owned();
        let saved = std::env::var_os("RUSTUP_HOME");
        crate::process_env::set_var("RUSTUP_HOME", &fake);
        let widened = dispatch_caveats_for_command("cargo --version", &base("/ws"));
        match saved.and_then(|v| v.into_string().ok()) {
            Some(v) => crate::process_env::set_var("RUSTUP_HOME", &v),
            None => crate::process_env::remove_var("RUSTUP_HOME"),
        }
        assert!(
            widened.permits_fs_read(&fake),
            "a build-tool dispatch must be able to read its toolchain home"
        );
    }

    /// A non-build-tool command is passed through unchanged — no toolchain
    /// roots leak into an ordinary `run_command` dispatch.
    #[test]
    fn a_non_build_tool_command_is_unchanged() {
        let base = base("/ws");
        let widened = dispatch_caveats_for_command("ls -la", &base);
        assert_eq!(widened.fs_read, base.fs_read);
    }

    /// #2596 round 3: a session with a host-scoped `net` grant (e.g.
    /// `[tui.permissions] net = ["api.example.com"]`) must not L3-BOUND-refuse
    /// an ordinary shell dispatch under agent-bridle 0.8 — the whole spawn
    /// used to fail closed because `Scope::Only(_)` is `Unknown` to every
    /// backend's admission check. The dispatch caveats narrow `net` to
    /// `none`, which the `DenyDirect` sandbox policy can bind on Linux.
    #[test]
    fn a_host_scoped_net_grant_is_narrowed_to_none_for_the_dispatch() {
        let mut caveats = base("/ws");
        caveats.net = crate::caveats::Scope::only(["api.example.com".to_string()]);
        let widened = dispatch_caveats_for_command("cargo --version", &caveats);
        assert_eq!(
            widened.net,
            crate::caveats::Scope::none(),
            "a host-scoped net grant cannot be bound by a spawn backend and \
             must be narrowed, not passed through as an Unknown scope"
        );
    }

    /// `dispatch_caveats_for_command` clones the session — the caller's
    /// original `Caveats` must never be mutated by the dispatch.
    #[test]
    fn dispatch_caveats_for_command_does_not_mutate_session() {
        let mut original = base("/ws");
        original.net = crate::caveats::Scope::only(["api.example.com".to_string()]);
        let original_net = original.net.clone();
        let _ = dispatch_caveats_for_command("cargo --version", &original);
        assert_eq!(
            original.net, original_net,
            "session caveats must not be mutated by dispatch"
        );
    }

    /// `Scope::All` (unrestricted) and `Scope::none()` (already bindable) must
    /// pass through the dispatch narrowing unchanged — narrowing only ever
    /// tightens a non-empty host list, never widens `All`.
    #[test]
    fn all_and_none_net_scopes_pass_through_the_dispatch_unchanged() {
        let mut all_caveats = base("/ws");
        all_caveats.net = crate::caveats::Scope::All;
        let widened = dispatch_caveats_for_command("cargo --version", &all_caveats);
        assert_eq!(widened.net, crate::caveats::Scope::All);

        let mut none_caveats = base("/ws");
        none_caveats.net = crate::caveats::Scope::none();
        let widened = dispatch_caveats_for_command("cargo --version", &none_caveats);
        assert_eq!(widened.net, crate::caveats::Scope::none());
    }
}

#[cfg(all(windows, feature = "test-util"))]
pub(crate) async fn test_windows_ambient_dispatch(
    executable: &std::path::Path,
    cmd: &str,
    cwd: &str,
    windows_cmd: bool,
    timeout: std::time::Duration,
) -> std::io::Result<serde_json::Value> {
    let route = select_shell_route(
        true,
        false,
        false,
        true,
        true,
        windows_cmd,
        crate::ambient_brush::runner_available(executable),
        crate::ShellEngine::SafeSubset,
    );
    let command = host_shell_command_at(route, false, cmd, cwd, executable)?;
    let run = supervise_windows_shell(
        command,
        (route == ShellRoute::AmbientBrush).then_some(cmd),
        None,
        timeout,
    )
    .await?;
    Ok(
        serde_json::json!({"exit_code":run.exit_code,"stdout":decode_shell_stream(&run.stdout),"stderr":decode_shell_stream(&run.stderr),"timed_out":run.timed_out}),
    )
}

#[cfg(test)]
mod ambient_runner_tests {
    use super::*;

    /// #2776/#2789: a core consumer must launch the adjacent dedicated runner,
    /// never re-execute its own (possibly server) binary as an interpreter.
    #[test]
    fn windows_2776_non_cli_consumer_selects_dedicated_runner() {
        let root = tempfile::tempdir().unwrap();
        let host = root.path().join("embedding-server.exe");
        let runner = root.path().join("tools").join(format!(
            "newt-ambient-brush{}",
            std::env::consts::EXE_SUFFIX
        ));
        std::fs::create_dir(runner.parent().unwrap()).unwrap();
        std::fs::write(&runner, b"fixture").unwrap();
        let command =
            host_shell_command_at(ShellRoute::AmbientBrush, false, "echo hello", ".", &host)
                .unwrap();
        assert_eq!(command.as_std().get_program(), runner.as_os_str());
        assert_eq!(command.as_std().get_args().count(), 0);
    }
}

#[cfg(test)]
mod missing_ambient_runner_tests {
    use super::*;
    /// #2789: missing carried runner restores cmd with matching dialect and
    /// one notice, without changing any of the authority route clamps.
    #[test]
    fn windows_2776_missing_runner_falls_back_with_one_notice() {
        let root = tempfile::tempdir().unwrap();
        let host = root.path().join("not-the-cli.exe");
        // A similarly named sibling outside tools/ is never a candidate.
        std::fs::write(
            root.path().join(format!(
                "newt-ambient-brush{}",
                std::env::consts::EXE_SUFFIX
            )),
            b"wrong directory",
        )
        .unwrap();
        let available = crate::ambient_brush::runner_available(&host);
        assert!(!available);
        let route = select_shell_route(
            true,
            false,
            false,
            true,
            true,
            false,
            available,
            crate::ShellEngine::SafeSubset,
        );
        assert_eq!(route, ShellRoute::Cmd);
        assert!(route.sentence().contains("cmd.exe /C"));
        let child = host_shell_command_at(route, false, "echo hello", ".", &host).unwrap();
        assert_eq!(child.as_std().get_program(), "cmd");
        let shown = std::sync::atomic::AtomicBool::new(false);
        assert_eq!(
            missing_runner_notice(route, true, &shown),
            None,
            "explicit opt-out is silent"
        );
        assert_eq!(
            missing_runner_notice(route, false, &shown),
            Some("carried brush not installed; using cmd")
        );
        assert_eq!(missing_runner_notice(route, false, &shown), None);
        for (bypass, broker, lease, floor) in [
            (false, false, false, true),
            (true, true, false, true),
            (true, false, true, true),
            (true, false, false, false),
        ] {
            let route = select_shell_route(
                bypass,
                broker,
                lease,
                floor,
                true,
                false,
                available,
                crate::ShellEngine::SafeSubset,
            );
            assert!(matches!(route, ShellRoute::Bridled(_)));
            assert_eq!(
                missing_runner_notice(route, false, &std::sync::atomic::AtomicBool::new(false)),
                None
            );
        }
    }
}