dpc-tau-ext-shell 0.2.0

A minimal Unix-first coding agent.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
//! Tests for process lifecycle behavior.

use super::*;

#[test]
fn shell_hidden_read_write_mode_is_unrestricted_by_default() {
    // With directory locking disabled, shell calls run read-write and publish
    // no access-mode chip.
    let td = TempDir::new().expect("tempdir");
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("printf ok > probe".to_owned()),
        ),
        (
            CborValue::Text("cwd".to_owned()),
            CborValue::Text(td.path().to_string_lossy().into_owned()),
        ),
    ]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(output.display.mode, "");
    assert_eq!(
        fs::read_to_string(td.path().join("probe")).expect("probe"),
        "ok"
    );
}

/// Ensures model shell calls and user `!` / `!!` children receive the same
/// protected pager overlay after hostile ordinary configuration, without
/// replacing the configured TERM value.
#[test]
fn model_and_user_shells_share_protected_pager_environment() {
    let shell_config: crate::config::ShellConfig = serde_json::from_value(serde_json::json!({
        "extra_env": {
            "PAGER": "hostile-pager",
            "GIT_PAGER": "hostile-git-pager",
            "GH_PAGER": "hostile-gh-pager",
            "JJ_PAGER": "hostile-jj-pager",
            "SYSTEMD_PAGER": "hostile-systemd-pager",
            "TERM": "tau-test-term"
        }
    }))
    .expect("parse shell config");
    let command = "printf '%s|%s|%s|%s|%s|%s' \"$PAGER\" \"$GIT_PAGER\" \"$GH_PAGER\" \
         \"$JJ_PAGER\" \"$SYSTEMD_PAGER\" \"$TERM\"";
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text(command.to_owned()),
    )]);

    let CommandOutcome::Finished(model_output) = run_command_live(
        &args,
        &shell_config,
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run model shell environment probe") else {
        panic!("expected finished model shell outcome");
    };
    assert_eq!(
        cbor_map_text(&model_output.result, "output"),
        Some("out(no_nl) cat|cat|cat|cat|cat|tau-test-term")
    );

    let (tx, rx) = path_std_sync::mpsc::channel();
    let user_command = tau_proto::UiShellCommand {
        session_id: "s1"
            .parse::<tau_proto::SessionId>()
            .expect("known-safe SessionId must be valid"),
        command_id: tau_proto::ShellCommandId::parse("ui-sh-pager-env")
            .expect("test identifier must satisfy its grammar"),
        command: command.to_owned(),
        include_in_context: true,
        target_agent_id: None,
    };
    let output = Output::channel(tx);
    let (_cancel_tx, cancel_rx) = path_std_sync::mpsc::channel();
    path_crate_tools::shell::dispatch_user_shell_command(
        user_command,
        shell_config,
        &output,
        cancel_rx,
        std::env::current_dir().expect("current dir"),
    );
    let finished = rx
        .try_iter()
        .find_map(|message| match message {
            HarnessInputMessage::Emit(emit) => match *emit.event {
                Event::ShellCommandFinishedReported(event) => Some(event),
                _ => None,
            },
            _ => None,
        })
        .expect("user shell finished event");
    assert_eq!(finished.output, "cat|cat|cat|cat|cat|tau-test-term");
    assert_eq!(finished.exit_code, Some(0));
}

/// Ensures the user-shell spawn boundary retains an admission-time non-UTF-8
/// cwd as an OS path instead of round-tripping it through lossy display text.
#[cfg(unix)]
#[test]
fn user_shell_preserves_non_utf8_operational_cwd() {
    use std::ffi::OsString;
    use std::os::unix::ffi::OsStringExt as _;

    let root = TempDir::new().expect("tempdir");
    let cwd = root
        .path()
        .join(OsString::from_vec(b"non-utf8-\xff".to_vec()));
    fs::create_dir(&cwd).expect("create non-UTF-8 cwd");
    fs::write(cwd.join("sentinel"), b"present").expect("write sentinel");

    let (tx, rx) = path_std_sync::mpsc::channel();
    let command = tau_proto::UiShellCommand {
        session_id: "s1"
            .parse::<tau_proto::SessionId>()
            .expect("known-safe SessionId must be valid"),
        command_id: tau_proto::ShellCommandId::parse("ui-sh-non-utf8-cwd")
            .expect("test identifier must satisfy its grammar"),
        command: "test -f ./sentinel".to_owned(),
        include_in_context: true,
        target_agent_id: None,
    };
    let output = Output::channel(tx);
    let (_cancel_tx, cancel_rx) = path_std_sync::mpsc::channel();

    path_crate_tools::shell::dispatch_user_shell_command(
        command,
        path_crate_config::ShellConfig::default(),
        &output,
        cancel_rx,
        cwd,
    );

    let finished = rx
        .try_iter()
        .find_map(|message| match message {
            HarnessInputMessage::Emit(emit) => match *emit.event {
                Event::ShellCommandFinishedReported(event) => Some(event),
                _ => None,
            },
            _ => None,
        })
        .expect("user shell finished event");
    assert_eq!(finished.output, "");
    assert_eq!(finished.exit_code, Some(0));
    assert!(!finished.cancelled);
}

#[test]
fn shell_tool_replaces_invalid_utf8_stderr_and_marks_output_invalid() {
    // Regression coverage for agent-facing shell output collection: stderr
    // must be decoded lossily too, with a warning that does not erase the
    // original stderr text.
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text("printf '\\376stderr' >&2".to_owned()),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(
        cbor_map_text(&output.result, "output"),
        Some("err(invalid-utf8,no_nl) �stderr")
    );
    assert_eq!(cbor_bool_field(&output.result, "valid_utf8"), Some(false));
}

#[test]
fn shell_tool_replaces_invalid_utf8_both_streams_in_combined_output() {
    // Regression coverage for commands that write invalid bytes to both
    // streams: the agent should see both decoded streams and one concise
    // warning.
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text("printf '\\377stdout'; printf '\\376stderr' >&2".to_owned()),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(
        cbor_map_text(&output.result, "output"),
        Some("out(invalid-utf8,no_nl) �stdout\nerr(invalid-utf8,no_nl) �stderr")
    );
    assert_eq!(cbor_bool_field(&output.result, "valid_utf8"), Some(false));
}

#[cfg(target_os = "linux")]
#[test]
fn read_only_mount_setattr_flags_are_recursive() {
    // Enforced read-only mode clones the cwd tree recursively, so the final
    // mount_setattr call must also apply recursively; otherwise nested mounts
    // could remain writable under a supposedly read-only cwd subtree.
    let flags = crate::isolation::read_only_mount_setattr_flags();
    assert_ne!(flags & (libc::AT_EMPTY_PATH as libc::c_uint), 0);
    assert_ne!(flags & (libc::AT_RECURSIVE as libc::c_uint), 0);
}

