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
use super::super::NoMcp;
use super::*;
use crate::caveats::{Caveats, CountBound, Scope};

/// Serializes every test that reads or writes `NEWT_DISABLE_OCAP` (and
/// the venv vars the bypass forwards) with settings and denial journaling.
/// A separate mutex inverts the order when settings-owning loop fixtures
/// await it while an ocap fixture journals a denial under `process_env`.
/// Keep the async call surface, but share the one reentrant lock. Its guard
/// is thread-affine: hold it on the test's root future, never move it to a worker.
pub(crate) async fn env_lock() -> crate::process_env::EnvGuard {
    crate::process_env::lock()
}

/// The real fixture guard must be the settings/journal lock, not a second
/// mutex: otherwise a denial holding it can deadlock a verification fixture
/// that already owns GlobalSettingsGuard. Check ownership on this thread so
/// an unrelated sibling holding the global lock cannot make the test pass.
#[tokio::test]
async fn ocap_env_guard_shares_the_settings_and_denial_journal_lock() {
    let _env = env_lock().await;
    assert!(
        crate::process_env::held_by_current_thread(),
        "the ocap fixture must own the process environment lock"
    );
    let _settings = crate::test_guard::GlobalSettingsGuard::acquire();
    assert!(
        std::thread::spawn(|| crate::process_env::try_lock().is_none())
            .join()
            .unwrap()
    );
}

/// RAII env override: set/unset `key` for the test body, restore the
/// previous value on drop — including on a failed assertion, so yolo can
/// never leak into a neighboring test.
pub(crate) struct EnvVar {
    key: &'static str,
    saved: Option<String>,
}

impl EnvVar {
    pub(crate) fn set(key: &'static str, value: &str) -> Self {
        let saved = std::env::var(key).ok();
        std::env::set_var(key, value);
        Self { key, saved }
    }

    pub(crate) fn unset(key: &'static str) -> Self {
        let saved = std::env::var(key).ok();
        std::env::remove_var(key);
        Self { key, saved }
    }
}

impl Drop for EnvVar {
    fn drop(&mut self) {
        match self.saved.take() {
            Some(v) => std::env::set_var(self.key, v),
            None => std::env::remove_var(self.key),
        }
    }
}

/// #1600 regression: the confined (safe-subset / brush / host) shell env is an
/// ALLOWLIST — `ConfinedCommand::env_clear` + a narrow passthrough of NAMES
/// (default `HOME`/`USER`) + explicit `~/.newt/shell-env/` file imports — never
/// an ambient copy. A parent-only secret whose name is NOT allowlisted must
/// not reach the confined child's environment (`venv_env_map` is the seam that
/// builds it). Proves the "degraded/SafeSubset path" does not leak, closing
/// the deviation with executable coverage.
#[tokio::test]
async fn confined_shell_env_does_not_leak_a_parent_only_secret_1600() {
    let _lock = env_lock().await;
    // Narrow default passthrough (no operator widening).
    let _pt = EnvVar::unset("NEWT_SHELL_ENV_PASSTHROUGH");
    // A secret only in newt's OWN process env, with a non-allowlisted name.
    let _canary = EnvVar::set("NEWT_SAFESUBSET_ENV_CANARY_1600", "s3cr3t-parent-only-1600");
    let env = venv_env_map();
    assert!(
        !env.contains_key("NEWT_SAFESUBSET_ENV_CANARY_1600"),
        "the confined shell env leaked a parent-only secret NAME (#1600): {env:?}"
    );
    assert!(
        !env.values().any(|v| v.contains("s3cr3t-parent-only-1600")),
        "the confined shell env leaked a parent-only secret VALUE (#1600)"
    );
    // Sanity: the seam still builds a real env (the engine marker is set), so
    // the assertions above are not vacuously true against an empty map.
    assert_eq!(
        env.get("SHELL").map(String::as_str),
        Some(shell_engine().as_str())
    );
}

/// The default host-env seam preserves both a named timezone and explicit
/// empty TZ (UTC). An absent TZ must stay absent so libc uses the OS timezone.
#[tokio::test]
async fn confined_shell_env_preserves_parent_timezone() {
    let _lock = env_lock().await;
    let _pt = EnvVar::unset("NEWT_SHELL_ENV_PASSTHROUGH");
    let _config = EnvVar::set("NEWT_CONFIG_DIR", "/nonexistent-newt-timezone-test");
    for timezone in ["America/New_York", "UTC-14", ""] {
        let _tz = EnvVar::set("TZ", timezone);
        assert_eq!(venv_env_map().get("TZ").map(String::as_str), Some(timezone));
    }
    let _tz = EnvVar::unset("TZ");
    assert!(!venv_env_map().contains_key("TZ"));
}

#[tokio::test]
async fn confined_shell_env_timezone_respects_operator_allowlist() {
    let _lock = env_lock().await;
    let _pt = EnvVar::set("NEWT_SHELL_ENV_PASSTHROUGH", "HOME:USER");
    let _config = EnvVar::set("NEWT_CONFIG_DIR", "/nonexistent-newt-timezone-test");
    let _tz = EnvVar::set("TZ", "UTC-14");
    assert!(!venv_env_map().contains_key("TZ"));
}

/// Grounds the mocked timezone env-seam contract above with the real confined
/// safe-subset dispatch, a shell child, and its date grandchild. POSIX TZ avoids
/// depending on the separately tested OS timezone database read policy.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
#[ignore = "real confined child and grandchild; run serially in integration tier"]
async fn confined_shell_parent_timezone_reaches_child_and_grandchild() {
    let _lock = env_lock().await;
    let _pt = EnvVar::unset("NEWT_SHELL_ENV_PASSTHROUGH");
    let _config = EnvVar::set("NEWT_CONFIG_DIR", "/nonexistent-newt-timezone-test");
    let _engine = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let _venv = EnvVar::unset("NEWT_VENV");
    let _virtual = EnvVar::unset("VIRTUAL_ENV");
    let _paths = EnvVar::unset("NEWT_EXEC_PATHS");
    #[cfg(target_os = "macos")]
    let date_args = ["-r", "1705320000", "+%Y-%m-%dT%H:%M:%S%z"];
    #[cfg(not(target_os = "macos"))]
    let date_args = ["--date=@1705320000", "+%Y-%m-%dT%H:%M:%S%z"];
    let command = format!(
        "/bin/sh -c '/bin/date {}; status=$?; exit \"$status\"'",
        date_args.join(" ")
    );
    let workspace = tempfile::tempdir().expect("timezone fixture workspace");
    let cwd = workspace.path().to_str().unwrap();
    for timezone in ["UTC-14", ""] {
        let _tz = EnvVar::set("TZ", timezone);
        let expected = std::process::Command::new("/bin/date")
            .args(date_args)
            .env_clear()
            .env("TZ", timezone)
            .output()
            .expect("parent date");
        assert!(expected.status.success());
        let caveats = Caveats {
            fs_read: Scope::only([cwd.to_string()]),
            fs_write: Scope::none(),
            ..Caveats::top()
        };
        let result = super::shell::dispatch_bridled_shell(
            confined_dispatch_args(&command, cwd),
            &caveats,
            None,
        )
        .await
        .expect("confined dispatch");
        assert_eq!(result["exit_code"], 0, "confined date must execute");
        assert_eq!(
            result["stdout"].as_str(),
            Some(std::str::from_utf8(&expected.stdout).unwrap()),
            "parent and grandchild must agree for TZ={timezone:?}"
        );
    }
}

/// Workspace-fenced fs, NO exec, NO net — the shape under which the
/// confined shell denies (real build) or fails closed (stub build).
fn caveats_no_exec(ws: &std::path::Path) -> Caveats {
    Caveats {
        fs_read: Scope::only([ws.to_string_lossy().into_owned()]),
        fs_write: Scope::only([ws.to_string_lossy().into_owned()]),
        exec: Scope::none(),
        net: Scope::none(),
        max_calls: CountBound::Unlimited,
        valid_for_generation: Scope::All,
    }
}

async fn run_tool(
    name: &str,
    args: serde_json::Value,
    ws: &std::path::Path,
    caveats: &Caveats,
) -> String {
    run_tool_with_floor(name, args, ws, caveats, None).await
}

/// #307: like [`run_tool`] but with an explicit exec FLOOR (the active
/// named-permission-preset clamp). `Some(scope)` makes the `--disable-ocap`
/// bypass conditional on the floor permitting the command; `None` is the
/// pre-#307 behavior.
async fn run_tool_with_floor(
    name: &str,
    args: serde_json::Value,
    ws: &std::path::Path,
    caveats: &Caveats,
    exec_floor: Option<&Scope<String>>,
) -> String {
    execute_tool(
        name,
        &args,
        &ws.to_string_lossy(),
        false,
        20,
        caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        None,
        exec_floor,
        None, // git_tool
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
    )
    .await
}

/// The switch reads fail-closed: ONLY the exact value `1` (the value the
/// CLI exports and the issue documents) asserts the bypass. This is also
/// the env-var-equivalence half of the #297 test list — the flag and the
/// env var are one mechanism (`--disable-ocap` just exports the var).
#[test]
fn ocap_disabled_requires_exactly_1() {
    let _l = crate::process_env::lock();
    {
        let _unset = EnvVar::unset("NEWT_DISABLE_OCAP");
        assert!(!ocap_disabled(), "absent ⇒ confinement stays on");
    }
    for (value, expected) in [
        ("1", true),
        ("0", false),
        ("", false),
        ("true", false),
        ("yes", false),
        ("YOLO", false),
    ] {
        let _set = EnvVar::set("NEWT_DISABLE_OCAP", value);
        assert_eq!(
            ocap_disabled(),
            expected,
            "NEWT_DISABLE_OCAP={value:?} must read as {expected}"
        );
    }
}

/// Same fail-closed contract for the `--full-access` preset override:
/// ONLY the exact value `1` asserts it (the flag and the env var are one
/// mechanism — `--full-access` just exports the var).
#[test]
fn full_access_requested_requires_exactly_1() {
    let _l = crate::process_env::lock();
    {
        let _unset = EnvVar::unset("NEWT_FULL_ACCESS");
        assert!(!full_access_requested(), "absent ⇒ configured preset rules");
    }
    for (value, expected) in [
        ("1", true),
        ("0", false),
        ("", false),
        ("true", false),
        ("yes", false),
        ("FULL", false),
    ] {
        let _set = EnvVar::set("NEWT_FULL_ACCESS", value);
        assert_eq!(
            full_access_requested(),
            expected,
            "NEWT_FULL_ACCESS={value:?} must read as {expected}"
        );
    }
}