#[cfg(target_os = "linux")]
#[test]
fn shell_tool_enforced_read_only_mode_bind_mounts_cwd_read_only() {
    // Regression coverage for enforced inferred read-only shell mode: lock
    // elision is not enough. When `enforce_ro_bind` is true, the child must get
    // a read-only bind mount over its cwd so accidental writes fail before
    // they can alter the working tree.
    let dir = TempDir::new().expect("temp dir");
    fs::write(dir.path().join("input.txt"), "ok").expect("write fixture");
    let args = CborValue::Map(vec![
        (
            CborValue::Text("cwd".to_owned()),
            CborValue::Text(dir.path().display().to_string()),
        ),
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("cat input.txt; touch created.txt".to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(5.into()),
        ),
    ]);

    let mut world = path_crate_tools_world::ShellWorld::real();
    let output = match path_crate_tools::shell::run_command_cancellable(
        "enforced_ro_test",
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::visible(
            path_crate_tools_shell::ShellAccessMode::ReadOnly,
        ),
        true,
        None,
        &mut world,
    ) {
        Ok(path_crate_tools_shell::CommandOutcome::Finished(output)) => *output,
        Ok(path_crate_tools_shell::CommandOutcome::Cancelled) => panic!("unexpected cancellation"),
        Err(error) if error.message.contains("Operation not permitted") => return,
        Err(error) => panic!("unexpected shell start error: {error:?}"),
    };

    assert_ne!(cbor_int_field(&output.result, "status"), Some(0));
    assert!(
        !dir.path().join("created.txt").exists(),
        "read-only shell command must not create files in cwd"
    );
    let combined = cbor_map_text(&output.result, "output").expect("output");
    assert!(
        combined.contains(" ok"),
        "read should still work: {combined}"
    );
    assert!(
        combined.contains("Read-only file system") || combined.contains("Permission denied"),
        "write should fail due to mount permissions: {combined}"
    );
}

/// A normal shell exit emits its classification and round-trips through the
/// shared process-outcome consumer without inferring from the status code.
#[test]
fn command_details_value_round_trips_explicit_normal_exit() {
    let details = command_details_value(CommandDetails {
        status: Some(0),
        signal: None,
        timed_out: false,
        duration_seconds: None,
        termination_reason: "exit",
        total_lines: None,
        total_bytes: None,
        output: "out hi\nerr oops".to_owned(),
        truncated: false,
        valid_utf8: true,
        saved_output: None,
    });
    assert_eq!(cbor_map_text(&details, "output"), Some("out hi\nerr oops"));
    assert!(cbor_map_field(&details, "total_lines").is_none());
    assert!(cbor_map_field(&details, "total_bytes").is_none());
    assert!(cbor_map_field(&details, "valid_utf8").is_none());
    assert!(cbor_map_field(&details, "timed_out").is_none());
    assert_eq!(cbor_map_text(&details, "termination_reason"), Some("exit"));
    assert!(cbor_map_field(&details, "truncated").is_none());
    assert!(cbor_map_field(&details, "duration_seconds").is_none());

    let outcome = tau_proto::ShellProcessOutcome::from_result(&details)
        .expect("explicit normal exit must project");
    assert!(outcome.success());
    assert_eq!(
        outcome.termination_reason(),
        tau_proto::ShellTerminationReason::Exit
    );
    assert_eq!(outcome.exit_code(), Some(0));
}

#[test]
fn command_details_value_records_slow_command_exec_time() {
    let details = command_details_value(CommandDetails {
        status: Some(0),
        signal: None,
        timed_out: false,
        duration_seconds: Some(6),
        termination_reason: "exit",
        total_lines: None,
        total_bytes: None,
        output: String::new(),
        truncated: false,
        valid_utf8: true,
        saved_output: None,
    });

    assert_eq!(cbor_int_field(&details, "duration_seconds"), Some(6));
}

/// Ensures closed stdin presents persistent poll-visible readiness rather than
/// leaving event-driven consumers waiting for input forever.
#[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))]
#[test]
fn shell_tool_closed_stdin_provides_poll_visible_readiness() {
    let helper = std::env::current_exe()
        .expect("current test executable")
        .to_string_lossy()
        .replace('\'', "'\"'\"'");
    let command = format!(
        "'{helper}' --ignored --exact tests::process_lifecycle::shell_tool_poll_stdin_helper \
         >/dev/null 2>&1 && printf 'after poll\\n'"
    );
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text(command),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(2.into()),
        ),
    ]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run stdin hangup probe") else {
        panic!("expected finished shell outcome");
    };

    assert_eq!(cbor_int_field(&output.result, "status"), Some(0));
    assert_eq!(
        cbor_map_text(&output.result, "output"),
        Some("out after poll")
    );
    assert!(cbor_bool_field(&output.result, "timed_out").is_none());
}

/// Ensures both model shell dialects enforce command-regex rules before spawn
/// and disclose each typed command/workdir pair in the agent-facing error.
#[test]
fn model_shell_surfaces_enforce_allowlist_before_spawn() {
    let workdir = TempDir::new().expect("workdir");
    let sentinel = workdir.path().join("must-not-exist");
    let (mut reader, mut writer) = spawn_extension();
    drain_startup(&mut reader);
    send_shell_regex_allowlist_config(
        &mut writer,
        vec![(
            workdir.path().to_str().expect("UTF-8 workdir"),
            r"printf allowed",
            Some("Use the permitted printf form."),
        )],
    );
    let Event::ExtPromptFragmentPublish(_) = reader
        .read_event()
        .expect("read configured prompt fragment")
        .expect("configured prompt fragment")
    else {
        panic!("expected configured prompt fragment publication");
    };

    for (call_id, tool_name, directory_field) in [
        ("deny-generic", SHELL_TOOL_NAME, "cwd"),
        ("deny-chatgpt", GPT_SHELL_TOOL_NAME, "workdir"),
    ] {
        writer
            .write_event(&Event::ToolStarted(ToolStarted {
                invocation_policy: tau_proto::ToolInvocationPolicy::default(),
                call_id: call_id.into(),
                tool_name: tau_proto::ToolName::new(tool_name),
                arguments: cbor_map(vec![
                    (
                        "command",
                        CborValue::Text(format!("touch {}", sentinel.display())),
                    ),
                    (
                        directory_field,
                        CborValue::Text(workdir.path().display().to_string()),
                    ),
                ]),
                agent_id: tau_proto::AgentId::parse("allowlist-agent").expect("agent id"),
                originator: tau_proto::PromptOriginator::User,
            }))
            .expect("invoke denied shell");
        writer.flush().expect("flush denied shell");

        let Event::ToolError(error) = reader.read_event().expect("read").expect("error") else {
            panic!("expected tool error");
        };
        assert!(error.message.contains("denied by configured allowlist"));
        assert!(error.message.contains(r#"command_regex: "printf allowed""#));
        assert!(
            error
                .message
                .contains(r#"description: "Use the permitted printf form.""#)
        );
        assert!(error.message.contains("workdir:"));
        assert!(
            !error.message.contains(&sentinel.display().to_string()),
            "generated model denial must not echo the denied command"
        );
        assert!(!sentinel.exists(), "denied command must not spawn");
    }
}

/// Ensures both `!` and `!!` execution semantics use the same command-regex
/// allowlist and report one terminal denial without spawning a child.
#[test]
fn user_shell_context_modes_enforce_the_same_allowlist() {
    let workdir = TempDir::new().expect("workdir");
    let agent_id = tau_proto::AgentId::parse("allowlist-user-agent").expect("agent id");
    let sentinel = workdir.path().join("must-not-exist");
    let (mut reader, mut writer) = spawn_extension();
    drain_startup(&mut reader);
    send_shell_regex_allowlist_config(
        &mut writer,
        vec![(
            workdir.path().to_str().expect("UTF-8 workdir"),
            r"printf allowed",
            Some("Use the permitted printf form."),
        )],
    );
    writer
        .write_event(&Event::AgentMetadataSet(tau_proto::AgentMetadataSet {
            agent_id: agent_id.clone(),
            key: tau_proto::AgentMetadataKey::new("ext_test-extension_cwd"),
            value: CborValue::Text(workdir.path().display().to_string()),
            mutation_id: None,
            inheritable: true,
        }))
        .expect("seed workdir");
    writer.flush().expect("flush seed");

    for (command_id, include_in_context) in [("deny-bang", true), ("deny-double-bang", false)] {
        writer
            .write_event(&Event::UiShellCommand(tau_proto::UiShellCommand {
                session_id: "session-1".parse().expect("session id"),
                command_id: test_shell_command_id(command_id),
                command: format!("touch {}", sentinel.display()),
                include_in_context,
                target_agent_id: Some(agent_id.clone()),
            }))
            .expect("send user shell");
        writer.flush().expect("flush user shell");
        let finished = wait_for_user_shell_finished(&mut reader, command_id);
        assert_eq!(finished.include_in_context, include_in_context);
        assert!(finished.output.contains("denied by configured allowlist"));
        assert!(
            finished
                .output
                .contains(r#"command_regex: "printf allowed""#)
        );
        assert!(
            finished
                .output
                .contains(r#"description: "Use the permitted printf form.""#)
        );
        assert!(
            !finished.output.contains(&sentinel.display().to_string()),
            "generated user-shell denial must not echo the denied command"
        );
        assert_eq!(finished.exit_code, None);
        assert!(!sentinel.exists(), "denied user command must not spawn");
    }
}

/// Ensures denial happens before RecordIfMissing can create an empty cassette
/// and before ReplayOnly can report missing or malformed VCR state.
#[test]
fn shell_allowlist_denial_never_opens_vcr_state() {
    let workdir = TempDir::new().expect("workdir");
    let config: path_crate_config::ShellConfig = serde_json::from_value(serde_json::json!({
        "allowlist": [{
            "workdir": workdir.path().display().to_string(),
            "command_regex": "printf allowed"
        }]
    }))
    .expect("config");
    let invoke = || {
        let mut invoke = match tool_started(
            "deny-before-vcr",
            SHELL_TOOL_NAME,
            cbor_map(vec![
                ("command", CborValue::Text("printf denied".to_owned())),
                ("cwd", CborValue::Text(workdir.path().display().to_string())),
            ]),
            "vcr-policy-agent",
        ) {
            Event::ToolStarted(invoke) => invoke,
            _ => unreachable!("helper always returns ToolStarted"),
        };
        invoke.tool_name = tau_proto::ToolName::new(SHELL_TOOL_NAME);
        invoke
    };

    let record_dir = TempDir::new().expect("record dir");
    let error = world_after_shell_authorization(
        &mut invoke(),
        &config,
        Some(tau_vcr::VcrConfig::new(
            tau_vcr::VcrMode::RecordIfMissing,
            record_dir.path(),
        )),
        workdir.path().to_path_buf(),
    )
    .err()
    .expect("policy denial precedes recording");
    assert!(error.message.contains("denied by configured allowlist"));
    assert!(
        std::fs::read_dir(record_dir.path())
            .expect("read record dir")
            .next()
            .is_none(),
        "denial must not create a cassette"
    );

    let invalid_record_dir = TempDir::new().expect("invalid record dir");
    let mut invalid = match tool_started(
        "invalid-before-vcr",
        GPT_SHELL_TOOL_NAME,
        cbor_map(vec![
            ("command", CborValue::Text("printf allowed".to_owned())),
            (
                "workdir",
                CborValue::Text(workdir.path().display().to_string()),
            ),
            ("cwd", CborValue::Text(workdir.path().display().to_string())),
        ]),
        "vcr-policy-agent",
    ) {
        Event::ToolStarted(invoke) => invoke,
        _ => unreachable!("helper always returns ToolStarted"),
    };
    let error = world_after_shell_authorization(
        &mut invalid,
        &config,
        Some(tau_vcr::VcrConfig::new(
            tau_vcr::VcrMode::RecordIfMissing,
            invalid_record_dir.path(),
        )),
        workdir.path().to_path_buf(),
    )
    .err()
    .expect("surface validation precedes recording");
    assert!(error.message.contains("`cwd` is not supported"));
    assert!(
        std::fs::read_dir(invalid_record_dir.path())
            .expect("read invalid record dir")
            .next()
            .is_none(),
        "invalid invocation must not create a cassette"
    );

    for malformed in [false, true] {
        let replay_dir = TempDir::new().expect("replay dir");
        if malformed {
            std::fs::write(
                replay_dir.path().join("deny-before-vcr.yaml"),
                "not: [valid",
            )
            .expect("write malformed cassette");
        }
        let error = world_after_shell_authorization(
            &mut invoke(),
            &config,
            Some(tau_vcr::VcrConfig::new(
                tau_vcr::VcrMode::ReplayOnly,
                replay_dir.path(),
            )),
            workdir.path().to_path_buf(),
        )
        .err()
        .expect("policy denial precedes replay state");
        assert!(error.message.contains("denied by configured allowlist"));
        assert!(!error.message.contains("vcr"));
    }
}
/// Ensures the default overlay bypasses a deterministic hostile pager, while
/// the explicit opt-out exposes that pager and lets the normal timeout bound
/// it.
#[cfg(unix)]
#[test]
fn protected_pager_overlay_prevents_stall_and_opt_out_forfeits_guarantee() {
    use std::os::unix::fs::PermissionsExt as _;

    let tempdir = TempDir::new().expect("tempdir");
    let pager = tempdir.path().join("hostile-pager");
    fs::copy(
        concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/fixtures/hostile-pager.sh"
        ),
        &pager,
    )
    .expect("copy hostile pager fixture");
    fs::set_permissions(&pager, fs::Permissions::from_mode(0o700))
        .expect("make hostile pager executable");
    let pager = pager.to_string_lossy();
    let command = "printf 'pager payload\\n' | \"$PAGER\"";
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text(command.to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(1.into()),
        ),
    ]);
    let protected: crate::config::ShellConfig = serde_json::from_value(serde_json::json!({
        "extra_env": { "PAGER": pager.as_ref() }
    }))
    .expect("parse protected config");

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &protected,
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run protected pager probe") else {
        panic!("expected finished protected shell outcome");
    };
    assert_eq!(cbor_int_field(&output.result, "status"), Some(0));
    assert_eq!(
        cbor_map_text(&output.result, "output"),
        Some("out pager payload")
    );
    assert!(cbor_bool_field(&output.result, "timed_out").is_none());

    let unprotected: crate::config::ShellConfig = serde_json::from_value(serde_json::json!({
        "non_interactive_pager": false,
        "extra_env": { "PAGER": pager.as_ref() }
    }))
    .expect("parse opt-out config");
    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &unprotected,
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run opt-out pager probe") else {
        panic!("expected finished opt-out shell outcome");
    };
    assert_eq!(cbor_bool_field(&output.result, "timed_out"), Some(true));
    assert_eq!(
        cbor_map_text(&output.result, "termination_reason"),
        Some("timeout")
    );
}