/// #1176 shadow-OCAP recording gate. The decision table, which
/// `exec_confined_command` consults before dispatch:
/// - host-bypass (yolo) → record (unconfined host shell);
/// - full-access on the confined path → record (caveats are top()) —
///   THE PARITY FIX: before it, a bare `--full-access` run armed the
///   recorder yet the confined dispatch never wrote;
/// - a genuinely confined session (neither) → do NOT record (real leash).
#[test]
fn shadow_records_iff_the_run_is_unconfined() {
    assert!(shadow_records(true, false), "yolo host bypass records");
    assert!(
        shadow_records(false, true),
        "--full-access confined dispatch records (the #1176 parity fix)"
    );
    assert!(shadow_records(true, true), "both routes still record");
    assert!(
        !shadow_records(false, false),
        "a genuinely confined session has a real leash — nothing to shadow"
    );
}

/// FLAG OFF ⇒ the command goes to the confined dispatch, which governs it.
/// Built against the agent-bridle env-seam branch (#783), the bridle ships
/// the REAL safe-subset shell (not the old fail-closed stub), so an
/// ungranted `echo` under `exec = none` is DENIED by the L3 boundary. This
/// is the "when the real shell returns" case the prior stub-build note
/// anticipated; the "unavailable in this build" stub error is retired.
#[tokio::test]
async fn flag_off_run_command_keeps_the_confined_dispatch_verbatim() {
    let _l = env_lock().await;
    let _off = EnvVar::unset("NEWT_DISABLE_OCAP");
    // #1243 Leg 1: pin safe-subset. This test proves the disable-ocap FLOOR
    // (engine-independent, runs before the engine); it must not depend on
    // the L3-gated default (`echo` is a TRUE bash builtin under brush — it
    // never spawns, so it isn't exec-gated, which is correct but would make
    // this floor assertion box-dependent).
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let out = run_tool(
        "run_command",
        serde_json::json!({"command": "echo hi"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(
        out.contains("capability denied"),
        "flag off ⇒ the confined dispatch must govern (deny) the command, got: {out}"
    );
}

/// FLAG ON: a command the confined shell fails closed on now runs on the
/// host shell and returns its real output through the SAME envelope
/// formatter (`shell_envelope_output`).
#[cfg(unix)]
#[tokio::test]
async fn yolo_runs_the_denied_command_on_the_host_shell() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let out = run_tool(
        "run_command",
        serde_json::json!({"command": "echo yolo-ok"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert_eq!(out, "yolo-ok\n");

    // No output ⇒ the same shape the bridle path produces. Since #1969 a
    // nonzero exit renders as a failure rather than a bare `(exit N)`, which
    // classified as a success.
    let out = run_tool(
        "run_command",
        serde_json::json!({"command": "exit 3"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert_eq!(out, "error: command exited 3");
}

/// #726/#945: a verbose `run_command` MUST NOT flood the model's context
/// window, but MUST still surface both ends of the output — a command's
/// summary/failure/exit status lives at the TAIL, and #726's original
/// head-only cap silently dropped exactly that (the gap #945 closed). Runs
/// through the real host shell (yolo path) so it exercises the actual
/// `shell_envelope_output` → cap composition. The global budget is the
/// default 10k in the test binary (nothing raises it above default), so
/// the assertions are upper-bounded and robust regardless of a smaller
/// racing value. This test goes through the legacy `execute_tool` path
/// (`run_tool`/`run_tool_with_floor` below), which has no spill store —
/// the no-spill-id elision marker branch, not the `spill:<id>` one.
#[cfg(unix)]
#[tokio::test]
async fn run_command_output_over_budget_is_token_capped() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    // ~350k chars of output — well over the default ~40k-char budget.
    let out = run_tool(
        "run_command",
        serde_json::json!({"command": "seq 1 60000"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(
        out.len() < 41_500,
        "model-facing output capped near the ~40k-char budget, got {} bytes",
        out.len()
    );
    assert!(
        out.contains("chars elided (head+tail shown"),
        "carries the head+tail elision marker: {:?}",
        &out[..out.len().min(400)]
    );
    // #945: the HEAD survives — the earliest lines are still visible.
    assert!(
        out.starts_with("1\n2\n3\n"),
        "head preserved: {:?}",
        &out[..out.len().min(160)]
    );
    // #945 (the regression this test now guards): the TAIL survives too —
    // under the old head-only cap this was the first assertion to break
    // (it asserted the OPPOSITE: `!out.contains("60000")`).
    assert!(
        out.trim_end().ends_with("60000"),
        "tail preserved, not dropped by the cap: {:?}",
        &out[out.len().saturating_sub(160)..]
    );
}

// --- #307 floor property: preset clamp WINS over --disable-ocap -------

/// Unit-cover every branch of the bypass-floor predicate.
#[test]
fn exec_floor_permits_covers_each_branch() {
    use crate::caveats::Scope;
    // No floor ⇒ always permit (bit-for-bit pre-#307).
    assert!(exec_floor_permits(None, "rm -rf /"));
    // Empty command ⇒ let it through to the normal path.
    let only_echo = Scope::only(["echo".to_string()]);
    assert!(exec_floor_permits(Some(&only_echo), ""));
    // In-floor simple command ⇒ permitted.
    assert!(exec_floor_permits(Some(&only_echo), "echo hi"));
    // Out-of-floor program ⇒ refused.
    assert!(!exec_floor_permits(Some(&only_echo), "rm hi"));
    // Compound command ⇒ refused even with an allow-listed leading token.
    assert!(!exec_floor_permits(Some(&only_echo), "echo hi && rm x"));
    assert!(!exec_floor_permits(Some(&only_echo), "echo a | tee b"));
    assert!(!exec_floor_permits(Some(&only_echo), "echo $(rm x)"));
    // `Scope::All` floor permits any simple command.
    let all: Scope<String> = Scope::All;
    assert!(exec_floor_permits(Some(&all), "anything goes"));
    assert!(!exec_floor_permits(Some(&all), "anything; sneaky"));
}

/// ADVERSARIAL PROBE (review #312): exhaustively attack `exec_floor_permits`
/// with EVERY shell injection / compound form so the floor is proven against
/// more than just `&&`. An `echo`-only floor must refuse to bypass for any
/// form that could chain or substitute a second program.
#[test]
fn exec_floor_refuses_every_metacharacter_form() {
    use crate::caveats::Scope;
    let echo = Scope::only(["echo".to_string()]);
    // Each of these begins with the allow-listed `echo` but smuggles or
    // could smuggle a second program. None may bypass.
    let attacks = [
        "echo ok && rm -rf /tmp/x", // && and
        "echo ok || rm -rf /tmp/x", // || or
        "echo ok ; rm -rf /tmp/x",  // ; sequence
        "echo ok | sh",             // | pipe
        "echo ok|sh",               // | no spaces
        "echo $(rm x)",             // $() command substitution
        "echo ${IFS}rm",            // ${} parameter expansion
        "echo `rm x`",              // backtick substitution
        "echo ok & rm x",           // & background
        "echo ok > /etc/passwd",    // > redirect out
        "echo ok >> /etc/passwd",   // >> append
        "echo < /etc/shadow",       // < redirect in
        "echo ok 2> err",           // 2> fd redirect (contains >)
        "(rm x)",                   // ( subshell
        "echo ok\nrm -rf /tmp/x",   // newline-separated
        "echo ok\nrm x\n",          // trailing newline
    ];
    for a in attacks {
        assert!(
            !exec_floor_permits(Some(&echo), a),
            "metacharacter form must NOT bypass the floor: {a:?}"
        );
    }
    // Forms with NO shell metacharacter that should still be refused because
    // the LEADING TOKEN is not the allow-listed program:
    let leading_token_attacks = [
        "rm -rf /tmp/x", // plain out-of-floor program
        "FOO=bar rm x",  // env-prefix: leading token `FOO=bar` ∉ floor
        "/bin/echo ok",  // path form: `/bin/echo` ≠ `echo` (exact match)
        "  rm x",        // leading whitespace, still `rm`
        "env rm x",      // `env` wrapper, leading token `env` ∉ floor
        "bash -c rm",    // `bash` ∉ floor
    ];
    for a in leading_token_attacks {
        assert!(
            !exec_floor_permits(Some(&echo), a),
            "out-of-floor leading token must be refused: {a:?}"
        );
    }
    // Sanity: a bare in-floor command with only a benign arg DOES bypass —
    // the floor is a ceiling, not a blanket off-switch. (A dangerous arg to
    // a permitted program is the user's accepted risk: they allow-listed it.)
    assert!(exec_floor_permits(Some(&echo), "echo hello world"));
    assert!(exec_floor_permits(Some(&echo), "echo -n trailing"));
}

/// FLOOR TEST (a) — the security contract: with `--disable-ocap` asserted,
/// an exec FLOOR that denies the command must STOP the unconfined bypass.
/// `echo` is outside a readonly floor (`exec = none`), so even with yolo on
/// it does NOT run on the host shell — it falls through to the confined
/// dispatch, which (env-seam real shell) DENIES it. A deliberately
/// restricted triage mode is NOT un-clamped by `--yolo`.
#[tokio::test]
async fn floor_blocks_disable_ocap_for_a_denied_exec() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    // #1243 Leg 1: pin safe-subset — this asserts the exec FLOOR blocks the
    // bypass (engine-independent); `echo` is a brush builtin, so the default
    // engine would run it unspawned and make the floor test box-dependent.
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    // A readonly-triage preset clamp: exec denies everything.
    let floor = crate::NamedPermissionPreset {
        readonly: true,
        ..Default::default()
    }
    .clamp();
    let out = run_tool_with_floor(
        "run_command",
        serde_json::json!({"command": "echo should-not-run"}),
        ws.path(),
        &caveats,
        Some(&floor.exec),
    )
    .await;
    // The bypass did NOT fire: the command never reached the host shell, so
    // it fell to the confined dispatch and was denied, not `should-not-run\n`.
    assert_ne!(out, "should-not-run\n", "the floor must block the bypass");
    assert!(
        out.contains("capability denied"),
        "fell to confined dispatch and was denied, got: {out}"
    );
}

/// FLOOR TEST (a, positive) — a command INSIDE the floor still takes the
/// fast unconfined path under `--disable-ocap`. The floor is a ceiling, not
/// a blanket off-switch: an explicitly allow-listed command runs.
#[cfg(unix)]
#[tokio::test]
async fn floor_allows_disable_ocap_for_an_in_floor_exec() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    // A triage preset that allow-lists `echo`.
    let floor = crate::NamedPermissionPreset {
        readonly: true,
        exec_allow: vec!["echo".to_string()],
        ..Default::default()
    }
    .clamp();
    let out = run_tool_with_floor(
        "run_command",
        serde_json::json!({"command": "echo in-floor-ok"}),
        ws.path(),
        &caveats,
        Some(&floor.exec),
    )
    .await;
    assert_eq!(out, "in-floor-ok\n", "in-floor command runs unconfined");
}

/// FLOOR conservatism — a COMPOUND command never bypasses under an active
/// floor, even if its leading token is allow-listed: `echo ok && rm -rf /`
/// must not smuggle `rm` past an `echo` grant. It falls to the confined
/// shell (env-seam real shell ⇒ denied), which gates each spawn.
#[tokio::test]
async fn floor_refuses_bypass_for_a_compound_command() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    // #1243 Leg 1: pin safe-subset so this confined-denial assertion is
    // deterministic — shell_engine() reads NEWT_SHELL_ENGINE FIRST, so the
    // test is immune to a NEWT_FULL_ACCESS leak from a concurrent test
    // (which on Windows would select brush, whose `echo` builtin runs
    // un-gated instead of the whole compound being atomically denied).
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    // `echo` is allow-listed, but the `&&` chains an unlisted `rm`.
    let floor = crate::NamedPermissionPreset {
        readonly: true,
        exec_allow: vec!["echo".to_string()],
        ..Default::default()
    }
    .clamp();
    let out = run_tool_with_floor(
        "run_command",
        serde_json::json!({"command": "echo ok && rm -rf /tmp/x"}),
        ws.path(),
        &caveats,
        Some(&floor.exec),
    )
    .await;
    assert_ne!(out, "ok\n", "a compound command must not bypass the floor");
    // Compound ⇒ never bypasses; it falls to the confined shell, which
    // (env-seam real shell) denies the ungranted command under `exec = none`.
    assert!(
        out.contains("capability denied"),
        "fell to confined dispatch and was denied, got: {out}"
    );
}

/// FLOOR TEST (c) — `None` floor is bit-for-bit the pre-#307 bypass: a
/// denied-by-caveats command still runs unconfined under `--disable-ocap`,
/// proving the floor is opt-in and the no-preset case is unchanged.
#[cfg(unix)]
#[tokio::test]
async fn no_floor_keeps_disable_ocap_bit_for_bit() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let out = run_tool_with_floor(
        "run_command",
        serde_json::json!({"command": "echo no-floor-ok"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert_eq!(out, "no-floor-ok\n", "no floor ⇒ bypass unchanged");
}

/// #2315: grounds the host 127 rule's mocked tests in the real host shell
/// (bash, else sh). A program the shell names as not found and that does not
/// resolve is `unavailable`; a bare `exit 127` names nothing and failed.
#[cfg(unix)]
#[tokio::test]
async fn host_shell_127_wording_grounds_the_named_missing_rule() {
    use crate::ExecOutcome;
    // Other shell fixtures mutate process-wide engine and authority settings.
    let _l = env_lock().await;
    let ws = tempfile::TempDir::new().unwrap();
    for (cmd, expected) in [
        (
            "newt-absent-binary-xyzzy-2315 --version",
            ExecOutcome::Unavailable,
        ),
        ("exit 127", ExecOutcome::Failed),
    ] {
        let envelope = super::shell::host_shell_dispatch(
            super::shell::ShellRoute::BashSh,
            cmd,
            &ws.path().to_string_lossy(),
            None,
            None,
            Default::default(),
        )
        .await
        .expect("host shell runs");
        assert_eq!(envelope["exit_code"], 127, "{envelope}");
        let (_, class) = super::shell::host_result(&envelope, |_| String::new());
        assert_eq!(class, expected, "{cmd}: {envelope}");
    }
}

/// Envelope parity (#297): the host-shell envelope is structurally
/// identical to the bridle one — `exit_code` / `stdout` / `stderr` /
/// `sandbox_kind`, `denied`/`denials` omitted (⇒ not denied) — so the
/// existing envelope readers apply unchanged.
#[cfg(unix)]
#[tokio::test]
async fn host_shell_envelope_matches_the_bridle_shape() {
    let _l = env_lock().await;
    let ws = tempfile::TempDir::new().unwrap();
    let envelope = super::shell::host_shell_dispatch(
        super::shell::ShellRoute::BashSh,
        "echo out; echo err >&2; exit 3",
        &ws.path().to_string_lossy(),
        None,
        None,
        Default::default(),
    )
    .await
    .expect("host shell runs");
    assert_eq!(envelope["exit_code"], 3);
    assert_eq!(envelope["stdout"], "out\n");
    assert_eq!(envelope["stderr"], "err\n");
    assert_eq!(envelope["sandbox_kind"], "none");
    // Omitted exactly as the bridle envelope omits them on the
    // nothing-was-denied path — `envelope_denied` reads it natively.
    assert!(envelope.get("denied").is_none(), "got: {envelope}");
    assert!(envelope.get("denials").is_none(), "got: {envelope}");
    assert!(!envelope_denied(&envelope));
    // And the shared formatter renders it like any confined result — which
    // since #1969 means a nonzero exit is marked as a failure ahead of its
    // output, so the ledger's `ok` bit stops reading a failing command as a
    // success. The streams themselves are untouched.
    assert_eq!(
        shell_envelope_output(&envelope, 20, false, false, None, None),
        "error: command exited 3\nout\nerr\n"
    );
}

#[test]
fn decode_shell_stream_preserves_valid_utf8() {
    let text = "// ── Model — test ──\n";
    assert_eq!(decode_shell_stream(text.as_bytes()), text);
}

#[test]
fn decode_shell_stream_repairs_bsd_cat_v_utf8_notation() {
    // This is what macOS/BSD `cat -v` emits for "─ —\n" in a UTF-8
    // locale: the leading e2 byte is raw, while continuation bytes are
    // rendered as M-^T/M-^@ etc. A lossy decode would display
    // "�M-^TM-^@ �M-^@M-^T".
    let cat_v = b"\xe2M-^TM-^@ \xe2M-^@M-^T\n";
    assert_eq!(decode_shell_stream(cat_v), "─ —\n");
}

#[test]
fn decode_shell_stream_repairs_two_byte_bsd_cat_v_notation() {
    // "é" is c3 a9; BSD `cat -v` leaves c3 raw and renders a9 as M-).
    let cat_v = b"caf\xc3M-)\n";
    assert_eq!(decode_shell_stream(cat_v), "café\n");
}

/// The venv/PATH prefix logic rides the HOST-BYPASS path unchanged: the
/// `export VIRTUAL_ENV=…; export PATH=…;` prefix is prepended to the
/// `--yolo` command, which runs on a real `/bin/sh` where `export` works.
/// (The confined path no longer gets the prefix — it uses the env seam;
/// see `confined_dispatch_uses_env_seam_not_export_prefix_783`.)
#[cfg(unix)]
#[tokio::test]
async fn yolo_keeps_the_venv_prefix_logic() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let _venv = EnvVar::set("NEWT_VENV", "/opt/fake-venv");
    let _virtual = EnvVar::unset("VIRTUAL_ENV");
    let _paths = EnvVar::unset("NEWT_EXEC_PATHS");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let out = run_tool(
        "run_command",
        serde_json::json!({"command": "echo \"$VIRTUAL_ENV\""}),
        ws.path(),
        &caveats,
    )
    .await;
    assert_eq!(out, "/opt/fake-venv\n");
}

/// In --yolo mode an unrestricted fs mutation prompt must not read EOF as
/// a human decline. The flag is already an explicit interactive override,
/// so final write/delete confirms auto-accept instead of auto-skipping.
#[tokio::test]
async fn yolo_auto_confirms_unrestricted_write_and_delete_prompts() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = Caveats::top();

    let out = run_tool(
        "write_file",
        serde_json::json!({"path": "auto.txt", "content": "ok\n"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(out.starts_with("wrote auto.txt"), "got: {out}");
    assert_eq!(
        std::fs::read_to_string(ws.path().join("auto.txt")).unwrap(),
        "ok\n"
    );

    let out = run_tool(
        "delete_file",
        serde_json::json!({"path": "auto.txt"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(out.starts_with("deleted auto.txt"), "got: {out}");
    assert!(
        !ws.path().join("auto.txt").exists(),
        "yolo-confirmed delete must remove the file"
    );
}

/// **The `--yolo` confirm's rendered bytes, pinned** (C0a, #1856).
///
/// A0's sweep found this form had no byte coverage at all: only the
/// alias-absence property and the fail-closed outcomes were tested, so
/// the string the operator reads was free to drift. C0a moves this
/// rendering from `Question::terminal_text` to `markup::plain::render`,
/// and changing an untested rendering path inside a byte-identity slice
/// is exactly the shape that slice must not have — so the gap closes
/// here rather than being inherited by D0.
#[test]
fn mutation_confirm_renders_its_frozen_form() {
    // D0 (#1878): built directly, no legacy `Question` in the middle. The
    // FROZEN BYTES below are unchanged, which is the whole point — this
    // test is what proves the migration moved the construction without
    // moving what the operator reads.
    let definition = mutation_confirm_definition("delete `auto.txt`?");
    assert_eq!(
        crate::markup::plain::render(&definition),
        "delete `auto.txt`?\n[y] to confirm\n[n] to skip"
    );
    // The hidden `Y`/`N` aliases parse but are never advertised
    // (BHV-PROMPT-005).
    let rendered = crate::markup::plain::render(&definition);
    assert!(!rendered.contains('Y'), "alias rendered: {rendered}");
    assert!(!rendered.contains('N'), "alias rendered: {rendered}");
}

/// Direct coverage of the fs-mutation confirm guard's parsing + fail-closed
/// contract, without the full `execute_tool` path. Proves defect 3 (uppercase
/// `Y` confirms again) and defect 2 (every non-answer outcome denies).
#[tokio::test]
async fn unrestricted_mutation_confirm_accepts_y_case_insensitively_and_fails_closed() {
    let _l = env_lock().await;
    let _off = EnvVar::unset("NEWT_DISABLE_OCAP");
    // fs_write = Scope::All → the guard actually prompts (does not bail true).
    let caveats = Caveats::top();

    struct ScriptGate(HumanQuestionOutcome);
    impl super::PermissionGate for ScriptGate {
        fn ask(&mut self, _r: &[super::PermissionRequest]) -> super::PermissionDecision {
            super::PermissionDecision::Deny
        }
        fn ask_question(&mut self, _q: &str) -> HumanQuestionOutcome {
            self.0.clone()
        }
    }

    fn confirm(caveats: &Caveats, outcome: Option<HumanQuestionOutcome>) -> bool {
        match outcome {
            Some(o) => {
                let mut gate = ScriptGate(o);
                let mut g: Option<&mut dyn super::PermissionGate> = Some(&mut gate);
                confirm_unrestricted_fs_mutation(caveats, &mut g, "overwrite ~/x?")
            }
            None => {
                let mut g: Option<&mut dyn super::PermissionGate> = None;
                confirm_unrestricted_fs_mutation(caveats, &mut g, "overwrite ~/x?")
            }
        }
    }

    // defect 3: lowercase and uppercase Y both confirm.
    assert!(confirm(
        &caveats,
        Some(HumanQuestionOutcome::Answer("y".into()))
    ));
    assert!(confirm(
        &caveats,
        Some(HumanQuestionOutcome::Answer("Y".into()))
    ));
    // any other answer denies (n, N, junk, empty).
    for a in ["n", "N", "maybe", ""] {
        assert!(
            !confirm(&caveats, Some(HumanQuestionOutcome::Answer(a.into()))),
            "answer {a:?} must not confirm the mutation"
        );
    }
    // defect 2: every non-answer outcome fails closed (mutation denied).
    for o in [
        HumanQuestionOutcome::Unavailable,
        HumanQuestionOutcome::Cancelled,
        HumanQuestionOutcome::ExitRequested,
        HumanQuestionOutcome::InputClosed,
        HumanQuestionOutcome::InputFailed,
    ] {
        assert!(
            !confirm(&caveats, Some(o.clone())),
            "outcome {o:?} must fail closed"
        );
    }
    // no gate at all → denied.
    assert!(!confirm(&caveats, None));
}

/// Non-yolo unrestricted fs mutations still ask, but through the
/// PermissionGate question seam. In the TUI that seam owns
/// PromptStdinGuard, so cbreak/VMIN=0 stdin cannot auto-answer "not y".
#[tokio::test]
async fn unrestricted_write_and_delete_confirm_through_permission_gate() {
    struct ConfirmGate {
        answer: Option<String>,
        questions: Vec<String>,
    }
    impl super::PermissionGate for ConfirmGate {
        fn ask(&mut self, _requests: &[super::PermissionRequest]) -> super::PermissionDecision {
            super::PermissionDecision::Deny
        }
        fn ask_question(&mut self, question: &str) -> HumanQuestionOutcome {
            self.questions.push(question.to_string());
            self.answer.clone().map_or(
                HumanQuestionOutcome::Unavailable,
                HumanQuestionOutcome::Answer,
            )
        }
    }

    let _l = env_lock().await;
    let _off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = Caveats::top();
    let mut gate = ConfirmGate {
        answer: Some("y".to_string()),
        questions: Vec::new(),
    };

    let out = execute_tool(
        "write_file",
        &serde_json::json!({"path": "guarded.txt", "content": "ok\n"}),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        Some(&mut gate),
        None,
        None, // git_tool
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
    )
    .await;
    assert!(out.starts_with("wrote guarded.txt"), "got: {out}");
    assert_eq!(
        std::fs::read_to_string(ws.path().join("guarded.txt")).unwrap(),
        "ok\n"
    );

    let out = execute_tool(
        "delete_file",
        &serde_json::json!({"path": "guarded.txt"}),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        Some(&mut gate),
        None,
        None, // git_tool
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
    )
    .await;
    assert!(out.starts_with("deleted guarded.txt"), "got: {out}");
    assert!(!ws.path().join("guarded.txt").exists());
    assert_eq!(
        gate.questions,
        vec![
            "Write this file? [y/N]\n[y] to confirm\n[n] to skip".to_string(),
            "Delete this file? [y/N]\n[y] to confirm\n[n] to skip".to_string(),
        ]
    );
}

/// #783 regression (Bug A): the confined-shell dispatch carries the RAW
/// user command and the venv via agent-bridle's structured `env` seam — NOT
/// an `export …;` prefix on `cmd`. The old code built
/// `{ "cmd": cmd_with_venv, "cwd": … }` (the prefixed form), and the
/// confined safe-subset engine refuses an `export` builtin on a compound
/// command, which is the bug. Pure: builds the dispatch args only, no spawn.
#[tokio::test]
async fn confined_dispatch_uses_env_seam_not_export_prefix_783() {
    let _l = env_lock().await;
    let _venv = EnvVar::set("NEWT_VENV", "/opt/fake-venv");
    let _virtual = EnvVar::unset("VIRTUAL_ENV");
    let _paths = EnvVar::unset("NEWT_EXEC_PATHS");

    // The literal failing case from #783.
    let cmd = "hostname; sw_vers 2>/dev/null | head -1; uname -s";
    let args = confined_dispatch_args(cmd, "/work/dir");

    // The command is passed RAW — no `export …;` prefix smuggled in.
    assert_eq!(args["cmd"], cmd);
    assert!(
        !args["cmd"]
            .as_str()
            .expect("cmd is a string")
            .contains("export "),
        "confined cmd must not carry an export prefix: {args}"
    );
    assert_eq!(args["cwd"], "/work/dir");

    // The venv rides the env seam: VIRTUAL_ENV + venv bin prepended to PATH.
    assert_eq!(args["env"]["VIRTUAL_ENV"], "/opt/fake-venv");
    let path = args["env"]["PATH"].as_str().expect("PATH in the env seam");
    assert!(
        path.starts_with("/opt/fake-venv/bin"),
        "venv bin must be prepended to PATH: {path}"
    );
}

/// #783: with neither venv input set, the env seam is empty (no spurious
/// VIRTUAL_ENV / PATH keys) — the no-venv invocation is unaffected.
#[tokio::test]
async fn confined_dispatch_env_seam_without_venv_783() {
    let _l = env_lock().await;
    let _venv = EnvVar::unset("NEWT_VENV");
    let _virtual = EnvVar::unset("VIRTUAL_ENV");
    let _paths = EnvVar::unset("NEWT_EXEC_PATHS");
    let _pass = EnvVar::unset("NEWT_SHELL_ENV_PASSTHROUGH"); // ⇒ default HOME+USER
    let _home = EnvVar::set("HOME", "/home/testuser");

    let args = confined_dispatch_args("ls -la", "/work/dir");
    assert_eq!(args["cmd"], "ls -la");
    let env = &args["env"];
    // #783: without a venv, no VIRTUAL_ENV / PATH override is injected...
    assert!(
        env.get("VIRTUAL_ENV").is_none(),
        "no venv ⇒ no VIRTUAL_ENV: {args}"
    );
    #[cfg(not(target_os = "macos"))]
    assert!(
        env.get("PATH").is_none(),
        "no venv/exec-paths ⇒ no PATH override: {args}"
    );
    #[cfg(target_os = "macos")]
    if let Some(developer) = crate::confined_exec::selected_developer_directory() {
        assert!(env["PATH"]
            .as_str()
            .unwrap()
            .starts_with(&format!("{developer}/usr/bin")));
    } else {
        assert!(env.get("PATH").is_none());
    }
    // ...but HOME now passes through so brush can expand `~` (the confined
    // shell had NO env before, so `~` stayed literal and left `~/…` debris),
    // and SHELL identifies the confined engine.
    assert_eq!(
        env["HOME"], "/home/testuser",
        "HOME must pass through: {args}"
    );
    assert!(
        env.get("SHELL").is_some(),
        "SHELL must identify the confined engine: {args}"
    );
}

/// fs fence under yolo (#297): the newt-native workspace fence is NOT
/// bypassed — a write/read outside the granted scope keeps the standard
/// denial bit-for-bit. Yolo is unconfined exec, never authority-off.
#[tokio::test]
async fn yolo_keeps_the_fs_workspace_fence() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let escape = "/definitely-outside-the-fence/escape.txt";
    // The denial names the WORKSPACE-JOINED path (#2629), not the model's raw
    // spelling. On Windows, joining this rooted-but-driveless literal onto an
    // absolute workspace keeps the workspace's own drive prefix (e.g.
    // `C:/definitely-outside-the-fence/escape.txt`) rather than replacing the
    // path outright, so the expected value must be computed with the SAME
    // join the production code performs — a hardcoded Unix-style literal
    // only matched by coincidence on platforms where join fully replaces an
    // absolute path (round 3 review item 2).
    #[allow(clippy::join_absolute_paths)] // intentional: mirrors production's own join exactly
    let escape_full = ws.path().join(escape).to_string_lossy().into_owned();
    let out = run_tool(
        "write_file",
        serde_json::json!({"path": escape, "content": "nope"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert_eq!(out, denied_fs_result("fs_write", &escape_full));
    assert!(!std::path::Path::new(&escape_full).exists());

    let out = run_tool(
        "delete_file",
        serde_json::json!({"path": escape}),
        ws.path(),
        &caveats,
    )
    .await;
    assert_eq!(out, denied_fs_result("fs_write", &escape_full));

    let outside_read = "/etc/hostname";
    #[allow(clippy::join_absolute_paths)] // intentional: mirrors production's own join exactly
    let outside_read_full = ws.path().join(outside_read).to_string_lossy().into_owned();
    let out = run_tool(
        "read_file",
        serde_json::json!({"path": outside_read}),
        ws.path(),
        &caveats,
    )
    .await;
    assert_eq!(out, denied_fs_result("fs_read", &outside_read_full));
}

/// Precedence (#297): with both `--disable-ocap` and a #263 gate present,
/// exec never prompts — nothing is denied, so the gate is structurally
/// unreachable for run_command. (fs prompting stays live; the fs-fence
/// test above and the #263 suite cover that axis.)
#[cfg(unix)]
#[tokio::test]
async fn yolo_never_consults_the_permission_gate_for_exec() {
    struct PanicGate;
    impl super::PermissionGate for PanicGate {
        fn ask(&mut self, requests: &[super::PermissionRequest]) -> super::PermissionDecision {
            panic!("yolo exec must never prompt, but the gate was asked: {requests:?}");
        }
        fn ask_question(&mut self, question: &str) -> HumanQuestionOutcome {
            panic!("yolo exec must never prompt, but the gate was asked: {question:?}");
        }
    }
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let mut gate = PanicGate;
    let out = execute_tool(
        "run_command",
        &serde_json::json!({"command": "echo no-prompt"}),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        Some(&mut gate),
        None,
        None, // git_tool
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
    )
    .await;
    assert_eq!(out, "no-prompt\n");
}

/// The corrective tool-name guard still answers BEFORE the bypass: yolo
/// changes where commands run, not what counts as a command.
#[tokio::test]
async fn yolo_keeps_the_tool_name_corrective_guard() {
    let _l = env_lock().await;
    let _on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let out = run_tool(
        "run_command",
        serde_json::json!({"command": "read_file foo.txt"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(out.contains("is a tool, not a shell command"), "got: {out}");
}

// --- facade P4 (#780): hidden tool-call routing dispatch ---------------

/// Even when a legacy Git collaborator is installed, native shell commands
/// must not dispatch through its narrower operation interface.
struct UnexpectedEmbeddedGit;
impl crate::agentic::GitTool for UnexpectedEmbeddedGit {
    fn dispatch(
        &self,
        op: &str,
        _args: &serde_json::Value,
        _caps: &crate::git_caveats::GitCaveats,
        _session: &Caveats,
    ) -> Result<String, String> {
        panic!("native command reached the embedded Git operation {op}");
    }
}

async fn run_command_with_legacy_git(
    command: &str,
    ws: &std::path::Path,
    caveats: &Caveats,
) -> String {
    execute_tool(
        "run_command",
        &serde_json::json!({ "command": command }),
        &ws.to_string_lossy(),
        false,
        20,
        caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        None, // permission_gate
        None, // exec_floor
        Some(&UnexpectedEmbeddedGit as &dyn crate::agentic::GitTool),
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
    )
    .await
}

#[cfg(target_os = "windows")]
async fn run_command_with_legacy_git_and_gate(
    command: &str,
    ws: &std::path::Path,
    caveats: &Caveats,
    permission_gate: &mut dyn super::PermissionGate,
) -> String {
    execute_tool(
        "run_command",
        &serde_json::json!({ "command": command }),
        &ws.to_string_lossy(),
        false,
        20,
        caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        Some(permission_gate),
        None, // exec_floor
        Some(&UnexpectedEmbeddedGit as &dyn crate::agentic::GitTool),
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
    )
    .await
}

/// The routing switch reads fail-closed (only the exact `1`), and it is a
/// DISTINCT mechanism from `ocap_disabled` (§7-F5): asserting `NEWT_NO_ROUTE`
/// never moves `ocap_disabled`, and asserting `NEWT_DISABLE_OCAP` never moves
/// `routing_disabled`. The two switches can never alias.
#[test]
fn routing_disabled_requires_exactly_1_and_is_independent_of_ocap() {
    let _l = crate::process_env::lock();
    let _no_ocap = EnvVar::unset("NEWT_DISABLE_OCAP");
    {
        let _unset = EnvVar::unset("NEWT_NO_ROUTE");
        assert!(!routing_disabled(), "absent ⇒ routing stays on");
    }
    for (value, expected) in [("1", true), ("0", false), ("", false), ("true", false)] {
        let _set = EnvVar::set("NEWT_NO_ROUTE", value);
        assert_eq!(routing_disabled(), expected, "NEWT_NO_ROUTE={value:?}");
        // F5: turning routing off NEVER turns on the L3-off unconfine.
        assert!(
            !ocap_disabled(),
            "NEWT_NO_ROUTE must not imply --disable-ocap"
        );
    }
    // And the inverse: --disable-ocap must not imply --no-route.
    let _unset_route = EnvVar::unset("NEWT_NO_ROUTE");
    let _on_ocap = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    assert!(ocap_disabled());
    assert!(
        !routing_disabled(),
        "--disable-ocap must not imply --no-route"
    );
}

/// F11 (verify-routing-f11b): the fix for the model that never calls
/// `lifecycle` and instead runs `run_command "cargo test …"`, which times
/// out under the 60s exec wall (2485-r5/r6 measured 6 headless replays never
/// reaching `lifecycle`, even after the fix landed). A recognised build
/// invocation now routes to the confined build lane's own
/// gate/`leq`-authority path — proven here by a gate that DENIES and records
/// the request, so the test stays in the fully-mocked unit tier (no real
/// `cargo` subprocess): the denial message alone proves the call reached the
/// build lane (not the 60s `run_command` exec path) and that it carries the
/// model's LITERAL argv, never a resolved phase command.
#[tokio::test]
async fn routed_cargo_test_reaches_the_confined_build_lane() {
    struct RecordingDenyGate {
        seen: Option<super::PermissionRequest>,
    }
    impl super::PermissionGate for RecordingDenyGate {
        fn ask(&mut self, requests: &[super::PermissionRequest]) -> super::PermissionDecision {
            self.seen = requests.first().cloned();
            super::PermissionDecision::Deny
        }
        fn ask_question(&mut self, _question: &str) -> HumanQuestionOutcome {
            HumanQuestionOutcome::Cancelled
        }
    }

    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let mut gate = RecordingDenyGate { seen: None };
    let out = execute_tool(
        "run_command",
        &serde_json::json!({ "command": "cargo test -p newt-core" }),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        Some(&mut gate),
        None,
        None, // git_tool
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
    )
    .await;

    assert!(
        out.contains("routed `cargo test -p newt-core` to the confined build lane")
            && out.contains("30 min limit")
            && out.contains("network denied"),
        "rendered result must say it ran in the build lane with its limit; got: {out}"
    );
    assert!(
        out.contains("capability denied") && out.contains("build authority"),
        "denied gate must refuse via the same build-authority path lifecycle action=build \
         uses, not silently run; got: {out}"
    );
    let reason = gate
        .seen
        .expect("the build-lane gate/leq path must be consulted")
        .reason;
    assert!(
        reason.contains("cargo test -p newt-core"),
        "the permission reason must show the model's LITERAL argv, not a resolved \
         phase command; got: {reason}"
    );
}

/// TDD: a routed read goes through the SAME fs floor — routing is NOT a
/// bypass. An out-of-scope `cat /etc/shadow` routes to `read_file` and is
/// denied by `fs_read` exactly as a direct `read_file` would be (the denial
/// short-circuits before any real fs access). The `fs_read` denial wording
/// also proves it reached the `read_file` arm (vs. the exec/shell path).
#[tokio::test]
async fn routed_cat_goes_through_the_fs_floor_not_a_bypass() {
    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    // #1243 Leg 1: pin safe-subset (deterministic confined engine) so a
    // concurrent NEWT_FULL_ACCESS leak can't flip this to brush on Windows.
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path()); // fs_read scoped to ws only
    let out = run_tool(
        "run_command",
        serde_json::json!({ "command": "cat /etc/shadow" }),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(
        out.contains("capability denied: fs_read does not permit") && out.contains("/etc/shadow"),
        "routed cat must hit the fs floor, not run unconfined; got: {out}"
    );
}

/// Grounds the routing table's native-Git decision with a real repository:
/// status observes an untracked file through the exec gate with scoped reads,
/// no write grant, and explicitly granted network/exec authority.
#[tokio::test]
async fn native_git_status_requires_exec_and_reads_the_actual_repository() {
    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let ws = tempfile::TempDir::new().unwrap();
    let init = {
        let mut cmd = crate::git_hardening::hardened_git(ws.path(), &["init", "-q"]).unwrap();
        // Windows CI: temp fixture owned by a different principal. Inject safe.directory
        // only for this test fixture, not in production hardened_git.
        #[cfg(windows)]
        if let Ok(canonical) = ws.path().canonicalize() {
            if let Some(dir) = canonical.to_str() {
                cmd.env("GIT_CONFIG_COUNT", "1")
                    .env("GIT_CONFIG_KEY_0", "safe.directory")
                    .env("GIT_CONFIG_VALUE_0", dir);
            }
        }
        cmd.output().unwrap()
    };
    assert!(init.status.success(), "{init:?}");
    std::fs::write(ws.path().join("native-only.txt"), "native evidence\n").unwrap();
    let mut caveats = caveats_no_exec(ws.path());
    caveats.fs_write = Scope::none();
    caveats.net = Scope::All;
    let denied = run_command_with_legacy_git("git status", ws.path(), &caveats).await;
    assert!(denied.contains("capability denied"), "{denied}");
    assert!(
        !denied.contains(super::native_git::WINDOWS_APPCONTAINER_GIT_UNAVAILABLE),
        "the ordinary exec denial must win before the Windows compatibility guard: {denied}"
    );
    caveats.exec = Scope::All;
    let out = run_command_with_legacy_git("git status", ws.path(), &caveats).await;
    #[cfg(target_os = "windows")]
    {
        assert!(
            out.contains(super::native_git::WINDOWS_APPCONTAINER_GIT_UNAVAILABLE),
            "restricted AppContainer must refuse before native Git runs: {out}"
        );
        assert!(!out.contains("routed:"), "{out}");
        assert!(!ws.path().join(".git/index").exists());
    }
    #[cfg(not(target_os = "windows"))]
    assert!(
        out.contains("native-only.txt"),
        "native Git must report the actual untracked file: {out}"
    );
    #[cfg(not(target_os = "windows"))]
    {
        assert!(!out.contains("routed:"), "{out}");
        assert!(!ws.path().join(".git/index").exists());
    }
}

/// The documented operator-controlled host route is intentionally distinct
/// from the restricted AppContainer path: it preserves ordinary native Git
/// behavior rather than silently widening a confined invocation.
#[cfg(target_os = "windows")]
#[tokio::test]
async fn windows_disable_ocap_keeps_native_git_available() {
    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_on = EnvVar::set("NEWT_DISABLE_OCAP", "1");
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let ws = tempfile::TempDir::new().unwrap();
    let init = crate::git_hardening::hardened_git(ws.path(), &["init", "-q"])
        .unwrap()
        .output()
        .unwrap();
    assert!(init.status.success(), "{init:?}");
    std::fs::write(ws.path().join("native-only.txt"), "host route evidence\n").unwrap();
    let out =
        run_command_with_legacy_git("git status", ws.path(), &caveats_no_exec(ws.path())).await;
    assert!(out.contains("native-only.txt"), "{out}");
    assert!(
        !out.contains(super::native_git::WINDOWS_APPCONTAINER_GIT_UNAVAILABLE),
        "the explicit host route must not take the AppContainer refusal: {out}"
    );
    assert!(!out.contains("routed:"), "{out}");
}

/// #1022: `run_command("rm file")` routes to the governed delete_file arm,
/// so deletion works under fs_write without requiring raw shell `rm`.
#[tokio::test]
async fn routed_rm_dispatches_through_delete_file() {
    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("stale.txt"), "remove me\n").unwrap();
    let caveats = caveats_no_exec(ws.path());
    let out = run_tool(
        "run_command",
        serde_json::json!({ "command": "rm stale.txt" }),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(out.starts_with("deleted stale.txt"), "got: {out}");
    assert!(
        !ws.path().join("stale.txt").exists(),
        "routed rm must remove the file through delete_file"
    );
}

/// The same exec boundary governs mutations: denial creates no index. On
/// Windows, restricted AppContainer reports the documented pre-spawn native
/// Git incompatibility; other platforms stage the real file.
#[tokio::test]
async fn state_modifying_git_add_is_not_routed() {
    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let ws = tempfile::TempDir::new().unwrap();
    let init = {
        let mut cmd = crate::git_hardening::hardened_git(ws.path(), &["init", "-q"]).unwrap();
        // Windows CI: temp fixture owned by a different principal. Inject safe.directory
        // only for this test fixture, not in production hardened_git.
        #[cfg(windows)]
        if let Ok(canonical) = ws.path().canonicalize() {
            if let Some(dir) = canonical.to_str() {
                cmd.env("GIT_CONFIG_COUNT", "1")
                    .env("GIT_CONFIG_KEY_0", "safe.directory")
                    .env("GIT_CONFIG_VALUE_0", dir);
            }
        }
        cmd.output().unwrap()
    };
    assert!(init.status.success(), "{init:?}");
    std::fs::write(ws.path().join("stage-me.txt"), "stage this file\n").unwrap();
    let mut caveats = caveats_no_exec(ws.path());
    caveats.net = Scope::All;
    let denied = run_command_with_legacy_git("git add stage-me.txt", ws.path(), &caveats).await;
    assert!(denied.contains("capability denied"), "{denied}");
    assert!(
        !denied.contains(super::native_git::WINDOWS_APPCONTAINER_GIT_UNAVAILABLE),
        "the ordinary exec denial must win before the Windows compatibility guard: {denied}"
    );
    assert!(!ws.path().join(".git/index").exists());
    caveats.exec = Scope::All;
    let out = run_command_with_legacy_git("git add stage-me.txt", ws.path(), &caveats).await;
    assert!(
        !out.contains("routed"),
        "git add must NOT route to the git built-in; got: {out}"
    );
    let staged = {
        let mut cmd =
            crate::git_hardening::hardened_git(ws.path(), &["diff", "--cached", "--name-only"])
                .unwrap();
        #[cfg(windows)]
        if let Ok(canonical) = ws.path().canonicalize() {
            if let Some(dir) = canonical.to_str() {
                cmd.env("GIT_CONFIG_COUNT", "1")
                    .env("GIT_CONFIG_KEY_0", "safe.directory")
                    .env("GIT_CONFIG_VALUE_0", dir);
            }
        }
        cmd.output().unwrap()
    };
    assert!(staged.status.success(), "{staged:?}; dispatch: {out}");
    #[cfg(target_os = "windows")]
    {
        assert!(
            out.contains(super::native_git::WINDOWS_APPCONTAINER_GIT_UNAVAILABLE),
            "restricted AppContainer must refuse before native Git runs: {out}"
        );
        assert!(!ws.path().join(".git/index").exists());
        assert_eq!(
            String::from_utf8(staged.stdout).unwrap().trim(),
            "",
            "the unavailable command must not stage the file: {out}"
        );
    }
    #[cfg(not(target_os = "windows"))]
    assert_eq!(
        String::from_utf8(staged.stdout).unwrap().trim(),
        "stage-me.txt",
        "native dispatch must actually stage the file: {out}"
    );
}

/// An interactive exec grant retries once with the freshly minted caveats. On
/// Windows that retry must still fail before native Git reaches AppContainer.
#[cfg(target_os = "windows")]
#[tokio::test]
async fn native_git_exec_grant_retry_is_refused_before_spawn() {
    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let ws = tempfile::TempDir::new().unwrap();
    let init = crate::git_hardening::hardened_git(ws.path(), &["init", "-q"])
        .unwrap()
        .output()
        .unwrap();
    assert!(init.status.success(), "{init:?}");
    std::fs::write(ws.path().join("retry-me.txt"), "retry evidence\n").unwrap();

    struct GrantExecGate {
        requests: Vec<super::PermissionRequest>,
        granted: Caveats,
    }
    impl super::PermissionGate for GrantExecGate {
        fn ask(&mut self, requests: &[super::PermissionRequest]) -> super::PermissionDecision {
            self.requests.extend_from_slice(requests);
            super::PermissionDecision::Allow(self.granted.clone())
        }
        fn ask_question(&mut self, _: &str) -> super::HumanQuestionOutcome {
            super::HumanQuestionOutcome::Unavailable
        }
    }

    let mut caveats = caveats_no_exec(ws.path());
    caveats.net = Scope::All;
    let mut granted = caveats.clone();
    granted.exec = Scope::All;
    let mut gate = GrantExecGate {
        requests: vec![],
        granted,
    };
    let out = run_command_with_legacy_git_and_gate(
        "git add retry-me.txt",
        ws.path(),
        &caveats,
        &mut gate,
    )
    .await;
    assert!(
        out.contains(super::native_git::WINDOWS_APPCONTAINER_GIT_UNAVAILABLE),
        "the post-grant retry must be refused before native Git runs: {out}"
    );
    assert_eq!(gate.requests.len(), 1, "{out}");
    assert_eq!(gate.requests[0].kind, super::DenialKind::Exec, "{out}");
    assert_eq!(gate.requests[0].target, "git", "{out}");
    assert!(
        !ws.path().join(".git/index").exists(),
        "the refused retry must not stage a file: {out}"
    );
}

/// F5 (§7-F5): `--no-route` bypasses routing but NEVER disables L3. With
/// `NEWT_NO_ROUTE=1`, the same out-of-bounds `cat` is no longer routed to
/// `read_file` (no `fs_read` denial), yet it does NOT run unconfined — it
/// falls to the confined shell (env-seam real shell ⇒ denied), and
/// `ocap_disabled()` stays false. The boundary holds.
#[tokio::test]
async fn no_route_bypasses_routing_but_keeps_l3() {
    let _l = env_lock().await;
    let _route_off = EnvVar::set("NEWT_NO_ROUTE", "1");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    // #1243 Leg 1: pin safe-subset (deterministic confined engine) so a
    // concurrent NEWT_FULL_ACCESS leak can't flip this to brush on Windows.
    let _eng = EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    assert!(routing_disabled() && !ocap_disabled(), "L2 off, L3 on");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_no_exec(ws.path());
    let out = run_tool(
        "run_command",
        serde_json::json!({ "command": "cat /etc/shadow" }),
        ws.path(),
        &caveats,
    )
    .await;
    // Routing was OFF ⇒ NOT rewritten to read_file (no fs_read denial)…
    assert!(
        !out.contains("fs_read does not permit"),
        "--no-route must not route to read_file; got: {out}"
    );
    // …and the command did NOT run unconfined: it took the confined shell
    // (env-seam real shell ⇒ denied — the L3 boundary held).
    assert!(
        out.contains("capability denied"),
        "the L3 confined dispatch must still gate the command; got: {out}"
    );
}

/// The confined brush child does not inherit newt's env (`do_not_inherit_env`;
/// the `env` seam is the only import), so the temp dir its tools use must be
/// handed over EXPLICITLY, matching the write fence's scratch root — else a
/// configured scratch/`TMPDIR` is granted while the child defaults to `/tmp`,
/// which the fence denies. `NEWT_CHILD_TMPDIR` is published by the headless
/// confined lane from the same value the fence was built from.
#[tokio::test]
async fn confined_shell_env_carries_the_fence_scratch_root_as_tmpdir() {
    let _lock = env_lock().await;
    let _pt = EnvVar::unset("NEWT_SHELL_ENV_PASSTHROUGH");
    let _config = EnvVar::set("NEWT_CONFIG_DIR", "/nonexistent-newt-tmpdir-test");
    // newt's own TMPDIR is never passed through by accident.
    let _parent = EnvVar::set("TMPDIR", "/parent-only-tmpdir");
    {
        let _child = EnvVar::unset("NEWT_CHILD_TMPDIR");
        assert!(
            !venv_env_map().contains_key("TMPDIR"),
            "no root published, none passed"
        );
    }
    let _child = EnvVar::set("NEWT_CHILD_TMPDIR", "/srv/scratch");
    assert_eq!(
        venv_env_map().get("TMPDIR").map(String::as_str),
        Some("/srv/scratch")
    );
}

/// #2533 round 2 (verify-routing-f11b item 1): the #2516 round-1 bug class
/// (a prepended routed note shifts an `error:`/failure prefix off the front
/// of the string, so the tool-result classifier reads a failure as success)
/// reappeared for the build route. RED before the fix: `run_confined_build_lane`
/// renders a failing command as `error: command exited N\n<output>`; the build
/// route PREPENDED `[routed …]` in front of that, so `tool_result_ok` saw the
/// note text first and returned `true` for a build that failed. Calling
/// `build_exec` directly (bypassing the `cargo`/`just` routing table, which
/// this test does not need) with a command that fails proves the ledgered
/// `ok` bit follows the exit code even through the routed note.
#[tokio::test]
async fn failed_routed_build_ledgers_not_ok() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = Caveats::top();

    let out = execute_tool(
        "build_exec",
        &serde_json::json!({ "argv": ["false"] }),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        None, // permission_gate
        None,
        None, // git_tool
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
    )
    .await;

    if crate::confined_exec::kernel_fs_fence_available() {
        assert!(
            !super::tool_result_ok(&out),
            "a routed build whose command failed must not read ok:true; got: {out}"
        );
        assert!(
            out.contains("routed `false` to the confined build lane"),
            "the routed note must still be present, appended after the failure \
             text, not prepended in front of it; got: {out}"
        );
    }

    // The passing case must still read ok:true — the fix must not flip both.
    let out_ok = execute_tool(
        "build_exec",
        &serde_json::json!({ "argv": ["true"] }),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;
    if crate::confined_exec::kernel_fs_fence_available() {
        assert!(
            super::tool_result_ok(&out_ok),
            "a routed build that PASSED must still read ok:true; got: {out_ok}"
        );
    }
}

/// #2533 round 2 (item 2): a quoted, `~`-relative, or globbed operand cannot
/// be routed faithfully — there is no shell downstream of the build lane to
/// expand it — so the classifier must gate the whole call to exec rather than
/// run a silently mangled argv. `cargo test -p newt-core` (no such token)
/// must still route.
#[test]
fn build_route_refuses_unsafe_argv_shapes() {
    use super::super::routing::{RouteDecision, RouteTable};
    let table = RouteTable::builtin();
    let cwd = std::path::Path::new("/never-matches-a-test-cwd");

    for cmd in [
        r#"cargo test "a b""#,
        "cargo test --manifest-path ~/x",
        "cargo build --bin *",
        r#"cargo test 'a b'"#,
        r"cargo test a\ b",
    ] {
        assert_eq!(
            table.classify(cmd, cwd, &crate::caveats::Scope::All),
            RouteDecision::Exec,
            "{cmd:?} carries a token the shell would transform; it must gate to exec"
        );
    }

    assert!(
        matches!(
            table.classify("cargo test -p newt-core", cwd, &crate::caveats::Scope::All),
            RouteDecision::Route {
                tool: "build_exec",
                ..
            }
        ),
        "a bare, unquoted argv must still route"
    );
}

/// #2533 round 2 (item 3): `just` itself searches the cwd AND every parent
/// directory for a justfile, so a workspace whose justfile sits one level up
/// must still route-and-run through the build lane's exec fallback — not
/// error — exactly as the shell path would have found it.
#[tokio::test]
async fn just_with_justfile_one_level_up_falls_back_to_exec_not_error() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let root = tempfile::TempDir::new().unwrap();
    std::fs::write(
        root.path().join("justfile"),
        "check:\n\techo up-one-level\n",
    )
    .unwrap();
    let sub = root.path().join("crates/foo");
    std::fs::create_dir_all(&sub).unwrap();
    let caveats = Caveats::top();

    let out = execute_tool(
        "build_exec",
        &serde_json::json!({ "argv": ["just", "check"] }),
        &sub.to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert!(
        !out.starts_with("error: no justfile"),
        "a justfile one level up must be found, not reported missing; got: {out}"
    );
}

/// PR-F28 review, Blocker 2 (red first, real dispatch, offload on): a routed
/// `timeout 2 …` wrapper must leave the build lane at THAT 2-second wall, not
/// the lane's own 30-minute one — round 1 threw the model's own bound away.
/// A scratch justfile recipe that sleeps 10s proves it: the call must die at
/// ~2s (`ExecOutcome::TimedOut`), and the note must name the 2-second wall
/// actually applied, never "30 min".
#[cfg(not(windows))]
#[tokio::test]
async fn a_routed_short_timeout_wrapper_honours_its_own_wall_not_the_lane_wall() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("justfile"), "slow:\n\tsleep 10\n").unwrap();
    let caveats = Caveats::top();

    let out = execute_tool_with_offload(
        "build_exec",
        &serde_json::json!({
            "argv": ["just", "slow"],
            "timeout_secs": 2,
        }),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None, // memory_source
        None, // permission_gate
        None, // exec_floor
        None, // git_tool
        None, // crew_runner
        None, // scratchpad_store
        None, // code_search
        None, // where_is
        None, // experience_store
        None, // step_ledger
        true, // tool_offload
        None, // spill_store
        None, // persona_tools
    )
    .await;

    // No elapsed-time assertion: had the 30 min lane wall applied, `sleep 10`
    // would have finished and the call would read ok:true, which the two
    // assertions below reject on content alone. The clock proved nothing the
    // outcome does not, and under load it failed on its own.
    if crate::confined_exec::kernel_fs_fence_available() {
        assert!(
            !super::tool_result_ok(&out),
            "a call killed by its own 2-second wall must not read ok:true; got: {out}"
        );
        assert!(
            out.contains("`timeout 2` honoured as this lane's wall (2s)"),
            "the note must name the 2-second wall actually applied, not the 30 min \
             lane wall; got: {out}"
        );
    }
}

/// A scratch crate whose `cargo check` genuinely FAILS: 20 distinct
/// undefined-identifier references, each its own compile error, so the
/// output comfortably exceeds any trim window this test uses. Offline, no
/// deps — `cargo check` never touches the network for a dependency-free
/// crate.
#[cfg(not(windows))]
fn write_failing_scratch_crate(dir: &std::path::Path) {
    std::fs::write(
        dir.join("Cargo.toml"),
        "[package]\nname = \"scratch\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
    )
    .unwrap();
    std::fs::create_dir_all(dir.join("src")).unwrap();
    let body: String = (1..=20)
        .map(|i| format!("    let _ = UNDEFINED_VAR_{i};\n"))
        .collect();
    std::fs::write(dir.join("src/main.rs"), format!("fn main() {{\n{body}}}\n")).unwrap();
}

/// A scratch crate whose `cargo check` genuinely PASSES but still emits
/// substantial output: 10 unused-variable warnings (compiles clean, exit 0
/// — a warning is not a failure), each its own diagnostic block.
#[cfg(not(windows))]
fn write_passing_scratch_crate(dir: &std::path::Path) {
    std::fs::write(
        dir.join("Cargo.toml"),
        "[package]\nname = \"scratch\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
    )
    .unwrap();
    std::fs::create_dir_all(dir.join("src")).unwrap();
    let body: String = (1..=10)
        .map(|i| format!("    let unused_var_{i} = {i};\n"))
        .collect();
    std::fs::write(dir.join("src/main.rs"), format!("fn main() {{\n{body}}}\n")).unwrap();
}

/// F23 / #2524 "tail-pipe-routes" (red first): the EXACT masking bug measured
/// in 2488-r9 — piping a build ONLY to cut output must never let `tail`'s own
/// (successful) exit code stand in for the build's. A FAILING build piped to
/// `tail` must still render as a failure, not `(exit 0)`.
///
/// Uses `cargo check`, not `just` — CI runners are not guaranteed to have
/// `just` on `PATH` (measured: PR #2549 CI failed both `just`-based
/// predecessors of these two tests with `exec "just" failed: No such file
/// or directory` on every runner). `cargo` is what CI always has; the
/// scratch-crate approach mirrors `routed_cargo_plus_stable_resolves_the_
/// toolchain_in_the_confined_lane` below. Verified with `just` absent from
/// `PATH` entirely (not merely unused), so neither test can secretly
/// depend on it.
// The build lane fail-closes on Windows: a network-denied build needs a kernel
// egress floor (Linux seccomp guard / macOS Seatbelt) that Windows lacks.
#[cfg(not(windows))]
#[tokio::test]
async fn a_failing_build_piped_to_tail_still_reports_the_real_failure() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let root = tempfile::TempDir::new().unwrap();
    write_failing_scratch_crate(root.path());
    let caveats = Caveats::top();

    let out = execute_tool(
        "run_command",
        &serde_json::json!({ "command": "cargo check 2>&1 | tail -10" }),
        &root.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert!(
        out.contains("error: command exited 1"),
        "the build's real failure must survive the pipe, never masked by \
         tail's own exit code: {out}"
    );
    assert!(
        out.contains("routed") && out.contains("confined build lane"),
        "the failing build must still have been ROUTED (not run in the \
         confined shell, where the pipe WOULD mask the exit code): {out}"
    );
    assert!(
        out.contains("output trimmed to the last 10 lines"),
        "must say the output was trimmed: {out}"
    );
    // Only the last 10 lines survive — rustc reports errors in source
    // order, so the LAST error (UNDEFINED_VAR_20) must survive the cut and
    // an early one (UNDEFINED_VAR_1) must not.
    assert!(out.contains("UNDEFINED_VAR_20"), "{out}");
    assert!(
        !out.contains("UNDEFINED_VAR_1`"),
        "only the last 10 lines should remain: {out}"
    );
}

/// A requested tail is a view of the captured build, not permission to discard
/// earlier diagnostics. Recover an omitted error through the normal spill API.
#[cfg(not(windows))]
#[tokio::test]
async fn a_trimmed_build_retains_full_diagnostics_for_retrieval() {
    use crate::agentic::content_spill::{SessionSpillStore, SpillCid, SpillStore};
    use crate::agentic::memory_fetch::{execute_memory_fetch, StoreMemorySource};

    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let root = tempfile::TempDir::new().unwrap();
    write_failing_scratch_crate(root.path());
    let spill = SessionSpillStore::new([19u8; 16]);
    let out = execute_tool_with_collaborators(
        "run_command",
        &serde_json::json!({"command": "cargo check 2>&1 | tail -10; echo \"EXIT: $?\""}),
        &root.path().to_string_lossy(),
        false,
        20,
        &Caveats::top(),
        &mut NoMcp,
        ToolCollaborators {
            spill_store: Some(&spill),
            ..Default::default()
        },
        true,
        PromptDisposition::Act,
        None,
    )
    .await
    .unwrap()
    .unwrap();

    assert!(out.contains("error: command exited 1"), "{out}");
    assert!(out.contains("output trimmed to the last 10 lines"), "{out}");
    assert!(out.contains("UNDEFINED_VAR_20"), "{out}");
    assert!(
        !out.contains("UNDEFINED_VAR_1`"),
        "tail must stay selected: {out}"
    );
    let handle = out
        .split("spill:")
        .nth(1)
        .and_then(|rest| rest.split('"').next())
        .expect("trimmed build must expose the existing full-output retrieval handle");
    let cid = SpillCid::parse(handle).unwrap();
    let full = spill
        .fetch(&cid)
        .expect("retained build output")
        .redacted_text;
    assert!(
        full.contains("UNDEFINED_VAR_1`"),
        "first error was lost: {full}"
    );
    assert!(
        full.contains("UNDEFINED_VAR_20"),
        "last error was lost: {full}"
    );

    let source = StoreMemorySource::from_stores(None, None).with_spill_store(&spill);
    let recovered = execute_memory_fetch(
        &serde_json::json!({"address": format!("spill:{handle}"), "grep": "UNDEFINED_VAR_1`"}),
        &source,
        false,
        20,
    );
    assert!(recovered.contains("UNDEFINED_VAR_1`"), "{recovered}");
}

/// F27 (r14a evidence): the twin hazard to the `| tail` case above — a
/// trailing `; echo "EXIT: $?"` used to keep the whole command compound
/// (SHELL_META), so it ran un-routed in the confined shell, where `$?`
/// after `cargo check; echo "EXIT: $?"` is ALWAYS the shell's own exit
/// code (0), never cargo's. Stripping the echo (routing.rs) lets the
/// command route to the build lane instead, which reports cargo's REAL
/// exit code — a failure must still render as a failure, never masked by
/// the echo's synthetic success.
#[cfg(not(windows))]
#[tokio::test]
async fn a_failing_build_with_a_trailing_exit_echo_still_reports_the_real_failure() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let root = tempfile::TempDir::new().unwrap();
    write_failing_scratch_crate(root.path());
    let caveats = Caveats::top();

    let out = execute_tool(
        "run_command",
        &serde_json::json!({ "command": "cargo check 2>&1; echo \"EXIT: $?\"" }),
        &root.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert!(
        out.contains("error: command exited 1"),
        "the build's real failure must survive, never masked by the shell's \
         own $? (always 0 after `cmd; echo …$?…`): {out}"
    );
    assert!(
        out.contains("routed") && out.contains("confined build lane"),
        "must have been ROUTED (not run in the confined shell, where the \
         trailing echo WOULD have kept it compound and masked the exit \
         code): {out}"
    );
    // #2554 round 2: the model asked for an `EXIT: N` line and will not
    // find one — the note must say the echo was dropped and that the
    // lane's own exit code (above) is the real one, so a model grepping
    // its own output for `EXIT` does not re-run the call believing it
    // never answered.
    assert!(
        out.contains("a trailing exit-code `echo` was dropped"),
        "the routed note must say the echo was dropped: {out}"
    );
}

/// The passing twin: a build that genuinely passes, piped to `head`, keeps
/// its `Passed` outcome and the first N lines. See the failing test's doc
/// comment for why `cargo`, not `just`.
// The build lane fail-closes on Windows: a network-denied build needs a kernel
// egress floor (Linux seccomp guard / macOS Seatbelt) that Windows lacks.
#[cfg(not(windows))]
#[tokio::test]
async fn a_passing_build_piped_to_head_keeps_the_pass_and_trims_to_the_first_lines() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let root = tempfile::TempDir::new().unwrap();
    write_passing_scratch_crate(root.path());
    let caveats = Caveats::top();

    let out = execute_tool(
        "run_command",
        &serde_json::json!({ "command": "cargo check 2>&1 | head -5" }),
        &root.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert!(
        !out.contains("error: command exited"),
        "a genuinely passing build (warnings only, exit 0) must not be \
         reported as failed: {out}"
    );
    assert!(
        out.contains("output trimmed to the first 5 lines"),
        "must say the output was trimmed: {out}"
    );
    // rustc emits warnings in source order — the first (unused_var_1) must
    // survive the cut, the last (unused_var_10) must not.
    assert!(out.contains("unused_var_1`"), "{out}");
    assert!(
        !out.contains("unused_var_10"),
        "only the first 5 lines should remain: {out}"
    );
}

/// #2524 follow-up (F23 evidence): 2488-r9's own build-verifying command
/// carried `+stable`. Confirms EMPIRICALLY, not just by code inspection,
/// that rustup resolves it inside the confined build lane —
/// `build_tool_request` forwards `RUSTUP_HOME`/`CARGO_HOME` from the
/// OPERATOR's real environment (never the confined child's redirected
/// `HOME`), so a routed `cargo +stable check` must behave exactly as it
/// would from an ordinary shell, never report the toolchain missing.
// The build lane fail-closes on Windows: a network-denied build needs a kernel
// egress floor (Linux seccomp guard / macOS Seatbelt) that Windows lacks.
#[cfg(not(windows))]
#[tokio::test]
async fn routed_cargo_plus_stable_resolves_the_toolchain_in_the_confined_lane() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let root = tempfile::TempDir::new().unwrap();
    std::fs::write(
        root.path().join("Cargo.toml"),
        "[package]\nname = \"scratch\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
    )
    .unwrap();
    std::fs::create_dir_all(root.path().join("src")).unwrap();
    std::fs::write(root.path().join("src/main.rs"), "fn main() {}\n").unwrap();
    let caveats = Caveats::top();

    let out = execute_tool(
        "run_command",
        &serde_json::json!({ "command": "cargo +stable check 2>&1 | tail -20" }),
        &root.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert!(
        out.contains("routed `cargo +stable check`") && out.contains("confined build lane"),
        "must have been routed with the toolchain selector kept in the argv: {out}"
    );
    assert!(
        !out.contains("toolchain") || !out.contains("is not installed"),
        "rustup must resolve +stable inside the confined lane's forwarded \
         RUSTUP_HOME/CARGO_HOME, not report it missing: {out}"
    );
    assert!(
        !out.contains("error: command exited"),
        "cargo +stable check on a trivial offline crate must actually \
         succeed in this environment: {out}"
    );
}

/// F24/PR1 (r10-r12 evidence, red first): almost every `run_command` began
/// with `cd <dir> && …` — the session's OWN workspace root, or a real
/// subdirectory (see `a_cd_prefixed_subdirectory_routes_and_says_so` below)
/// — which made every command compound and never routed at all. A routed
/// `cd <root> && cargo check` must run through the SAME build lane as a
/// bare `cargo check`; the workspace root resolves to `cwd="."`, so PR1's
/// routed-note clause (which names the folded directory) stays empty for
/// this case — nothing to say beyond the routed note itself.
// `write_passing_scratch_crate` (a real build-lane dispatch) is
// `#[cfg(not(windows))]`; see its own doc for why.
#[cfg(not(windows))]
#[tokio::test]
async fn a_noop_cd_to_the_workspace_root_still_routes_and_says_so() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let root = tempfile::TempDir::new().unwrap();
    write_passing_scratch_crate(root.path());
    let caveats = Caveats::top();
    let root_str = root.path().to_string_lossy();

    let out = execute_tool(
        "run_command",
        &serde_json::json!({ "command": format!("cd {root_str} && cargo check") }),
        &root_str,
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert!(
        out.contains("routed `cargo check`") && out.contains("confined build lane"),
        "the cd-prefixed call must still route, with the cd stripped from \
         the displayed argv: {out}"
    );
    assert!(
        !out.contains("cwd="),
        "the workspace root resolves to cwd=\".\" — nothing to name: {out}"
    );
    assert!(
        !out.contains("error: command exited"),
        "a genuinely passing build must not be reported as failed: {out}"
    );
}

/// PR1 (red first): a `cd <subdir> && cargo check` — not just the
/// workspace root — now routes too, and the routed note names WHICH
/// directory it actually ran in.
// `write_passing_scratch_crate` (a real build-lane dispatch) is
// `#[cfg(not(windows))]`; see its own doc for why.
#[cfg(not(windows))]
#[tokio::test]
async fn a_cd_prefixed_subdirectory_routes_and_says_so() {
    let _l = env_lock().await;
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let root = tempfile::TempDir::new().unwrap();
    let sub = root.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    write_passing_scratch_crate(&sub);
    let caveats = Caveats::top();
    let root_str = root.path().to_string_lossy();

    let out = execute_tool(
        "run_command",
        &serde_json::json!({ "command": "cd sub && cargo check" }),
        &root_str,
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert!(
        out.contains("routed `cargo check`") && out.contains("confined build lane"),
        "the cd-prefixed subdirectory call must route too: {out}"
    );
    assert!(
        out.contains("cwd=sub"),
        "the routed note must name the folded directory: {out}"
    );
    assert!(
        !out.contains("error: command exited"),
        "a genuinely passing build must not be reported as failed: {out}"
    );
}

// ---------------------------------------------------------------------------
// F38 — lifecycle run of a build-tool command routes to the build lane
// ---------------------------------------------------------------------------

/// F38 (a): `lifecycle {"phase":"check"}` (no action, defaults to run) when
/// the resolved command starts with a build tool (cargo) must route to the
/// build lane and request Build authority — not fail in the run lane.
#[cfg(not(windows))]
#[tokio::test]
async fn lifecycle_run_of_build_tool_requests_build_authority() {
    struct RecordingDenyGate {
        seen: Option<super::PermissionRequest>,
    }
    impl super::PermissionGate for RecordingDenyGate {
        fn ask(&mut self, requests: &[super::PermissionRequest]) -> super::PermissionDecision {
            self.seen = requests.first().cloned();
            super::PermissionDecision::Deny
        }
        fn ask_question(&mut self, _question: &str) -> HumanQuestionOutcome {
            HumanQuestionOutcome::Cancelled
        }
    }

    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let ws = tempfile::TempDir::new().unwrap();
    // Cargo.toml triggers the `rust` pack: check = "cargo fmt -- --check && cargo test"
    std::fs::write(
        ws.path().join("Cargo.toml"),
        "[package]\nname = \"dummy\"\n",
    )
    .unwrap();
    let caveats = caveats_no_exec(ws.path());
    let mut gate = RecordingDenyGate { seen: None };
    let out = execute_tool(
        "lifecycle",
        &serde_json::json!({"phase": "check"}),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        Some(&mut gate),
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    let request = gate
        .seen
        .expect("lifecycle run of a build-tool command must consult the build-authority gate");
    assert_eq!(
        request.kind,
        super::DenialKind::Build,
        "must request Build authority, not exec/fs; got: {:?}",
        request.kind
    );
    assert!(
        out.contains("build authority") || out.contains("capability denied"),
        "result must name build authority, not 'just isn't available'; got: {out}"
    );
    assert!(
        !out.contains("isn't available") && !out.contains("Unavailable"),
        "must not fail in the run lane; got: {out}"
    );
}

/// F38 (c): `lifecycle {"phase":"check"}` when the resolved command is NOT a
/// build tool (e.g. pytest) must NOT route to the build lane — it stays on
/// the run-lane path with escalation.
#[cfg(not(windows))]
#[tokio::test]
async fn lifecycle_run_of_non_build_tool_does_not_request_build_authority() {
    struct RecordingDenyGate {
        seen: Option<super::PermissionRequest>,
    }
    impl super::PermissionGate for RecordingDenyGate {
        fn ask(&mut self, requests: &[super::PermissionRequest]) -> super::PermissionDecision {
            self.seen = requests.first().cloned();
            super::PermissionDecision::Deny
        }
        fn ask_question(&mut self, _question: &str) -> HumanQuestionOutcome {
            HumanQuestionOutcome::Cancelled
        }
    }

    let _l = env_lock().await;
    let _route_on = EnvVar::unset("NEWT_NO_ROUTE");
    let _ocap_off = EnvVar::unset("NEWT_DISABLE_OCAP");
    let ws = tempfile::TempDir::new().unwrap();
    // pyproject.toml triggers the `python` pack: check = "pytest -x"
    std::fs::write(
        ws.path().join("pyproject.toml"),
        "[project]\nname = \"dummy\"\n",
    )
    .unwrap();
    let caveats = caveats_no_exec(ws.path());
    let mut gate = RecordingDenyGate { seen: None };
    let _out = execute_tool(
        "lifecycle",
        &serde_json::json!({"phase": "check"}),
        &ws.path().to_string_lossy(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        Some(&mut gate),
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    let has_build_request = gate
        .seen
        .as_ref()
        .is_some_and(|r| r.kind == super::DenialKind::Build);
    assert!(
        !has_build_request,
        "a non-build-tool lifecycle run must NOT route to the build lane; \
         gate saw: {:?}",
        gate.seen
    );
}

/// Grounds `confined_exec::developer_exec_twins` against a REAL confined
/// `python3` under a restricted exec grant. A live ornith-1.5-35b refactor run
/// had `python3` granted by name, yet the shell resolved the `/usr/bin` xcrun
/// shim (Seatbelt denied the Xcode binary its PATH put first), and the shim
/// failed with `You can set the path to the Xcode folder using
/// /usr/bin/xcode-select -switch`. Library tests run the safe-subset engine
/// (see `bridle_registry`), so this covers the exec fence, not brush's lookup.
#[cfg(target_os = "macos")]
#[tokio::test]
#[serial_test::serial]
async fn confined_python3_runs_on_macos() {
    let _l = env_lock().await;
    let _ocap = EnvVar::unset("NEWT_DISABLE_OCAP");
    let _full = EnvVar::unset("NEWT_FULL_ACCESS");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = Caveats {
        exec: Scope::only(["python3".to_string()]),
        // Exercise the executable fence; macOS cannot admit restricted networking.
        net: Scope::All,
        ..caveats_no_exec(ws.path())
    };
    let out = run_tool(
        "run_command",
        serde_json::json!({"command": "python3 -c 'print(40 + 2)'"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(out.contains("42"), "{out}");
}

/// Grounds `git_hardening::sandbox_git_env` against a REAL confined `git`. A
/// live ornith-1.5-35b run's `git status` died with `unable to access
/// '~/.gitconfig': Operation not permitted`, because git read the operator's
/// global config and the fence refused it.
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial]
async fn confined_git_ignores_ambient_config_and_carries_the_agent_identity() {
    let _l = env_lock().await;
    let _ocap = EnvVar::unset("NEWT_DISABLE_OCAP");
    let _full = EnvVar::unset("NEWT_FULL_ACCESS");
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = Caveats {
        exec: Scope::only(["git".to_string()]),
        // Exercise Git identity/config isolation without an unsupported net floor.
        #[cfg(target_os = "macos")]
        net: Scope::All,
        ..caveats_no_exec(ws.path())
    };
    let out = run_tool(
        "run_command",
        serde_json::json!({"command": "git init -q && git status --short && git config user.email"}),
        ws.path(),
        &caveats,
    )
    .await;
    assert!(!out.contains("unable to access"), "{out}");
    let identity = crate::AgentIdentity::resolve().unwrap_or_default();
    assert!(out.contains(&identity.email), "{out}");
}

/// #2796: host Bash and fallback sh discover tools even with no external which.
#[cfg(unix)]
#[tokio::test]
async fn which_2796_ambient_host_routes() {
    let _guard = env_lock().await;
    use super::shell::{host_shell_command, ShellRoute};
    let root = tempfile::tempdir().unwrap();
    for fallback in [false, true] {
        let mut command = host_shell_command(
            ShellRoute::BashSh,
            fallback,
            "PATH=; which printf && ! which missing_2796",
            root.path().to_str().unwrap(),
        )
        .unwrap();
        let out = command.output().await.unwrap();
        assert!(out.status.success(), "{out:?}");
        assert_eq!(out.stdout, b"printf\n");
    }
}