#[test]
fn shell_tool_reports_progress_and_success() {
    let (mut reader, mut writer) = spawn_extension();
    drain_startup(&mut reader);

    writer
        .write_event(&Event::ToolStarted(ToolStarted {
            invocation_policy: tau_proto::ToolInvocationPolicy::default(),
            call_id: "call-1".into(),
            tool_name: tau_proto::ToolName::new(SHELL_TOOL_NAME),
            arguments: CborValue::Map(vec![(
                CborValue::Text("command".to_owned()),
                CborValue::Text("printf hello".to_owned()),
            )]),
            agent_id: tau_proto::AgentId::parse("agent-1").expect("agent id"),
            originator: tau_proto::PromptOriginator::User,
        }))
        .expect("invoke");
    writer.flush().expect("flush");

    let progress = reader.read_event().expect("read").expect("progress");
    let Event::ToolProgressReported(progress) = progress else {
        panic!("expected tool progress");
    };
    assert_eq!(progress.display.expect("display").mode, "");

    let result = reader.read_event().expect("read").expect("result");
    let Event::ToolResult(result) = result else {
        panic!("expected tool result");
    };
    assert_eq!(result.tool_name, SHELL_TOOL_NAME);
    assert_eq!(result.display.as_ref().expect("display").mode, "");
    assert_eq!(
        optional_argument_text(&result.result, "output"),
        Ok(Some("out(no_nl) hello".to_owned()))
    );

    writer
        .write_frame(&disconnect_frame(None))
        .expect("disconnect");
    writer.flush().expect("flush");
}

#[test]
fn gpt_shell_tool_reports_progress_and_success() {
    let (mut reader, mut writer) = spawn_extension();
    drain_startup(&mut reader);

    writer
        .write_event(&Event::ToolStarted(ToolStarted {
            invocation_policy: tau_proto::ToolInvocationPolicy::default(),
            call_id: "call-gpt-shell".into(),
            tool_name: tau_proto::ToolName::new(GPT_SHELL_TOOL_NAME),
            arguments: CborValue::Map(vec![(
                CborValue::Text("command".to_owned()),
                CborValue::Text("printf hello".to_owned()),
            )]),
            agent_id: tau_proto::AgentId::parse("agent-1").expect("agent id"),
            originator: tau_proto::PromptOriginator::User,
        }))
        .expect("invoke");
    writer.flush().expect("flush");

    let progress = reader.read_event().expect("read").expect("progress");
    let Event::ToolProgressReported(progress) = progress else {
        panic!("expected tool progress");
    };
    assert_eq!(progress.tool_name, GPT_SHELL_TOOL_NAME);
    assert_eq!(progress.display.expect("display").mode, "");

    let result = reader.read_event().expect("read").expect("result");
    let Event::ToolResult(result) = result else {
        panic!("expected tool result");
    };
    assert_eq!(result.tool_name, GPT_SHELL_TOOL_NAME);
    assert_eq!(result.display.as_ref().expect("display").mode, "");
    assert_eq!(
        optional_argument_text(&result.result, "output"),
        Ok(Some("out(no_nl) hello".to_owned()))
    );

    writer
        .write_frame(&disconnect_frame(None))
        .expect("disconnect");
    writer.flush().expect("flush");
}

#[test]
fn command_isolation_preserves_explicit_environment() {
    let mut cmd = path_std_process::Command::new("sh");
    cmd.arg("-c")
        .arg("printf %s \"${TAU_EXPLICIT_ENV_TEST-unset}\"")
        .env("TAU_EXPLICIT_ENV_TEST", "ok")
        .stdout(path_std_process::Stdio::piped())
        .stderr(path_std_process::Stdio::piped());
    crate::isolation::apply_command_isolation(&mut cmd);
    let output = cmd.output().expect("run env probe");
    assert!(output.status.success(), "env probe failed: {output:?}");
    assert_eq!(String::from_utf8(output.stdout).expect("utf8 stdout"), "ok");
}

#[test]
fn command_isolation_clears_cargo_build_environment() {
    let cargo_env_vars = [
        "CARGO",
        "CARGO_BIN_NAME",
        "CARGO_CRATE_NAME",
        "CARGO_MANIFEST_DIR",
        "CARGO_MANIFEST_LINKS",
        "CARGO_MANIFEST_PATH",
        "CARGO_PKG_AUTHORS",
        "CARGO_PKG_DESCRIPTION",
        "CARGO_PKG_HOMEPAGE",
        "CARGO_PKG_LICENSE",
        "CARGO_PKG_LICENSE_FILE",
        "CARGO_PKG_NAME",
        "CARGO_PKG_README",
        "CARGO_PKG_REPOSITORY",
        "CARGO_PKG_RUST_VERSION",
        "CARGO_PKG_VERSION",
        "CARGO_PKG_VERSION_MAJOR",
        "CARGO_PKG_VERSION_MINOR",
        "CARGO_PKG_VERSION_PATCH",
        "CARGO_PKG_VERSION_PRE",
        "CARGO_PRIMARY_PACKAGE",
        "OUT_DIR",
    ];
    let script = cargo_env_vars
        .iter()
        .map(|env_var| format!("printf '%s=%s\\n' {env_var} \"${{{env_var}-unset}}\""))
        .collect::<Vec<_>>()
        .join("; ");
    let expected = cargo_env_vars
        .iter()
        .map(|env_var| format!("{env_var}=unset\n"))
        .collect::<String>();

    let mut cmd = path_std_process::Command::new("sh");
    cmd.arg("-c")
        .arg(script)
        .stdout(path_std_process::Stdio::piped())
        .stderr(path_std_process::Stdio::piped());
    for env_var in cargo_env_vars {
        cmd.env(env_var, "should-not-leak");
    }
    crate::isolation::apply_command_isolation(&mut cmd);
    let output = cmd.output().expect("run env probe");
    assert!(output.status.success(), "env probe failed: {output:?}");
    assert_eq!(
        String::from_utf8(output.stdout).expect("utf8 stdout"),
        expected
    );
}

#[test]
fn shell_working_directory_cannot_be_set_after_runtime_events() {
    // A late None -> Some transition would mutate process-global cwd while
    // workers may already be resolving relative paths, so it must be rejected.
    let current = ExtConfig::default();
    let next = ExtConfig {
        working_directory: Some(PathBuf::from("/srv/late")),
        ..Default::default()
    };

    let err = apply_working_directory(&current, &next, true).expect_err("late cwd set rejected");

    assert!(err.contains("cannot be set after runtime events"));
}

#[test]
fn shell_tool_multiline_display_uses_short_args_and_text_payload() {
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("printf hello\nprintf world".to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(5.into()),
        ),
    ]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(output.display.mode, "");
    assert_eq!(output.display.args, "printf hello");
    assert_eq!(
        output.display.payload,
        Some(tau_proto::ToolUsePayload::Text {
            text: "printf hello\nprintf world".to_owned(),
        })
    );
}

/// A one-line shell command shortened in the display header remains available
/// as a full Unicode text payload in both progress and terminal descriptors so
/// `show-tools=full` can render the omitted middle.
#[test]
fn shell_tool_long_display_args_include_full_text_payload() {
    let command = "αβγδεζηθικλμνξοπρστυφχψω一二三四五六七八九十甲乙丙丁戊己庚辛壬癸";
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text(command.to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(5.into()),
        ),
    ]);
    let expected_args = "αβγδεζηθικλμνξοπρστυ┄一二三四五六七八九十甲乙丙丁戊己庚辛壬癸";
    let expected_payload = Some(tau_proto::ToolUsePayload::Text {
        text: command.to_owned(),
    });
    let initial = path_crate_tools::shell::initial_display(
        &args,
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
    );
    assert_eq!(initial.args, expected_args);
    assert_eq!(initial.payload, expected_payload);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(output.display.mode, "");
    assert_eq!(output.display.args, expected_args);
    assert_eq!(output.display.payload, expected_payload);
}

/// A one-line shell command that fits the display header does not gain a
/// redundant payload body.
#[test]
fn shell_tool_short_display_args_omit_redundant_text_payload() {
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text("printf hello".to_owned()),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(output.display.args, "printf hello");
    assert_eq!(output.display.payload, None);
}

#[test]
fn shell_tool_use_state_mode_can_show_inferred_access_mode() {
    // When directory locking is enabled, the CLI can render ext-shell's
    // inferred shell access mode separately from display args.
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text("printf hello".to_owned()),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::visible(
            path_crate_tools_shell::ShellAccessMode::ReadOnly,
        ),
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(output.display.mode, "ro");
    assert_eq!(output.display.args, "printf hello");
}

/// Ensures PTY-supported shell commands see TTY-backed output descriptors while
/// stdin stays closed and the result still distinguishes stdout from stderr.
#[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))]
#[test]
fn shell_tool_runs_with_tty_outputs_closed_stdin_and_separate_streams() {
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text(
            "[ ! -t 0 ] && [ -t 1 ] && [ -t 2 ] \
             && printf 'tty stdout\\n' \
             && printf 'tty stderr\\n' >&2"
                .to_owned(),
        ),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run TTY probe") else {
        panic!("expected finished shell outcome");
    };

    assert_eq!(cbor_int_field(&output.result, "status"), Some(0));
    assert_eq!(
        cbor_map_text(&output.result, "output"),
        Some("out tty stdout\nerr tty stderr")
    );
}

/// Ensures the documented bare-`cat` dependency fails as an ordinary missing
/// command when the configured child PATH contains no `cat`.
#[cfg(unix)]
#[test]
fn protected_pager_reports_command_not_found_when_cat_is_absent() {
    let shell = path_std_process::Command::new("sh")
        .arg("-c")
        .arg("command -v sh")
        .output()
        .expect("locate shell");
    assert!(shell.status.success());
    let shell = String::from_utf8(shell.stdout)
        .expect("shell path is utf8")
        .trim()
        .to_owned();
    let empty_path = TempDir::new().expect("empty PATH directory");
    let shell_config: crate::config::ShellConfig = serde_json::from_value(serde_json::json!({
        "command": shell,
        "extra_env": { "PATH": empty_path.path() }
    }))
    .expect("parse missing-cat config");
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text("printf payload | \"$PAGER\"".to_owned()),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &shell_config,
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run missing-cat probe") else {
        panic!("expected finished missing-cat shell outcome");
    };
    assert_eq!(cbor_int_field(&output.result, "status"), Some(127));
    assert!(
        cbor_map_text(&output.result, "output")
            .is_some_and(|output| output.contains("cat") && output.contains("not found"))
    );
}

/// Repository-owned subprocess helper that asserts closed stdin is immediately
/// poll-ready without depending on an external interpreter.
#[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))]
#[test]
#[ignore = "invoked explicitly by shell_tool_closed_stdin_provides_poll_visible_readiness"]
fn shell_tool_poll_stdin_helper() {
    let mut poll_fd = libc::pollfd {
        fd: 0,
        events: libc::POLLIN | libc::POLLHUP | libc::POLLERR,
        revents: 0,
    };
    // SAFETY: `poll_fd` points to one initialized `pollfd`, fd 0 is borrowed
    // rather than owned, and a zero timeout cannot block.
    #[allow(unsafe_code)]
    let ready = unsafe { libc::poll(&mut poll_fd, 1, 0) };
    assert_eq!(ready, 1);
}

#[test]
fn shell_tool_marks_invalid_utf8_stdout_line_and_marks_output_invalid() {
    // Regression coverage for agent-facing shell output collection: stdout
    // can contain arbitrary bytes, and read_to_string used to drop all output
    // after the first invalid UTF-8 sequence.
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text("printf '\\377stdout'".to_owned()),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(
        cbor_map_text(&output.result, "output"),
        Some("out(invalid-utf8,no_nl) �stdout")
    );
    assert_eq!(cbor_bool_field(&output.result, "valid_utf8"), Some(false));
}

#[test]
fn shell_tool_marks_crlf_and_cr_line_endings() {
    // Keep shell output line markers aligned with `read`: raw carriage
    // returns should not leak into agent-visible output.
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text("printf 'a\r\nb\rc\n'".to_owned()),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(
        cbor_map_text(&output.result, "output"),
        Some("out(crlf) a\nout(cr) b\nout c")
    );
}

#[test]
fn shell_tool_omits_truncation_marker_without_truncation() {
    // Compatibility metadata should stay sparse: total/truncated fields are
    // only present when a stream was actually truncated.
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text("printf 'ok\\n'".to_owned()),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(cbor_map_text(&output.result, "output"), Some("out ok"));
    let field = "truncated";
    assert!(
        cbor_map_field(&output.result, field).is_none(),
        "{field} should be absent without truncation"
    );
}

/// Ensures model shell accepts output exactly at its 15 KiB byte boundary.
#[test]
fn shell_tool_accepts_exact_model_output_byte_cap() {
    const EXPECTED_MODEL_SHELL_OUTPUT_BYTES: usize = 15 * 1024;
    assert_eq!(
        crate::tools::shell::MAX_MODEL_SHELL_OUTPUT_BYTES,
        EXPECTED_MODEL_SHELL_OUTPUT_BYTES
    );
    let emoji = "🙂";
    let emoji_count = (EXPECTED_MODEL_SHELL_OUTPUT_BYTES - "out ".len()) / emoji.len();
    let expected = format!("out {}", emoji.repeat(emoji_count));
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text(format!(
            "i=0; while [ \"$i\" -lt {emoji_count} ]; do printf '\\360\\237\\231\\202'; i=$((i + 1)); done; printf '\\n'"
        )),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    let combined = cbor_map_text(&output.result, "output").expect("output");
    assert_eq!(combined, expected);
    assert_eq!(combined.len(), EXPECTED_MODEL_SHELL_OUTPUT_BYTES);
    assert!(cbor_map_field(&output.result, "truncated").is_none());
    assert!(cbor_map_field(&output.result, "full_output_path").is_none());
}

/// Ensures byte-cap truncation preserves UTF-8 boundaries and saves the
/// complete rendering.
#[test]
fn shell_tool_multibyte_output_over_model_cap_keeps_exact_artifact() {
    const EXPECTED_MODEL_SHELL_OUTPUT_BYTES: usize = 15 * 1024;
    assert_eq!(
        crate::tools::shell::MAX_MODEL_SHELL_OUTPUT_BYTES,
        EXPECTED_MODEL_SHELL_OUTPUT_BYTES
    );
    let emoji = "🙂";
    const SECOND_LINE_EMOJI_COUNT: usize = 3;
    const ONE_BYTE_OVER_CAP: usize = 1;
    let output_prefix = "out ";
    let second_line = format!("{output_prefix}{}", emoji.repeat(SECOND_LINE_EMOJI_COUNT));
    let first_line_emoji_count = (EXPECTED_MODEL_SHELL_OUTPUT_BYTES + ONE_BYTE_OVER_CAP
        - "\n".len()
        - second_line.len()
        - output_prefix.len())
        / emoji.len();
    let first_line = format!("{output_prefix}{}", emoji.repeat(first_line_emoji_count));
    let expected = format!("{first_line}\n{second_line}");
    assert_eq!(
        expected.len(),
        EXPECTED_MODEL_SHELL_OUTPUT_BYTES + ONE_BYTE_OVER_CAP
    );
    let command = format!(
        "i=0; while [ \"$i\" -lt {first_line_emoji_count} ]; do printf '\\360\\237\\231\\202'; i=$((i + 1)); done; printf '\\n\\360\\237\\231\\202\\360\\237\\231\\202\\360\\237\\231\\202\\n'"
    );
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text(command),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    let combined = cbor_map_text(&output.result, "output").expect("output");
    assert_eq!(combined, format!("{first_line}\nout(truncated)"));
    assert_eq!(combined.len(), EXPECTED_MODEL_SHELL_OUTPUT_BYTES - 1);
    assert!(!combined.contains('\u{FFFD}'));
    assert_eq!(cbor_bool_field(&output.result, "truncated"), Some(true));
    assert_eq!(
        cbor_int_field(&output.result, "total_bytes"),
        Some(expected.len() as i128)
    );
    let saved = std::fs::read_to_string(
        cbor_map_text(&output.result, "full_output_path").expect("full output path"),
    )
    .expect("read complete saved output");
    assert_eq!(saved, expected);
}

/// Ensures shell truncation publishes complete totals and a readable,
/// privately contained complete saved rendering.
#[test]
fn shell_tool_reports_truncation_marker_and_original_totals() {
    let line_count = MAX_OUTPUT_LINES + 1;
    let command = format!(
        "i=0; while [ \"$i\" -lt {line_count} ]; do printf 'x\\n'; printf 'e\\n' >&2; i=$((i + 1)); done"
    );
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text(command),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    let combined = cbor_map_text(&output.result, "output").expect("output");
    assert!(combined.starts_with("out x") || combined.starts_with("err e"));
    assert!(combined.contains("\n...\n"));
    assert!(combined.contains("\nout x") || combined.contains("\nerr e"));
    assert_eq!(
        cbor_int_field(&output.result, "total_lines"),
        Some((line_count * 2) as i128)
    );
    assert!(cbor_int_field(&output.result, "total_bytes").is_some());
    assert_eq!(cbor_bool_field(&output.result, "truncated"), Some(true));
    assert!(cbor_map_text(&output.result, "truncation_warning").is_some());
    let path = path_std_path::PathBuf::from(
        cbor_map_text(&output.result, "full_output_path").expect("full output path"),
    );
    let saved =
        std::fs::read_to_string(&path).expect("saved output remains readable by exact path");
    assert!(saved.len() > combined.len());
    assert!(saved.starts_with("out x") || saved.starts_with("err e"));
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let directory_mode = path
            .parent()
            .expect("parent")
            .metadata()
            .expect("directory metadata")
            .permissions()
            .mode()
            & 0o777;
        let file_mode = path.metadata().expect("file metadata").permissions().mode() & 0o777;
        assert_eq!(directory_mode, 0o300);
        assert_eq!(file_mode, 0o600);
    }
}

#[test]
fn shell_tool_marks_invalid_utf8_and_truncation_together() {
    // When multiple shell-side warnings apply, keep them outside the stream
    // marker and in a deterministic order before stderr content.
    let line_count = MAX_OUTPUT_LINES + 1;
    let command = format!(
        "printf '\\377'; i=0; while [ \"$i\" -lt {line_count} ]; do printf 'x\\n'; i=$((i + 1)); done"
    );
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text(command),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(cbor_bool_field(&output.result, "valid_utf8"), Some(false));
    assert_eq!(cbor_bool_field(&output.result, "truncated"), Some(true));
}

#[test]
fn shell_tool_runs_in_requested_cwd() {
    // Regression coverage for the schema-exposed cwd argument: the execution
    // path already supports it, and the shell must actually start there.
    let tempdir = TempDir::new().expect("tempdir");
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("pwd".to_owned()),
        ),
        (
            CborValue::Text("cwd".to_owned()),
            CborValue::Text(tempdir.path().display().to_string()),
        ),
    ]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    let cwd = tempdir.path().canonicalize().expect("canonical cwd");
    let expected_stdout = format!("out {}", cwd.display());
    assert_eq!(
        cbor_map_text(&output.result, "output"),
        Some(expected_stdout.as_str())
    );
    assert!(cbor_map_text(&output.result, "cwd").is_none());
}

#[test]
fn shell_tool_timeout_preserves_partial_output() {
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("printf 'before\\n'; sleep 2; printf 'after\\n'".to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(1.into()),
        ),
    ]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("timeout result") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(output.display.status, ToolUseStatus::Error);
    assert_eq!(output.display.status_text, "timeout");
    assert_eq!(cbor_map_text(&output.result, "output"), Some("out before"));
    assert!(cbor_map_field(&output.result, "total_lines").is_none());
    assert_eq!(cbor_bool_field(&output.result, "timed_out"), Some(true));
    assert!(cbor_int_field(&output.result, "timeout_secs").is_none());
    assert_eq!(
        cbor_map_text(&output.result, "termination_reason"),
        Some("timeout")
    );
}

/// Ensures a foreground model shell result does not wait for EOF from a
/// background descendant that retains an output endpoint.
#[cfg(unix)]
#[test]
fn shell_tool_returns_after_foreground_exit_even_if_background_holds_output_endpoint() {
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("(sleep 5; printf late) & printf early".to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(1.into()),
        ),
    ]);

    let started = path_std_time::Instant::now();
    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    let elapsed = started.elapsed();
    assert!(
        elapsed < std::time::Duration::from_secs(2),
        "background output holder delayed shell result for {elapsed:?}"
    );
    let output = cbor_map_text(&output.result, "output").expect("output");
    assert_eq!(output, "out(no_nl) early");
    assert!(!output.contains("late"));
}

/// Ensures user `!` completion does not wait for stream EOF or capture late
/// output from a detached descendant that inherits stdout.
#[cfg(unix)]
#[test]
fn user_shell_returns_after_foreground_exit_even_if_background_holds_output_endpoint() {
    if !path_std_process::Command::new("sh")
        .arg("-c")
        .arg("command -v setsid >/dev/null")
        .status()
        .is_ok_and(|status| status.success())
    {
        return;
    }

    let (tx, rx) = path_std_sync::mpsc::channel();
    let cmd = tau_proto::UiShellCommand {
        session_id: "s1"
            .parse::<tau_proto::SessionId>()
            .expect("known-safe SessionId must be valid"),
        command_id: tau_proto::ShellCommandId::parse("ui-sh-bg")
            .expect("test identifier must satisfy its grammar"),
        command: "setsid sh -c 'sleep 5; printf late' & printf early".to_owned(),
        include_in_context: true,
        target_agent_id: None,
    };

    let started = path_std_time::Instant::now();
    let output = Output::channel(tx);
    let (_cancel_tx, cancel_rx) = path_std_sync::mpsc::channel();
    path_crate_tools::shell::dispatch_user_shell_command(
        cmd,
        path_crate_config::ShellConfig::default(),
        &output,
        cancel_rx,
        std::env::current_dir().expect("current dir"),
    );
    let elapsed = started.elapsed();
    assert!(
        elapsed < std::time::Duration::from_secs(2),
        "background output holder delayed user shell result for {elapsed:?}"
    );

    let mut finished = None;
    for message in rx.try_iter() {
        if let HarnessInputMessage::Emit(emit) = message
            && let Event::ShellCommandFinishedReported(event) = *emit.event
        {
            finished = Some(event);
        }
    }
    let finished = finished.expect("finished event");
    assert_eq!(finished.output, "early");
    assert!(!finished.output.contains("late"));
    assert_eq!(finished.exit_code, Some(0));
    assert!(!finished.cancelled);
}

/// Ensures timeout returns after killing the foreground process group even when
/// an escaped descendant retains an inherited stdout endpoint.
#[cfg(unix)]
#[test]
fn shell_tool_timeout_returns_without_waiting_for_escaped_output_holder() {
    if !path_std_process::Command::new("sh")
        .arg("-c")
        .arg("command -v setsid >/dev/null")
        .status()
        .is_ok_and(|status| status.success())
    {
        return;
    }

    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text(
                "setsid sh -c 'sleep 5; printf late' & printf early; sleep 5".to_owned(),
            ),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(1.into()),
        ),
    ]);

    let started = path_std_time::Instant::now();
    let CommandOutcome::Finished(result) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("timeout result") else {
        panic!("expected finished shell outcome");
    };
    let result = *result;
    let elapsed = started.elapsed();
    assert!(
        elapsed < std::time::Duration::from_secs(2),
        "escaped output holder delayed timeout result for {elapsed:?}"
    );
    assert_eq!(result.display.status, ToolUseStatus::Error);
    assert_eq!(result.display.status_text, "timeout");
    let output = cbor_map_text(&result.result, "output").expect("output");
    assert_eq!(output, "out(no_nl) early");
    assert!(!output.contains("late"));
    assert_eq!(cbor_bool_field(&result.result, "timed_out"), Some(true));
    assert_eq!(
        cbor_map_text(&result.result, "termination_reason"),
        Some("timeout")
    );
}

#[test]
fn shell_tool_bounded_huge_output_reports_original_totals() {
    // The shell reader keeps only a bounded tail in memory while counting the
    // original stream, so huge stdout still reports total bytes and truncation.
    let byte_count = MAX_OUTPUT_BYTES * 4 + 123;
    let command = format!("yes x | head -c {byte_count}");
    let args = CborValue::Map(vec![(
        CborValue::Text("command".to_owned()),
        CborValue::Text(command),
    )]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("run") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    let combined = cbor_map_text(&output.result, "output").expect("output");
    assert!(combined.contains("..."));
    assert!(combined.len() < byte_count);
    assert_eq!(cbor_bool_field(&output.result, "truncated"), Some(true));
    assert!(cbor_int_field(&output.result, "total_bytes").is_some());
}

#[test]
fn shell_tool_timeout_zero_is_immediate_timeout() {
    // A zero timeout is valid and means the child should be killed as soon as
    // timeout accounting observes that it has not already exited.
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("sleep 1".to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(0.into()),
        ),
    ]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("timeout result") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(output.display.status, ToolUseStatus::Error);
    assert_eq!(output.display.status_text, "timeout");
    assert_eq!(cbor_bool_field(&output.result, "timed_out"), Some(true));
    assert!(cbor_int_field(&output.result, "timeout_secs").is_none());
    assert_eq!(
        cbor_map_text(&output.result, "termination_reason"),
        Some("timeout")
    );
}

#[test]
fn shell_tool_rejects_negative_timeout() {
    // Negative durations cannot be represented by the runner; reject them
    // explicitly instead of silently falling back to the default.
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("printf should-not-run".to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer((-1).into()),
        ),
    ]);

    let error = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect_err("timeout");
    assert_eq!(error.message, "argument `timeout` must be non-negative");
}
#[test]
fn shell_tool_rejects_wrong_type_timeout() {
    // The old lenient integer helper ignored wrong-type values, causing the
    // default timeout to be used without telling the agent its request was bad.
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("printf should-not-run".to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Text("1".to_owned()),
        ),
    ]);

    let error = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect_err("timeout");
    assert_eq!(error.message, "argument `timeout` must be an integer");
}

#[test]
fn shell_tool_rejects_wrong_type_cwd() {
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("printf should-not-run".to_owned()),
        ),
        (
            CborValue::Text("cwd".to_owned()),
            CborValue::Integer(1.into()),
        ),
    ]);

    let error = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect_err("cwd");
    assert_eq!(error.message, "argument `cwd` must be a string");
}

#[cfg(unix)]
#[test]
fn shell_tool_reports_signal_termination_details() {
    // Regression coverage for signal deaths: shells killed by a signal do not
    // have an exit code, but Unix exposes the terminating signal separately.
    let args = CborValue::Map(vec![
        (
            CborValue::Text("command".to_owned()),
            CborValue::Text("kill -TERM $$".to_owned()),
        ),
        (
            CborValue::Text("timeout".to_owned()),
            CborValue::Integer(5.into()),
        ),
    ]);

    let CommandOutcome::Finished(output) = run_command_live(
        &args,
        &path_crate_config::ShellConfig::default(),
        path_crate_tools_shell::ShellCommandMode::READ_WRITE_HIDDEN,
        false,
        None,
    )
    .expect("signal result") else {
        panic!("expected finished shell outcome");
    };
    let output = *output;
    assert_eq!(output.display.status, ToolUseStatus::Error);
    assert_eq!(output.display.status_text, "signal 15");
    assert_eq!(cbor_int_field(&output.result, "signal"), Some(15));
    assert!(cbor_bool_field(&output.result, "timed_out").is_none());
    assert_eq!(
        cbor_map_text(&output.result, "termination_reason"),
        Some("signal")
    );
    assert!(cbor_map_field(&output.result, "status").is_none());
}

#[test]
fn shell_tool_reports_failures_with_details() {
    let (mut reader, mut writer) = spawn_extension();
    drain_startup(&mut reader);

    writer
        .write_event(&Event::ToolStarted(ToolStarted {
            invocation_policy: tau_proto::ToolInvocationPolicy::default(),
            call_id: "call-1".into(),
            tool_name: tau_proto::ToolName::new(SHELL_TOOL_NAME),
            arguments: CborValue::Map(vec![(
                CborValue::Text("command".to_owned()),
                CborValue::Text("exit 7".to_owned()),
            )]),
            agent_id: tau_proto::AgentId::parse("agent-1").expect("agent id"),
            originator: tau_proto::PromptOriginator::User,
        }))
        .expect("invoke");
    writer.flush().expect("flush");

    let _progress = reader.read_event().expect("read").expect("progress");

    let result = reader.read_event().expect("read").expect("result");
    let Event::ToolResult(result) = result else {
        panic!("expected tool result");
    };
    assert_eq!(result.tool_name, SHELL_TOOL_NAME);
    assert_eq!(cbor_int_field(&result.result, "status"), Some(7));
    assert_eq!(
        cbor_map_text(&result.result, "termination_reason"),
        Some("exit")
    );

    writer
        .write_frame(&disconnect_frame(None))
        .expect("disconnect");
    writer.flush().expect("flush");
}

/// Regression guard: a call-local shell cwd must never mutate durable workdir
/// metadata.
#[test]
fn explicit_shell_cwd_is_canonicalized_without_emitting_metadata() {
    let temp = TempDir::new().expect("tempdir");
    let original = TempDir::new().expect("original cwd");
    let agent_id = tau_proto::AgentId::parse("agent-cwd-explicit").expect("agent id");
    let cwd_state = CwdState::new();
    cwd_state.set(
        agent_id.clone(),
        original.path().canonicalize().expect("original"),
    );
    let Event::ToolStarted(invoke) = tool_started(
        "call-cwd",
        SHELL_TOOL_NAME,
        cbor_text_map(vec![
            ("command", "pwd"),
            ("cwd", &temp.path().display().to_string()),
        ]),
        agent_id.as_str(),
    ) else {
        unreachable!();
    };

    let base = cwd_state.get_or_default(&agent_id).expect("remembered cwd");
    let rewritten = rewrite_invoke_for_cwd(invoke, &base);
    let canonical = temp.path().canonicalize().expect("canonical cwd");
    assert_eq!(
        cwd_state.get_or_default(&agent_id).expect("remembered cwd"),
        original.path().canonicalize().expect("original")
    );
    assert_eq!(
        optional_argument_text(&rewritten.arguments, "cwd").expect("cwd arg"),
        Some(canonical.display().to_string())
    );
}

/// Regression guard: generic `shell.cwd` and GPT `shell_command.workdir` remain
/// call-local across full dispatch, including relative GPT resolution.
#[test]
fn shell_surface_directory_overrides_remain_call_local_across_full_dispatch() {
    let remembered = TempDir::new().expect("remembered");
    let override_dir = TempDir::new().expect("override");
    let relative_override = remembered.path().join("relative-override");
    fs::create_dir(&relative_override).expect("relative override");
    fs::write(remembered.path().join("remembered.txt"), "from-a\n").expect("remembered file");
    let agent_id = tau_proto::AgentId::parse("agent-call-local-cwd").expect("agent id");
    let (mut reader, mut writer) = spawn_extension();
    drain_startup(&mut reader);
    writer
        .write_event(&Event::AgentMetadataSet(tau_proto::AgentMetadataSet {
            agent_id: agent_id.clone(),
            key: tau_proto::AgentMetadataKey::new("ext_test-extension_cwd"),
            value: CborValue::Text(remembered.path().display().to_string()),
            mutation_id: None,
            inheritable: true,
        }))
        .expect("seed workdir");
    writer.flush().expect("flush seed");

    for tool_name in [SHELL_TOOL_NAME, GPT_SHELL_TOOL_NAME] {
        let surface =
            path_crate_tools::ShellSurface::for_tool_name(tool_name).expect("known shell surface");
        let mut cases = vec![
            (
                "override",
                Some(override_dir.path().display().to_string()),
                override_dir.path(),
            ),
            ("remembered-after", None, remembered.path()),
        ];
        if surface == path_crate_tools::ShellSurface::ChatGpt {
            cases.push((
                "relative-override",
                Some("relative-override".to_owned()),
                relative_override.as_path(),
            ));
        }
        for (suffix, directory_argument, expected) in cases {
            let call_id = format!("call-{tool_name}-{suffix}");
            let mut args = vec![("command", "pwd")];
            if let Some(directory_argument) = directory_argument.as_deref() {
                args.push((surface.directory_argument(), directory_argument));
            }
            writer
                .write_event(&tool_started(
                    &call_id,
                    tool_name,
                    cbor_text_map(args),
                    agent_id.as_str(),
                ))
                .expect("shell call");
            writer.flush().expect("flush shell call");
            loop {
                match reader.read_event().expect("read").expect("event") {
                    Event::AgentMetadataSetRequest(metadata) => {
                        panic!("call-local shell directory emitted metadata: {metadata:?}")
                    }
                    Event::AgentUserMessageInjected(notice) => {
                        panic!("call-local shell directory emitted notice: {notice:?}")
                    }
                    Event::ToolResult(result) if result.call_id.as_str() == call_id => {
                        let rendered = format!("{:?}", result.result);
                        assert!(
                            rendered.contains(expected.to_str().expect("UTF-8 path")),
                            "shell result did not use expected call-local directory: {rendered}"
                        );
                        break;
                    }
                    _ => {}
                }
            }
        }
    }
    writer
        .write_event(&tool_started(
            "call-read-remembered-after",
            READ_TOOL_NAME,
            cbor_text_map(vec![("path", "remembered.txt")]),
            agent_id.as_str(),
        ))
        .expect("read remembered file");
    writer.flush().expect("flush read");
    loop {
        match reader.read_event().expect("read").expect("event") {
            Event::AgentMetadataSetRequest(metadata) => {
                panic!("call-local shell directory emitted metadata: {metadata:?}")
            }
            Event::ToolResult(result)
                if result.call_id.as_str() == "call-read-remembered-after" =>
            {
                assert!(format!("{:?}", result.result).contains("from-a"));
                break;
            }
            _ => {}
        }
    }
}

#[test]
fn replayed_shell_tool_delivery_does_not_run_tool() {
    let tempdir = TempDir::new().expect("tempdir");
    let path = tempdir.path().join("replay-must-not-write.txt");
    let (mut reader, mut writer, done_rx) = spawn_extension_with_exit();
    drain_startup(&mut reader);

    let Event::ToolStarted(invoke) = tool_started(
        "replayed-edit",
        EDIT_TOOL_NAME,
        edit_arguments(&path, vec![context_half_open_edit(1, 1, "created\n", "")]),
        "agent-a",
    ) else {
        unreachable!();
    };
    writer
        .write_frame(&HarnessOutputMessage::deliver_replay(
            tau_proto::UnixMicros::new(1),
            Event::ToolStarted(invoke),
        ))
        .expect("replayed edit");
    writer
        .write_frame(&disconnect_frame(None))
        .expect("disconnect");
    writer.flush().expect("flush");

    done_rx
        .recv_timeout(Duration::from_secs(5))
        .expect("extension exit")
        .expect("extension ok");
    assert!(
        !path.exists(),
        "replayed tool delivery must not mutate files"
    );
}

#[test]
fn shell_tool_cancel_request_stops_running_command_quickly() {
    let (mut reader, mut writer) = spawn_extension();
    drain_startup(&mut reader);

    let call_id = tau_proto::ToolCallId::new("cancel-shell-call");
    writer
        .write_event(&Event::ToolStarted(ToolStarted {
            invocation_policy: tau_proto::ToolInvocationPolicy::default(),
            call_id: call_id.clone(),
            tool_name: tau_proto::ToolName::new(SHELL_TOOL_NAME),
            arguments: CborValue::Map(vec![(
                CborValue::Text("command".to_owned()),
                CborValue::Text("sleep 30".to_owned()),
            )]),
            agent_id: tau_proto::AgentId::parse("agent-1").expect("agent id"),
            originator: tau_proto::PromptOriginator::User,
        }))
        .expect("invoke shell");
    writer.flush().expect("flush invoke");

    let started = Instant::now();
    let progress_deadline = reader.arm_deadline(started + Duration::from_secs(2));
    loop {
        assert!(started.elapsed() < Duration::from_secs(2));
        match reader.read_event().unwrap_or_else(|error| {
            if matches!(&error, tau_proto::DecodeError::Io(error) if error.kind() == std::io::ErrorKind::TimedOut)
            {
                panic!("shell progress timed out");
            }
            panic!("read shell progress: {error}");
        }) {
            Some(Event::ToolProgressReported(progress)) if progress.call_id == call_id => break,
            Some(_) => continue,
            None => panic!("extension closed before shell started"),
        }
    }
    progress_deadline.finish();

    writer
        .write_event(&Event::ToolCancelRequest(ToolCancelRequest {
            target_call_id: call_id.clone(),
        }))
        .expect("cancel shell");
    writer.flush().expect("flush cancel");

    let deadline = Instant::now() + Duration::from_secs(3);
    let cancellation_deadline = reader.arm_deadline(deadline);
    loop {
        assert!(Instant::now() < deadline, "shell cancellation timed out");
        match reader.read_event().unwrap_or_else(|error| {
            if matches!(&error, tau_proto::DecodeError::Io(error) if error.kind() == std::io::ErrorKind::TimedOut)
            {
                panic!("shell cancellation timed out");
            }
            panic!("read shell cancellation: {error}");
        }) {
            Some(Event::ToolCancelled(cancelled)) if cancelled.call_id == call_id => break,
            Some(_) => continue,
            None => panic!("extension closed before cancellation"),
        }
    }
    cancellation_deadline.finish();

    writer
        .write_frame(&disconnect_frame(None))
        .expect("disconnect");
    writer.flush().expect("flush");
}