trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Unit tests for the PM Bash-command classifier (`super`), relocated out of
//! `mod.rs` (issue #2734) so the production file stays under the 500-SLOC cap.
//! `tests.rs` is classified as a test file (1500-SLOC cap).

use super::*;
// #7234: the rules now ask `unresolved_target`, so the narrower `$NAME` half is
// no longer imported by `mod.rs` and is reached here directly.
use super::main_checkout::main_checkout_head_move;
use super::path_tokens::unexpanded_shell_variable;

#[test]
fn evaluate_bash_command_denies_shell_edit_verbs() {
    for cmd in [
        "sed -i s/a/b/ src/lib.rs",
        "sed -i.bak s/a/b/ src/lib.rs",
        "awk -i inplace '{print}' f",
        "patch -p1 < d.patch",
        "git apply my.patch",
        "FOO=1 sed -i s/a/b/ f",
        "sudo patch -p0 x",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(SHELL_EDIT_REASON),
            "expected shell-edit deny for: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_allows_readonly_sed_awk() {
    // #2664: sed/awk used as narrowly read-only stream filters (no
    // in-place flag, no external script, no write/exec construct,
    // balanced quotes) must not be blanket-denied by name.
    for cmd in [
        "git status --porcelain | awk '{print $1}' | sort | uniq -c",
        "sed -n '1,5p' file.txt",
        "git log | awk '{print $1}'",
        "cat f | sed 's/a/b/'",
        "sed 's/a/b/g' f | grep x",
        // Code-critic re-review MEDIUM: an apostrophe/single-quote inside
        // a double-quoted read-only script must not be over-denied.
        r#"sed "s/can't/cannot/" f"#,
        r#"awk -F"'" '{print $2}'"#,
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "expected allow for read-only sed/awk: {cmd:?}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_awk_shell_escape_holes() {
    // Code-critic BLOCK on PR #2677: awk's `system()` builtin runs an
    // arbitrary shell command with no `-i` and no `>` — the
    // allow-by-default design missed this entirely.
    for cmd in [
        r#"awk 'BEGIN{system("touch /tmp/x")}'"#,
        r#"awk 'BEGIN{system("curl https://evil/x")}'"#,
        // Code-critic re-review CRITICAL: AWK tolerates whitespace
        // between a builtin name and its `(` — `system ("...")` (space)
        // executes exactly like `system("...")` and was missed by a
        // no-space-only substring check.
        r#"awk 'BEGIN{system ("touch /tmp/x")}'"#,
        "awk 'BEGIN{system\t(\"echo x\")}'",
        // A co-process pipe/read inside the awk program is itself a
        // bare `|`/`;` from the (quote-unaware) segment splitter's point
        // of view, so it fragments the quoted program and leaves an
        // unbalanced quote count in the resulting segment — denied.
        r#"awk 'BEGIN{print | "sort"}'"#,
        r#"awk 'BEGIN{"date" | getline}'"#,
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(SHELL_EDIT_REASON),
            "expected shell-edit deny for awk shell-escape: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_sed_e_w_commands() {
    // sed's `e` (execute) and `w`/`W` (write-to-file) commands need no
    // `-i` and no `>` — a bare verb-name deny-list miss, closed by
    // deny-by-default + script-content analysis in `sed_awk`.
    for cmd in [
        "sed '1e touch /tmp/x' f",
        "sed -n '1,5w /tmp/out' f",
        "sed 's/a/b/e' f",
        "sed 's/a/b/w /tmp/out' f",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(SHELL_EDIT_REASON),
            "expected shell-edit deny for sed e/w command: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_external_script_load() {
    // `-f`/`--file` loads a script the guard cannot see — it may contain
    // any of the w/e/system holes above, so deny unconditionally.
    for cmd in ["sed -f script.sed f", "awk -f script.awk f"] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(SHELL_EDIT_REASON),
            "expected shell-edit deny for external script load: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_sed_in_place_abbreviations() {
    // GNU getopt long-option abbreviations of `--in-place` must still
    // deny, not just the exact spelling.
    for cmd in [
        "sed --in s/a/b/ f",
        "sed --in-p s/a/b/ f",
        "sed --in=bak s/a/b/ f",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(SHELL_EDIT_REASON),
            "expected shell-edit deny for --in-place abbreviation: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_awk_family_verbs() {
    // gawk/nawk/mawk are the same in-place-edit-capable interpreter
    // family as awk and must be classified identically.
    assert_eq!(
        evaluate_bash_command("gawk -i inplace '{print}' f"),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        evaluate_bash_command(r#"nawk 'BEGIN{system("id")}'"#),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        evaluate_bash_command("gawk '{print $1}'"),
        None,
        "read-only gawk must still allow"
    );
}

#[test]
fn evaluate_bash_command_denies_redirection_write() {
    assert_eq!(
        evaluate_bash_command("echo 'code' > src/lib.rs"),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        evaluate_bash_command("printf x >> notes.txt"),
        Some(SHELL_EDIT_REASON)
    );
}

#[test]
fn evaluate_bash_command_denies_build_and_test() {
    for cmd in ["make build", "pytest -q", "npm test"] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(BUILD_TEST_REASON),
            "expected build/test deny for: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_network() {
    for cmd in ["curl https://example.com", "wget https://example.com/x"] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(NETWORK_REASON),
            "expected network deny for: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_allows_normal_shell() {
    for cmd in [
        "",
        "   ",
        "git status",
        "git add -A",
        "git commit -m x",
        "git log --oneline",
        "git diff",
        "git push",
        "ls -la",
        "grep -rn foo src",
        "cat README.md",
        "cargo tree 2>&1", // fd-dup, not a file write
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "expected allow for: {cmd:?}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_composition_hidden_verbs() {
    // A benign leading verb must NOT hide a forbidden verb in a later
    // composed segment (the shell-composition bypass, PR #1985).
    assert_eq!(
        evaluate_bash_command("cd repo && sed -i s/a/b/ f"),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        evaluate_bash_command("true; make build"),
        Some(BUILD_TEST_REASON)
    );
    assert_eq!(
        evaluate_bash_command("x || pytest"),
        Some(BUILD_TEST_REASON)
    );
    assert_eq!(
        evaluate_bash_command("ls && git apply p.diff"),
        Some(SHELL_EDIT_REASON)
    );
    // Redirection hidden after a benign first segment still denies.
    assert_eq!(
        evaluate_bash_command("cd repo && echo x > out.txt"),
        Some(SHELL_EDIT_REASON)
    );
}

#[test]
fn evaluate_bash_command_denies_bare_ampersand_composition() {
    // A bare `&` (background separator) must NOT hide a forbidden trailing
    // verb — the bare-`&` composition bypass (second adversarial review).
    assert_eq!(
        evaluate_bash_command("true & sed -i s/a/b/ f"),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        evaluate_bash_command("cd x & make build"),
        Some(BUILD_TEST_REASON)
    );
    assert_eq!(evaluate_bash_command("x & pytest"), Some(BUILD_TEST_REASON));
    // Newline is a separator too.
    assert_eq!(
        evaluate_bash_command("cd repo\nsed -i s/a/b/ f"),
        Some(SHELL_EDIT_REASON)
    );
}

#[test]
fn evaluate_bash_command_allows_trailing_background() {
    // Trailing background `&` with nothing after must not become a spurious
    // forbidden segment, and fd-dups must not be treated as separators.
    for cmd in ["sleep 1 &", "cargo tree 2>&1", "foo >&2"] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "expected allow for: {cmd:?}"
        );
    }
}

#[test]
fn evaluate_bash_command_allows_benign_pipes() {
    // Composition where NO segment is a forbidden verb must still allow —
    // we do not blanket-deny all composition.
    for cmd in [
        "git log | head",
        "cat f | grep x",
        "ls | wc -l",
        "git diff && git status",
        "cd repo; ls -la",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "expected allow for benign composition: {cmd:?}"
        );
    }
}

#[test]
fn evaluate_bash_command_allows_dev_null_redirect() {
    // `/dev/null` is an output-discard sink, not a file write.
    for cmd in ["which cargo 2>/dev/null", "command -v foo >/dev/null"] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "expected allow for /dev/null discard: {cmd:?}"
        );
    }
}

// ---- #2745 false-positive instance: 2>/dev/null on a read-only multi-line,
// multi-segment command (Bob's live hotstats-worktree repro, 2026-07-17) ----

#[test]
fn evaluate_bash_command_allows_bob_hotstats_dev_null_repro() {
    // Bob's live repro: a `cd` + `echo` + `ls … 2>/dev/null` composed over a
    // newline and `&&` was denied by an older deployed pm_guard binary. The
    // current classifier already treats `2>/dev/null` as a discard sink, not
    // a file write, across the whole (multi-segment, multi-line) command —
    // this locks that behaviour in as a permanent regression test.
    let cmd = "cd /Users/masa/trusty-mpm-projects/bobmatnyc/trusty-tools/.base/.claude/worktrees/tm-hotstats-product-poc-01\necho \"=== docs tree ===\" && ls docs docs/provenance 2>/dev/null";
    assert_eq!(
        evaluate_bash_command(cmd),
        None,
        "read-only cd/echo/ls with 2>/dev/null must be allowed"
    );
}

#[test]
fn evaluate_bash_command_allows_more_dev_null_and_fd_dup_shapes() {
    // The task's explicit list of read-only redirection shapes that must
    // never trip the edit heuristic.
    for cmd in [
        "ls docs 2>/dev/null",
        "cargo check 2>&1",
        "which rustc >/dev/null",
        "which rustc &>/dev/null",
        "ls a b 2>/dev/null && echo done",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "expected allow for read-only redirection shape: {cmd:?}"
        );
    }
}

// ---- #2918: content-aware delegation routing hint extraction -------------

#[test]
fn extract_shell_edit_target_from_redirection() {
    assert_eq!(
        extract_shell_edit_target("echo 'code' > src/lib.rs"),
        Some("src/lib.rs".to_string())
    );
    assert_eq!(
        extract_shell_edit_target("printf x >> docs/notes.md"),
        Some("docs/notes.md".to_string())
    );
}

#[test]
fn extract_shell_edit_target_from_trailing_sed_awk_patch_arg() {
    assert_eq!(
        extract_shell_edit_target("sed -i s/a/b/ app/main.py"),
        Some("app/main.py".to_string())
    );
    assert_eq!(
        extract_shell_edit_target("patch -p1 web/App.tsx"),
        Some("web/App.tsx".to_string())
    );
    assert_eq!(
        extract_shell_edit_target("git apply my.patch"),
        Some("my.patch".to_string())
    );
}

#[test]
fn extract_shell_edit_target_none_when_unresolvable() {
    // A verb with no plausible trailing target (not sed/awk/patch/git-apply)
    // yields no hint — caller falls back to generic.
    assert_eq!(extract_shell_edit_target("git status"), None);
    // A trailing flag with nothing after it yields no hint either.
    assert_eq!(extract_shell_edit_target("sed -i"), None);
}

#[test]
fn extract_shell_edit_target_best_effort_on_script_only_sed() {
    // `sed -n '1,5p'` has no target file — the trailing-token heuristic is
    // best-effort only (it never affects allow/deny, only the suggested
    // delegate name) and may pick up the script text itself here.
    assert_eq!(
        extract_shell_edit_target("sed -n '1,5p'"),
        Some("'1,5p'".to_string())
    );
}

#[test]
fn extract_shell_edit_target_ignores_dev_null_and_fd_dup() {
    // These are not file-write redirects, so no target — falls through to
    // the trailing-token heuristic (which also yields nothing here).
    assert_eq!(extract_shell_edit_target("ls docs 2>/dev/null"), None);
    assert_eq!(extract_shell_edit_target("cargo check 2>&1"), None);
}

#[test]
fn evaluate_bash_command_denies_hidden_substitution_verb() {
    // A forbidden verb inside a command substitution must be caught.
    assert_eq!(
        evaluate_bash_command("echo \"$(sed -i s/a/b/ f)\""),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        evaluate_bash_command("x=`make build`"),
        Some(BUILD_TEST_REASON)
    );
}

#[test]
fn evaluate_bash_command_allows_benign_substitution() {
    // Trivial substitutions with benign bodies must not be over-blocked.
    for cmd in [
        "echo \"$(date)\"",
        "cd \"$(git rev-parse --show-toplevel)\"",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "expected allow for benign substitution: {cmd:?}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_unbalanced_substitution() {
    // An unbalanced substitution we cannot decompose denies conservatively.
    assert_eq!(
        evaluate_bash_command("echo $(sed -i"),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(evaluate_bash_command("echo `foo"), Some(SHELL_EDIT_REASON));
}

#[test]
fn evaluate_bash_command_bounds_deep_substitution_nesting() {
    // Adversarial deep `$(` nesting must return a decision without panicking
    // (stack-exhaustion guard). A deny is the acceptable safe outcome.
    let deep = format!("echo {}", "$(".repeat(200));
    let decision = evaluate_bash_command(&deep);
    assert!(decision.is_some(), "deep nesting must deny, got allow");
    // Balanced-but-deep nesting is also bounded (no panic, returns a value).
    let balanced = format!("echo {}date{}", "$(".repeat(200), ")".repeat(200));
    let _ = evaluate_bash_command(&balanced);
}

#[test]
fn split_shell_segments_splits_operators() {
    assert_eq!(
        split_shell_segments("a && b || c ; d | e"),
        vec!["a ", " b ", " c ", " d ", " e"]
    );
}

#[test]
fn split_shell_segments_splits_bare_ampersand() {
    // A bare `&` with a following command splits; fd-dups and trailing
    // background do not.
    assert_eq!(split_shell_segments("a & b"), vec!["a ", " b"]);
    assert_eq!(split_shell_segments("foo &"), vec!["foo &"]);
    assert_eq!(
        split_shell_segments("cargo test 2>&1"),
        vec!["cargo test 2>&1"]
    );
    assert_eq!(split_shell_segments("foo >&2"), vec!["foo >&2"]);
    // Newline splits.
    assert_eq!(split_shell_segments("a\nb"), vec!["a", "b"]);
}

#[test]
fn split_shell_segments_single_command() {
    assert_eq!(split_shell_segments("git status"), vec!["git status"]);
    // Backgrounding `&` (nothing after) is not a split point.
    assert_eq!(split_shell_segments("foo &"), vec!["foo &"]);
}

#[test]
fn has_file_write_redirection_detects_write() {
    assert!(has_file_write_redirection("echo x > f"));
    assert!(has_file_write_redirection("echo x >f.rs"));
}

#[test]
fn has_file_write_redirection_detects_append() {
    assert!(has_file_write_redirection("echo x >> f"));
}

#[test]
fn has_file_write_redirection_ignores_fd_dup() {
    assert!(!has_file_write_redirection("cargo test 2>&1"));
    assert!(!has_file_write_redirection("foo >&2"));
}

#[test]
fn has_file_write_redirection_ignores_dev_null() {
    // Discarding output to /dev/null is not a file write.
    assert!(!has_file_write_redirection("which cargo 2>/dev/null"));
    assert!(!has_file_write_redirection("command -v foo >/dev/null"));
    assert!(!has_file_write_redirection("foo &>/dev/null"));
    // A real file write with the same shape still denies.
    assert!(has_file_write_redirection("echo x > /dev/null.txt"));
    assert!(has_file_write_redirection("echo x > out.txt"));
}

#[test]
fn has_file_write_redirection_false_for_plain_command() {
    assert!(!has_file_write_redirection("git status"));
}

// ---- #2734: git global flags + quoted-content false positives -----------

#[test]
fn evaluate_bash_command_allows_bob_git_commit_repro() {
    // Bob's live repro: an allowlisted `git commit` denied as a shell edit
    // because a `>` / `->` inside the single-quoted `-m` body tripped the
    // (then quote-unaware) file-write-redirection scan, compounded by the
    // leading `-C <path>` global flag hiding the `commit` subcommand.
    let cmd = r#"git -C /Users/masa/trusty-mpm-projects/bobmatnyc/writing commit -q -m 'feat(hyperdev): draft "SDD: When The Spec Becomes Part Of The Code"' -m 'HyperDev deep-dive: the spec IS the code — SDD flips the pipeline so spec > impl'"#;
    assert_eq!(
        evaluate_bash_command(cmd),
        None,
        "Bob's git commit with quoted prose must be allowed"
    );
}

#[test]
fn evaluate_bash_command_allows_git_commit_with_quoted_operators() {
    // A `-m` message may legitimately contain any shell metacharacter as prose;
    // none of it is shell syntax, so the commit stays allowed.
    for cmd in [
        r#"git commit -m 'spec -> code'"#,
        r#"git commit -m 'a > b'"#,
        r#"git commit -m 'pipe a | b then c'"#,
        r#"git commit -m 'run make && test'"#,
        r#"git commit -m 'costs $(x) or `y`'"#,
        r#"git commit -m 'use sed -i to fix; then awk'"#,
        r#"git commit -m "double > quoted -> ok""#,
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "quoted prose must not trip a deny: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_allows_git_global_flags() {
    // Allowlisted git subcommands must be recognised through leading global
    // flags (`-C <path>`, `-c <kv>`, `--git-dir=…`).
    for cmd in [
        "git -C /some/path status",
        "git -C /some/path log --oneline",
        "git -C /some/path diff",
        "git -C /some/path commit -m x",
        "git -c user.name=x -c user.email=y@z commit -m x",
        "git --git-dir=/p/.git --work-tree=/p status",
        "git -C /some/path push --force",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "git through global flags must be allowed: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_git_apply_through_global_flags() {
    // The one forbidden git subcommand must still be caught through global
    // flags — closing the `git -C <path> apply` under-deny hole.
    for cmd in [
        "git apply my.patch",
        "git -C /some/path apply my.patch",
        "git -c core.pager=x apply my.patch",
        "git --git-dir=/p/.git apply my.patch",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(SHELL_EDIT_REASON),
            "git apply must deny through global flags: {cmd}"
        );
    }
}

#[test]
fn evaluate_bash_command_preserves_true_positives_after_quote_awareness() {
    // Quote-awareness must NOT weaken real shell-level edits/pipes/redirects.
    let shell_edit = [
        "sed -i s/a/b/ src/lib.rs",
        "echo 'code' > src/lib.rs",
        "printf x >> src/lib.rs",
        r#"awk '{print}' > out.rs"#,      // unquoted redirect
        r#"awk 'BEGIN{print | "sort"}'"#, // quoted co-process
        r#"awk '{print > "out.rs"}'"#,    // in-program redirect
        "git apply p.diff",
        "cat f | sed -i s/a/b/ g", // forbidden verb in a real pipe
    ];
    for cmd in shell_edit {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(SHELL_EDIT_REASON),
            "must still deny shell edit: {cmd}"
        );
    }
    // #2664 read-only sed/awk carve-out still ALLOWS.
    for cmd in [
        "git status --porcelain | awk '{print $1}' | sort | uniq -c",
        "sed -n '1,5p' file.txt",
        "cat f | sed 's/a/b/'",
        r#"sed "s/can't/cannot/" f"#,
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "read-only sed/awk must still allow: {cmd}"
        );
    }
}

#[test]
fn split_shell_segments_ignores_quoted_operators() {
    // Operators inside quotes are literal data, not separators.
    assert_eq!(
        split_shell_segments("git commit -m 'a | b'"),
        vec!["git commit -m 'a | b'"]
    );
    assert_eq!(
        split_shell_segments("echo 'x && y ; z'"),
        vec!["echo 'x && y ; z'"]
    );
    // Unquoted operators still split.
    assert_eq!(split_shell_segments("a | b"), vec!["a ", " b"]);
    // Unbalanced quotes fall back to the quote-unaware split.
    assert_eq!(
        split_shell_segments("echo 'unterminated | b"),
        vec!["echo 'unterminated ", " b"]
    );
}

/// #6946: a here-document body is one segment with its operator line, so the
/// ADR-0049 composed-commit guard no longer sees a commit that never runs.
#[test]
fn split_shell_segments_keeps_a_heredoc_body_whole() {
    let command = "cat <<'EOF' > f\ngit commit -m x\nEOF";
    assert_eq!(split_shell_segments(command), vec![command]);
    // A separator of every kind inside the body is data too.
    let mixed = "cat <<EOF > f\na && b ; c | d & e\nEOF";
    assert_eq!(split_shell_segments(mixed), vec![mixed]);
    // The operator line keeps its live syntax, and text after the terminator
    // is a real second segment.
    assert_eq!(
        split_shell_segments("true && cat <<EOF\nbody\nEOF\ngit status"),
        vec!["true ", " cat <<EOF\nbody\nEOF", "git status"]
    );
}

/// #6946 fail-open check: an unterminated here-document claims nothing, so the
/// pre-#6946 over-splitting stands and the guard keeps denying.
#[test]
fn split_shell_segments_still_splits_an_unterminated_heredoc() {
    assert_eq!(
        split_shell_segments("cat <<'EOF' > f\ngit commit -m x"),
        vec!["cat <<'EOF' > f", "git commit -m x"]
    );
    // `$((1 << 3))` is not a here-document either.
    assert_eq!(
        split_shell_segments("echo $((1 << 3))\ngit status"),
        vec!["echo $((1 << 3))", "git status"]
    );
}

/// #6946 fail-open check: `bash <<EOF` runs its body as shell source, so the
/// body's separators must keep splitting and reaching the verb rules.
#[test]
fn split_shell_segments_still_splits_a_shell_heredoc_body() {
    assert_eq!(
        split_shell_segments("bash <<'EOF'\ngit add x && git commit -m y\nEOF"),
        vec!["bash <<'EOF'", "git add x ", " git commit -m y", "EOF"]
    );
    assert_eq!(
        split_shell_segments("sudo /bin/sh <<EOF\nsed -i s/a/b/ f\nEOF"),
        vec!["sudo /bin/sh <<EOF", "sed -i s/a/b/ f", "EOF"]
    );
    // …and the destructive verb in such a body is still denied end to end.
    assert_eq!(
        evaluate_bash_command("bash <<'EOF'\nsed -i s/a/b/ src/lib.rs\nEOF"),
        Some(SHELL_EDIT_REASON)
    );
}

#[test]
fn has_file_write_redirection_ignores_quoted_gt() {
    // A `>` inside quotes is literal; an unquoted one is a real redirect.
    assert!(!has_file_write_redirection("git commit -m 'spec > code'"));
    assert!(!has_file_write_redirection(r#"echo "a -> b""#));
    assert!(has_file_write_redirection("echo x > f.rs"));
    // Unbalanced quotes fall back to scanning all bytes.
    assert!(has_file_write_redirection("echo 'oops > f.rs"));
}

#[test]
fn has_file_write_redirection_ignores_heredoc_body() {
    // #5356: a `>` in here-document body text is script content, not a
    // redirect. Both spellings of the issue's reproduction.
    assert!(!has_file_write_redirection(
        "python3 <<'PY'\nprint([k for k in d if len(k) > 3])\nPY"
    ));
    assert!(!has_file_write_redirection("cat <<EOF\nspec -> code\nEOF"));
}

#[test]
fn has_file_write_redirection_detects_redirect_on_a_heredoc_operator_line() {
    // #5356 must not fail open: only the BODY is data. A redirect on the
    // operator line, or after the terminator, is still a file write.
    assert!(has_file_write_redirection(
        "python3 <<'PY' > out.rs\nprint(1)\nPY"
    ));
    assert!(has_file_write_redirection(
        "python3 <<'PY'\nprint(1)\nPY\necho done > f.rs"
    ));
}

#[test]
fn evaluate_bash_command_allows_readonly_heredoc_script() {
    // #5356 end-to-end through the classifier: the read-only heredoc that was
    // classified as a shell file edit (and so consumed the PM's per-turn
    // file-change budget) now allows.
    assert_eq!(
        evaluate_bash_command(
            "python3 <<'PY'\nimport json\nd = json.load(open('/tmp/x.json'))\nprint([k for k in d if len(k) > 3])\nPY"
        ),
        None
    );
}

#[test]
fn evaluate_bash_command_denies_heredoc_with_real_redirect() {
    // The still-denies arm of #5356.
    assert_eq!(
        evaluate_bash_command("python3 <<'PY' > src/lib.rs\nprint(1)\nPY"),
        Some(SHELL_EDIT_REASON)
    );
}

#[test]
fn evaluate_bash_command_allows_quoted_substitution_prose() {
    // `$(`/backtick inside SINGLE quotes is literal; inside DOUBLE quotes it is
    // still live and a forbidden body still denies.
    assert_eq!(
        evaluate_bash_command(r#"git commit -m 'run $(sed -i x) maybe'"#),
        None,
        "single-quoted substitution is literal prose"
    );
    assert_eq!(
        evaluate_bash_command(r#"echo "$(sed -i s/a/b/ f)""#),
        Some(SHELL_EDIT_REASON),
        "double-quoted substitution is still live"
    );
}

#[test]
fn evaluate_worktree_add_command_denies_direct_tmp_targets() {
    let cwd = Path::new("/Users/x/proj");
    for cmd in [
        "git worktree add /tmp/wt-x",
        "git worktree add /private/tmp/wt-x",
        "git worktree add /var/folders/x1/abc/T/wt-x",
        "git worktree add -b feat-x /tmp/wt-x",
        "git worktree add --lock --reason busy /tmp/wt-x",
    ] {
        assert_eq!(
            evaluate_worktree_add_command(cmd, cwd),
            Some(WORKTREE_TMP_REASON),
            "expected deny for: {cmd}"
        );
    }
}

#[test]
fn evaluate_worktree_add_command_allows_project_targets() {
    let cwd = Path::new("/Users/x/proj");
    for cmd in [
        "git worktree add .claude/worktrees/wt-x",
        "git worktree add /Users/x/proj/.claude/worktrees/wt-x",
        "git worktree add ../sibling-wt",
        "git worktree add -b feat-x .claude/worktrees/wt-x",
    ] {
        assert_eq!(
            evaluate_worktree_add_command(cmd, cwd),
            None,
            "expected allow for: {cmd}"
        );
    }
}

#[test]
fn evaluate_worktree_add_command_only_matches_add_subcommand() {
    let cwd = Path::new("/Users/x/proj");
    for cmd in [
        "git worktree list",
        "git worktree remove /tmp/wt-x",
        "git worktree prune",
        "git worktree lock /tmp/wt-x",
    ] {
        assert_eq!(
            evaluate_worktree_add_command(cmd, cwd),
            None,
            "non-add worktree subcommand must never be blocked: {cmd}"
        );
    }
}

#[test]
fn evaluate_worktree_add_command_ignores_ordinary_temp_usage() {
    let cwd = Path::new("/Users/x/proj");
    for cmd in [
        "mktemp -d",
        "echo x > /tmp/scratch.txt",
        "cargo build --target-dir /tmp/build",
        "git status",
        "git commit -m 'add worktree support'",
    ] {
        assert_eq!(
            evaluate_worktree_add_command(cmd, cwd),
            None,
            "ordinary temp usage must not be blocked: {cmd}"
        );
    }
}

#[test]
fn evaluate_worktree_add_command_resolves_relative_target_against_cwd() {
    // A relative target under a cwd that is ITSELF under /tmp must resolve
    // (and deny) even though the argument text never spells "/tmp".
    let cwd = Path::new("/tmp/some-repo");
    assert_eq!(
        evaluate_worktree_add_command("git worktree add wt-x", cwd),
        Some(WORKTREE_TMP_REASON)
    );
    // The same relative target from a project cwd is fine.
    let ok_cwd = Path::new("/Users/x/proj");
    assert_eq!(
        evaluate_worktree_add_command("git worktree add wt-x", ok_cwd),
        None
    );
}

/// Both spellings of macOS's `$TMPDIR` root deny, cwd-relative included (#5924).
///
/// Why: `/var` is a symlink to `/private/var`, and `current_dir()` inside
/// `$TMPDIR` returns the resolved `/private/var/folders/...` spelling. The
/// denylist carried only `/var/folders`, so a relative target resolved from
/// that cwd matched nothing and the guard let it through — the same paired-entry
/// treatment `/tmp` and `/private/tmp` already had was never applied to `/var`.
#[test]
fn evaluate_worktree_add_command_denies_both_var_folders_spellings() {
    for cwd in [
        Path::new("/var/folders/x1/abc/T"),
        Path::new("/private/var/folders/x1/abc/T"),
    ] {
        assert_eq!(
            evaluate_worktree_add_command("git worktree add wt-x", cwd),
            Some(WORKTREE_TMP_REASON),
            "cwd-relative target must deny from: {}",
            cwd.display()
        );
    }
    let proj = Path::new("/Users/x/proj");
    for cmd in [
        "git worktree add /private/var/folders/x1/abc/T/wt-x",
        "cd /private/var/folders/x1/abc/T && git worktree add wt-x",
        "git -C /private/var/folders/x1/abc/T worktree add wt-x",
    ] {
        assert_eq!(
            evaluate_worktree_add_command(cmd, proj),
            Some(WORKTREE_TMP_REASON),
            "expected deny for: {cmd}"
        );
    }
    // `/private/var` outside `folders/` is ordinary system state, not scratch.
    assert_eq!(
        evaluate_worktree_add_command("git worktree add /private/var/lib/wt-x", proj),
        None
    );
}

#[test]
fn evaluate_worktree_add_command_follows_cd_prefix() {
    // `cd /tmp && git worktree add wt-foo` — the cwd change must be tracked
    // across composition segments (documented partial mitigation).
    let cwd = Path::new("/Users/x/proj");
    assert_eq!(
        evaluate_worktree_add_command("cd /tmp && git worktree add wt-foo", cwd),
        Some(WORKTREE_TMP_REASON)
    );
    assert_eq!(
        evaluate_worktree_add_command("cd .claude/worktrees && git worktree add wt-foo", cwd),
        None
    );
}

#[test]
fn evaluate_worktree_add_command_follows_git_dash_c_override() {
    let cwd = Path::new("/Users/x/proj");
    assert_eq!(
        evaluate_worktree_add_command("git -C /tmp worktree add wt-foo", cwd),
        Some(WORKTREE_TMP_REASON)
    );
    assert_eq!(
        evaluate_worktree_add_command("git -C /tmp worktree add /Users/x/proj/wt-foo", cwd),
        None,
        "an absolute in-project target overrides the -C base"
    );
}

// The env values are INJECTED, never written to the process. An earlier
// revision set `TMPDIR`/`HOME` with `std::env::set_var` behind a restore-on-drop
// guard plus `#[serial]`; neither closes the window that matters, because
// `cargo test` runs tests as threads in ONE process and `#[serial]` only
// serialises against other `#[serial]` tests. Every non-serial sibling still saw
// the mutated `TMPDIR` — and `tempfile` honors it, so five `pm_guard_budget`
// tests panicked with `NotFound` on a Linux CI runner over a macOS-only literal
// path (PR #4914, run 31023632348). `PathEnv` is the seam that removes the
// global write; `#[serial]` is correspondingly gone because there is nothing
// left to serialise.
#[test]
fn evaluate_worktree_add_command_expands_tmpdir_and_home() {
    let cwd = Path::new("/Users/x/proj");
    let env = PathEnv {
        // A harness scratchpad under the `/private/tmp` denylist root — the
        // property under test. Deliberately not any real machine's path.
        tmpdir: Some("/private/tmp/agent-scratch".to_string()),
        tmp: None,
        home: Some("/Users/x".to_string()),
    };
    assert_eq!(
        evaluate_worktree_add_command_in("git worktree add $TMPDIR/wt-foo", cwd, &env),
        Some(WORKTREE_TMP_REASON),
        "$TMPDIR indirection must resolve to the harness scratchpad, still denylisted"
    );
    assert_eq!(
        evaluate_worktree_add_command_in(
            "git worktree add ~/proj/.claude/worktrees/wt-foo",
            cwd,
            &env
        ),
        None,
        "~ expansion to an in-project target must be allowed"
    );
}

/// The public entry point must still expand against the process environment.
///
/// Why: without this, the injected-env test above could stay green while a
/// refactor left [`evaluate_worktree_add_command`] passing an EMPTY `PathEnv`,
/// silently disabling `$TMPDIR`/`~` expansion for the real guard. Asserts
/// equivalence rather than a concrete verdict, so it depends on the delegation
/// and not on what this machine's `$TMPDIR`/`$HOME` happen to be.
#[test]
fn evaluate_worktree_add_command_delegates_to_the_process_environment() {
    let cwd = Path::new("/Users/x/proj");
    let process_env = PathEnv::from_process();
    for cmd in [
        "git worktree add $TMPDIR/wt-foo",
        "git worktree add ${TMPDIR}/wt-foo",
        "git worktree add ~/scratch/wt-foo",
        "git worktree add .claude/worktrees/wt-foo",
    ] {
        assert_eq!(
            evaluate_worktree_add_command(cmd, cwd),
            evaluate_worktree_add_command_in(cmd, cwd, &process_env),
            "the public entry point must expand against the process env: {cmd}"
        );
    }
}

#[test]
fn evaluate_worktree_add_command_normalizes_dot_dot_traversal() {
    // A purely textual `..` escape must be recognized without touching the fs.
    // cwd has exactly 2 name components (Users, proj), so 2 `..` pops back to
    // root before descending into `tmp`.
    let cwd = Path::new("/Users/proj");
    assert_eq!(
        evaluate_worktree_add_command("git worktree add ../../tmp/wt-x", cwd),
        Some(WORKTREE_TMP_REASON)
    );
}

// ── #4837 review BLOCK 1(b): the agent-cost stop's persistence escape hatch ──

#[test]
fn command_is_persistence_only_accepts_commit_and_push() {
    // Exactly the sequence a stopped agent needs to not lose its work.
    for cmd in [
        "git add -A",
        "git commit -m 'fix: something'",
        "git push origin HEAD",
        "git status --short",
        "git diff --stat",
        // Composed, but every segment is still persistence.
        "git add -A && git commit -m x && git push",
        "git status; git diff",
        // A trailing separator leaves an empty tail segment.
        "git status && ",
    ] {
        assert!(
            command_is_persistence_only(cmd),
            "expected {cmd:?} to count as persistence"
        );
    }
}

#[test]
fn command_is_persistence_only_sees_past_git_global_flags() {
    // Agents commit from a worktree with `git -C <path> …` constantly; the
    // escape hatch is useless if it cannot see the subcommand behind that.
    for cmd in [
        "git -C /repo/wt commit -m x",
        "git --git-dir=/repo/.git --work-tree=/repo add -A",
        "git --work-tree /repo -C /repo status",
        "git --no-pager diff --stat",
    ] {
        assert!(
            command_is_persistence_only(cmd),
            "expected {cmd:?} to resolve past its global flags"
        );
    }
}

#[test]
fn command_is_persistence_only_rejects_config_injection() {
    // #4850 review HIGH, shape 1: `-c` sits in `GIT_GLOBAL_OPTS_WITH_ARG`, so
    // the first cut consumed it with its value and resolved a clean `diff` —
    // while `diff.external` runs whatever it names. The earlier suite asserted
    // `git -c user.name=bot commit -m x` WAS persistence, which pinned the hole
    // open by construction: any `-c <anything>` was accepted. `-c` is now
    // rejected outright, so no value has to be judged.
    for cmd in [
        "git -c diff.external='cargo test' diff",
        "git -c core.gitProxy=cargo fetch",
        "git -c credential.helper='!cargo test' push",
        "git -c alias.p='!cargo test' push",
        // The benign spelling goes too — an agent persisting work does not
        // need `-c`, and allow-listing values is the losing side of the bet.
        "git -c user.name=bot commit -m x",
        // Same class, other spellings: config from the environment, and the
        // path git resolves its subcommand binaries from.
        "git --config-env=user.name=EVIL commit -m x",
        "git --exec-path=/tmp/evil status",
        // Default-deny means an option nobody thought about is rejected too.
        "git --totally-made-up-global status",
    ] {
        assert!(
            !command_is_persistence_only(cmd),
            "expected {cmd:?} to be rejected as config injection"
        );
    }
}

#[test]
fn command_is_persistence_only_rejects_exec_options() {
    // #4850 review HIGH, shape 3: these sit AFTER the subcommand, which the
    // first cut never examined — `git_subcommand` had already answered "push"
    // and stopped reading.
    for cmd in [
        "git push --receive-pack='cargo test' /tmp/repo HEAD",
        "git push --receive-pack cargo /tmp/repo HEAD",
        "git push --exec='cargo test' /tmp/repo HEAD",
        "git push --upload-pack=cargo origin HEAD",
        "git diff --ext-diff",
        "git diff --textconv",
        "git diff --output=/tmp/out.txt",
        // Default-deny, not a `-pack` suffix rule: a name nobody has listed is
        // denied because it is absent from SAFE_LONG_OPTS, not because it
        // matched a pattern someone thought of.
        "git push --future-pack=cargo origin HEAD",
        "git push --brand-new-exec-thing=cargo origin HEAD",
    ] {
        assert!(
            !command_is_persistence_only(cmd),
            "expected {cmd:?} to be rejected as an exec-capable option"
        );
    }
}

#[test]
fn command_is_persistence_only_rejects_abbreviated_exec_options() {
    // #4850 second review, HIGH: git's parse-options accepts any unambiguous
    // PREFIX of a long option, so `--exe` IS `--exec` and `--rece` IS
    // `--receive-pack`. The deny list matched names exactly, so all three of
    // these classified as persistence and all three executed the named program
    // against a real bare remote. `--receive-pack` was not even on the list —
    // it was riding the `-pack` SUFFIX rule, which an abbreviation strips off
    // entirely, so no suffix rule could ever have covered it.
    //
    // These pass now because the long-option surface is default-deny: an
    // abbreviation of a dangerous name is not in SAFE_LONG_OPTS. That is the
    // property under test — not the three strings.
    for cmd in [
        "git push --rece=cargo /tmp/r HEAD",
        "git push --exe=cargo /tmp/r HEAD",
        "git push --exe cargo /tmp/r HEAD",
        // The rest of the prefix chain, both families, both spellings.
        "git push --r=cargo /tmp/r HEAD",
        "git push --receiv=cargo /tmp/r HEAD",
        "git push --receive-pac=cargo /tmp/r HEAD",
        "git push --e cargo /tmp/r HEAD",
        "git push --exec cargo /tmp/r HEAD",
        "git push --uploa=cargo origin HEAD",
        "git push --upl cargo origin HEAD",
        // `--exec-path` and the diff-side exec filters abbreviate too.
        "git status --exec-pat=/tmp/evil",
        "git diff --ext",
        "git diff --textc",
        "git diff --outp=/tmp/out.txt",
    ] {
        assert!(
            !command_is_persistence_only(cmd),
            "expected {cmd:?} to be rejected: an abbreviation IS the option"
        );
    }
}

#[test]
fn command_is_persistence_only_accepts_the_flags_agents_actually_use() {
    // The other half of the default-deny flip: it must not strand the work the
    // hatch exists to save. Everything a stopped agent needs to stage, commit,
    // and push still classifies as persistence.
    for cmd in [
        "git add -A --force",
        "git add -- src/lib.rs",
        "git commit -m 'fix: thing' --amend --no-verify",
        "git commit --message='fix: thing' --signoff --allow-empty",
        "git commit -m x --no-gpg-sign --author='Bot <b@example.com>'",
        "git push -u origin HEAD --force-with-lease",
        "git push origin HEAD --tags --follow-tags --atomic",
        "git push origin HEAD --dry-run --porcelain",
        "git status --short --branch --untracked-files=all",
        "git diff --stat --cached --name-only",
        "git diff --unified=5 --ignore-all-space -- crates/",
        "git diff HEAD~1 --no-ext-diff --no-textconv",
    ] {
        assert!(
            command_is_persistence_only(cmd),
            "expected {cmd:?} to survive the default-deny option surface"
        );
    }
}

#[test]
fn command_is_persistence_only_rejects_remote_helper_transport() {
    // #4850 review HIGH, shape 2: `ext::` runs its argument as a shell command
    // by design, and the form generalises to any `<transport>::<address>`
    // remote helper. Rejecting the `::` token closes all of them, and the `-c`
    // that enabled it is independently rejected.
    for cmd in [
        "git -c protocol.ext.allow=always push ext::sh -c 'cargo test' HEAD",
        "git push ext::sh -c 'cargo test' HEAD",
        "git push ext::cargo origin HEAD",
    ] {
        assert!(
            !command_is_persistence_only(cmd),
            "expected {cmd:?} to be rejected as a remote-helper transport"
        );
    }
    // An ordinary remote with a single colon is untouched.
    assert!(command_is_persistence_only("git push origin HEAD:main"));
}

#[test]
fn command_is_persistence_only_admits_the_attacker_chosen_repo_residual() {
    // #4850 second review, LOW 1. The module's residual note used to scope the
    // on-disk exec route to "the repository's own config", which is wrong: `-C`,
    // `--git-dir`, and `--work-tree` are ALLOWED globals, so the repo whose
    // config git reads is attacker-choosable inside the same command. The
    // critic ran `git -C /tmp/evil diff` and it executed a `diff.external` from
    // an attacker-chosen path.
    //
    // This asserts the residual EXISTS, deliberately. Closing it means reading
    // and judging repo config from inside a PreToolUse hook, which is neither
    // fast nor side-effect-free; the note now says so. If someone later closes
    // it, this test fails and the note goes with it.
    assert!(command_is_persistence_only("git -C /tmp/evil diff"));
    assert!(command_is_persistence_only(
        "git --git-dir=/tmp/evil/.git diff"
    ));
}

#[test]
fn command_is_persistence_only_rejects_process_substitution() {
    // #4850 review HIGH, shape 4: `<(` is neither `$(` nor a backtick, and the
    // redirection scan only ever looked at `>`, so this ran `cargo test` inside
    // an "allowed" git call. Any unquoted metacharacter now disqualifies, so
    // there is no spelling left to miss.
    for cmd in [
        "git diff <(cargo test)",
        "git diff >(cargo test)",
        "git add -A < /tmp/list",
        "git commit -m x -F <(cargo test)",
        "git status (cargo test)",
    ] {
        assert!(
            !command_is_persistence_only(cmd),
            "expected {cmd:?} to be rejected as process substitution"
        );
    }
}

#[test]
fn command_is_persistence_only_allows_metacharacters_inside_quotes() {
    // The metacharacter rule has to stay quote-aware or it strands exactly the
    // work the hatch exists to save — commit messages are full of these.
    for cmd in [
        "git commit -m 'fix: handle (n>1) and $HOME'",
        "git commit -m \"refactor: spec -> code\"",
        "git commit -m 'closes #4850 (review)'",
    ] {
        assert!(
            command_is_persistence_only(cmd),
            "expected {cmd:?} to survive its quoted metacharacters"
        );
    }
}

#[test]
fn command_is_persistence_only_requires_a_bare_git_program() {
    // An env-assignment prefix is an exec vector of its own
    // (`GIT_SSH_COMMAND`, `GIT_EXTERNAL_DIFF`, `GIT_PAGER`, `LD_PRELOAD`), and
    // `sudo`/`env` re-exec. None is needed to persist, so the program token
    // must be git itself.
    for cmd in [
        "GIT_SSH_COMMAND='cargo test' git push",
        "GIT_EXTERNAL_DIFF=cargo git diff",
        "env GIT_PAGER=cargo git diff",
        "sudo git commit -m x",
        // #4850 second review, MEDIUM: the check was `program.rsplit('/')`, a
        // BASENAME test, so every one of these answered "git" and the critic
        // executed a planted script by that name. Exposure needs a pre-existing
        // write + chmod +x, but the module doc claimed the program was
        // verified, and a basename verifies the file's name, not the program.
        "./git commit -m x",
        "/tmp/evil/git push origin HEAD",
        "../../tmp/evil/git status",
        "$HOME/evil/git add -A",
        // The whole token must be `git`, so a path-qualified real git goes too.
        // That is the trade: no fs resolution in a PreToolUse hook, and a bare
        // `git` is always available as the fallback spelling.
        "/usr/bin/git commit -m x",
    ] {
        assert!(
            !command_is_persistence_only(cmd),
            "expected {cmd:?} to be rejected: the program must be git itself"
        );
    }
    // The one spelling that survives.
    assert!(command_is_persistence_only("git commit -m x"));
}

#[test]
fn command_is_persistence_only_rejects_smuggled_work() {
    // The whole risk of an allowlist: one allowed verb dragging real work in
    // behind it. Every one of these must fail the WHOLE command.
    for cmd in [
        "git commit -m x && cargo test",
        "cargo test && git commit -m x",
        "git commit -m x | tee log",
        "git commit -m x; rm -rf /",
        // Not persistence: these mutate the tree or fetch work.
        "git checkout main",
        "git reset --hard",
        "git worktree add /tmp/x",
        "git rebase -i HEAD~3",
        // Not git at all.
        "echo hi",
        "",
        "   ",
        // `git` reached through sudo: the program token is not git, and a
        // program that re-execs is not persistence.
        "sudo -u bob git commit -m x",
    ] {
        assert!(
            !command_is_persistence_only(cmd),
            "expected {cmd:?} to be rejected as non-persistence"
        );
    }
}

#[test]
fn command_is_persistence_only_rejects_substitution_and_redirection() {
    // A substitution runs arbitrary code inside an "allowed" segment, and a
    // redirection writes arbitrary files. Neither is needed to commit.
    for cmd in [
        "git commit -m \"$(cargo build 2>&1)\"",
        "git commit -m `date`",
        "git status > /tmp/out.txt",
        "git diff >> notes.md",
        // #4850: a discard sink used to be allowed here, on the strength of
        // `has_file_write_redirection` telling a `/dev/null` write from a real
        // one. That classifier is no longer in the trust path — keeping it
        // meant keeping a hand-rolled redirection parser that had already
        // missed `<`. Every unquoted redirection metacharacter now
        // disqualifies, and an agent saving its work never needs one.
        "git status 2>/dev/null",
    ] {
        assert!(
            !command_is_persistence_only(cmd),
            "expected {cmd:?} to be rejected"
        );
    }
}

/// Why (#5843): the owner's ruling asks for `tm wait` to be whitelisted by
/// pm_guard. Today's classifier denies by VERB, not by an allowlist, so
/// `tm wait` already passes — this test is the defence that keeps it passing.
/// A future deny rule that classifies by binary name, by "waits are
/// suspicious", or by a broadened build/test predicate would silently take the
/// one sanctioned in-turn wait mechanism away from every agent, and the guard
/// error would name a reason that has nothing to do with waiting.
/// What: asserts every shape of `tm wait` an agent is documented to type is
/// classified as allowed.
#[test]
fn evaluate_bash_command_never_denies_tm_wait() {
    for cmd in [
        "tm wait --for file --path /tmp/gate.txt",
        "tm wait --for file --path /tmp/gate.txt --contains EXIT=",
        "tm wait --for run --pid 4242 --timeout 3600",
        "tm wait --for run --handle /tmp/job.pid",
        "tm wait --for check --pr 5843 --repo bobmatnyc/trusty-tools",
        "tm wait --for check --pr 5843 --interval 30 --slice 100",
        "trusty-mpm wait --for file --path /tmp/gate.txt",
        // The re-run loop an agent drives: same command, over and over.
        "tm wait --for file --path /tmp/gate.txt --timeout 1800 --slice 100",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "`tm wait` is the sanctioned in-turn wait; it must never be denied: {cmd:?}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_process_substitution_edit() {
    // #2745: bash executes the body of `<(…)`, so a `sed -i` there edits a file
    // exactly as a bare `sed -i` would. Before the fix the guard inspected only
    // `$(…)` and backticks, so every spelling below was ALLOWED.
    for cmd in [
        "diff <(sed -i s/a/b/ f) x",
        "diff x <(sed -i s/a/b/ f)",
        "cat <(patch -p1 f.diff)",
        "wc -l <(git apply my.patch)",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            Some(SHELL_EDIT_REASON),
            "process-substitution body must be classified: {cmd:?}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_output_process_substitution_by_classification() {
    // #2745: `>(…)` was denied only incidentally, because its leading `>` trips
    // the redirection scan. The body is now classified, so the deny is by
    // design — and a non-shell-edit body reports ITS OWN reason rather than the
    // redirection one.
    assert_eq!(
        evaluate_bash_command("tee >(sed -i s/a/b/ f)"),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        evaluate_bash_command("tee >(curl http://example.com)"),
        Some(NETWORK_REASON),
        "the body's own classification decides, not the `>` scan"
    );
}

#[test]
fn evaluate_bash_command_allows_readonly_process_substitution() {
    // #2745 must close the bypass without blanket-denying the read-only form.
    for cmd in [
        "diff <(sort a.txt) <(sort b.txt)",
        "comm -12 <(git ls-files) <(cat manifest.txt)",
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "read-only process substitution must still pass: {cmd:?}"
        );
    }
}

#[test]
fn evaluate_bash_command_denies_unbalanced_process_substitution() {
    // An unclassifiable segment fails CLOSED, matching the `$(`/backtick shape.
    assert_eq!(
        evaluate_bash_command("diff <(sed -i s/a/b/ f x"),
        Some(SHELL_EDIT_REASON)
    );
}

#[test]
fn evaluate_bash_command_allows_quoted_process_substitution_prose() {
    // Unlike `$(…)`, process substitution is suppressed by BOTH quote styles,
    // so a `<(…)` in a commit message is literal text in either.
    for cmd in [
        r#"git commit -m 'use diff <(sed -i x) y'"#,
        r#"git commit -m "use diff <(sed -i x) y""#,
    ] {
        assert_eq!(
            evaluate_bash_command(cmd),
            None,
            "quoted process-substitution prose is not shell syntax: {cmd:?}"
        );
    }
}

// ── #6660: wrapper spellings must not hide the inner command ────────────────

/// Every wrapper spelling that runs `inner` as a real command.
///
/// `inner` must contain no quote characters — the nested-quoting shapes are
/// asserted separately by each rule's own test so the quoting under test is
/// visible at the assertion, not buried in a formatter.
fn wrapper_spellings(inner: &str) -> Vec<String> {
    vec![
        format!("sh -c \"{inner}\""),
        format!("bash -c '{inner}'"),
        format!("zsh -c \"{inner}\""),
        format!("/bin/sh -c \"{inner}\""),
        format!("bash -lc \"{inner}\""),
        format!("env -S \"{inner}\""),
        format!("xargs {inner}"),
        format!("xargs -0 {inner}"),
        format!("xargs -n 4 {inner}"),
        // #8756: `eval` joins and runs its operands; a flag or `--` may sit
        // between `-c` and the command string.
        format!("eval \"{inner}\""),
        format!("eval {inner}"),
        format!("bash -ce \"{inner}\""),
        format!("sh -c -- \"{inner}\""),
        // A wrapper over a wrapper, and a shell over a shell.
        format!("sudo sh -c \"{inner}\""),
        format!("sh -c \"bash -c '{inner}'\""),
        // Composition inside the wrapped string.
        format!("sh -c \"true && {inner}\""),
    ]
}

/// Why (#6660): `git_subcommand` required the resolved program basename to be
/// `git`, and `strip_wrapper_prefix` never descended into a `-c` string or an
/// `xargs` argv. Every rule built on that classifier — the #5791 worktree-remove
/// deny, the ADR-0048 main-checkout HEAD-move rule, and the destructive-delete
/// rule — therefore saw `sh`/`bash`/`zsh`/`env`/`xargs` and allowed the command
/// underneath. One spelling handled is not a fix, so all three rules are
/// asserted against every spelling in [`wrapper_spellings`] plus the nested
/// quoting each rule can meet on its own.
/// Test: itself.
#[test]
fn wrappers_do_not_hide_the_inner_command_from_the_git_verb_rules() {
    const WT: &str = "/repo/.claude/worktrees/agent-x";
    let engineer = DispatchIdentity {
        agent_id: Some("agent-abc123"),
        agent_type: Some("rust-engineer"),
    };

    // --- Rule 1: `git worktree remove` by a non-version-control subagent. ---
    let mut worktree_cases = wrapper_spellings(&format!("git worktree remove {WT}"));
    // Nested quoting: the inner command quotes its own argument.
    worktree_cases.push(format!("bash -c \"git worktree remove '{WT}'\""));
    worktree_cases.push(format!("sh -c 'git worktree remove \"{WT}\"'"));
    // A `cd` inside the wrapped string still moves the resolution base.
    worktree_cases
        .push("sh -c \"cd /repo && git worktree remove .claude/worktrees/agent-x\"".to_string());
    for command in &worktree_cases {
        let verdict = evaluate_worktree_remove_command(command, true, engineer, Path::new("/repo"));
        assert!(
            matches!(verdict, WorktreeRemoveVerdict::Deny(_)),
            "the #5791 worktree-remove deny must see through: {command}"
        );
    }

    // --- Rule 2: a HEAD move inside a main checkout (ADR-0048). ------------
    let checkout = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir(checkout.path().join(".git")).expect("mkdir .git");
    for command in wrapper_spellings("git merge origin/main") {
        let resolved = main_checkout_head_move(&command, checkout.path());
        assert!(
            resolved.is_some(),
            "the main-checkout HEAD-move rule must see through: {command}"
        );
        assert_eq!(resolved.expect("resolved").expect("placed").0, "merge");
    }

    // --- Rule 3: destructive delete of a worktree root. --------------------
    for command in wrapper_spellings(&format!("rm -rf {WT}")) {
        assert!(
            evaluate_destructive_delete_command(&command, Path::new("/repo")).is_some(),
            "the destructive-delete rule must see through: {command}"
        );
    }
}

/// Why (#6660): a wrapped command whose inner string cannot be lexed is a
/// command the guard cannot classify at all. Allowing it would make broken
/// quoting the bypass, so the guard fails closed and denies.
/// Test: itself.
#[test]
fn an_unparseable_wrapped_command_is_denied() {
    for command in [
        "sh -c \"git worktree remove 'unterminated\"",
        "bash -c 'rm -rf \"unterminated'",
    ] {
        assert!(
            evaluate_bash_command(command).is_some(),
            "an unlexable wrapped command must deny: {command}"
        );
    }
}

// ── #6660 review: the three shapes that reached the ABSOLUTE guards ─────────

/// Why (#6660 review, CRITICAL 2): `shlex` 1.3.0 drops the quotes of `$'…'`
/// and keeps the `$`, so `sh -c $'git worktree remove x'` lexes to a program
/// token of `$git` and matches no rule. The critic confirmed the live bypass
/// against the compiled binary. The guard cannot decode the escapes, so it
/// must refuse — and the bypass needs no wrapper, which is why the bare `git`
/// spelling is asserted too.
/// Test: itself.
#[test]
fn unclassifiable_command_flags_ansi_c_quoting() {
    for command in [
        "sh -c $'git worktree remove /repo/.claude/worktrees/agent-x'",
        "bash -c $'rm -rf /repo/.claude/worktrees/agent-x'",
        "git $'worktree' remove /repo/.claude/worktrees/agent-x",
        "env -S $'git worktree remove x'",
        // Inside the wrapped string, where the outer quote map reads it as
        // literal text — the recursion re-scans it where it is live.
        "sh -c \"git $'worktree' remove /repo/.claude/worktrees/agent-x\"",
        "$\"git\" worktree remove x",
    ] {
        assert_eq!(
            unclassifiable_command(command),
            Some(ANSI_C_QUOTING_REASON),
            "ANSI-C quoting must be refused: {command}"
        );
    }
}

/// Why (#9127 fold-in): bash expands `{git,-C,<main>,commit}` into a git
/// command while every rule reads one unknown program word, the same blind
/// spot as `$'…'` quoting, refused the same way.
/// Test: itself.
#[test]
fn brace_expanded_program_word_is_unclassifiable() {
    for command in [
        "{git,-C,/m,commit,-a}",
        "({git,commit})",
        "true && {git,commit}",
        "if true; then {git,commit}; fi",
        "env {git,commit}",
        "/usr/bin/{git,x} commit",
        "sh -c '{git,commit}'",
    ] {
        assert!(
            unclassifiable_command(command).is_some_and(|r| r.contains("brace expansion")),
            "brace expansion must be refused: {command}"
        );
    }
    for command in [
        "mkdir -p src/{a,b}",
        "cp f{,.bak}",
        "{ git commit; }",
        "echo ${HOME}",
        "git add src/{a,b}.rs",
        "git commit -m '{a,b}'",
    ] {
        assert_eq!(unclassifiable_command(command), None, "{command}");
    }
}

/// Why (#6660 review, CRITICAL 1): the fail-closed answer has to come from a
/// function the ABSOLUTE guards' caller reaches, not only from
/// `evaluate_bash_command`.
/// Test: itself.
#[test]
fn unclassifiable_command_flags_an_unlexable_wrapper() {
    for command in [
        "sh -c \"git worktree remove 'unterminated\"",
        "bash -c 'rm -rf \"unterminated'",
        "xargs sh -c \"git worktree remove 'x\"",
    ] {
        assert_eq!(
            unclassifiable_command(command),
            Some(UNLEXABLE_WRAPPER_REASON),
            "an unlexable wrapper must be refused: {command}"
        );
    }
}

/// Why (#6660 review, CRITICAL 3): the first cut STOPPED recursing at the cap
/// instead of denying, so 8 nested layers denied and 9 allowed. Asserted at
/// the exact boundary the critic measured.
/// Test: itself.
#[test]
fn unclassifiable_command_denies_past_the_depth_cap() {
    /// `sh -c <cmd>` wrapped `layers` deep around `inner`, shell-quoting at
    /// each layer so every level is a legal single token (naive alternating
    /// quotes stop nesting correctly past two levels).
    fn nest(inner: &str, layers: usize) -> String {
        let mut command = inner.to_string();
        for _ in 0..layers {
            let quoted = shlex::try_quote(&command).expect("quotable");
            command = format!("sh -c {quoted}");
        }
        command
    }
    let inner = "git worktree remove /repo/.claude/worktrees/agent-x";

    // Within budget: resolvable, so this function has no opinion — the
    // worktree-remove rule classifies it (asserted below).
    for layers in 1..=MAX_WRAPPER_DEPTH {
        let command = nest(inner, layers);
        assert_eq!(
            unclassifiable_command(&command),
            None,
            "{layers} layers are within budget: {command}"
        );
    }
    // Past budget: refused, not skipped.
    for layers in [MAX_WRAPPER_DEPTH + 1, MAX_WRAPPER_DEPTH + 4] {
        let command = nest(inner, layers);
        assert_eq!(
            unclassifiable_command(&command),
            Some(WRAPPER_DEPTH_REASON),
            "{layers} layers exhaust the budget and must be refused"
        );
    }
    // And the rule that matters still denies on both sides of the boundary,
    // through the guard entry point a subagent actually reaches.
    let engineer = DispatchIdentity {
        agent_id: Some("agent-abc123"),
        agent_type: Some("rust-engineer"),
    };
    for layers in [MAX_WRAPPER_DEPTH, MAX_WRAPPER_DEPTH + 1] {
        let command = nest(inner, layers);
        let denied = unclassifiable_command(&command).is_some()
            || matches!(
                evaluate_worktree_remove_command(&command, true, engineer, Path::new("/repo")),
                WorktreeRemoveVerdict::Deny(_)
            );
        assert!(denied, "{layers} layers must deny: {command}");
    }
}

/// Why (#6660 review): the refusal must not swallow ordinary work — a guard
/// that denies `bash -c 'cargo build'` is retried differently and worse
/// (ADR-0048 decision 6).
/// Test: itself.
#[test]
fn unclassifiable_command_allows_ordinary_commands() {
    for command in [
        "git status --porcelain",
        "sh -c 'git status --porcelain'",
        "bash -c \"cargo build\"",
        "xargs git add",
        "cargo test -p trusty-mpm && git log --oneline -5",
        // A `$` that is not opening ANSI-C quoting stays fine.
        "echo $HOME",
        "git log --format='%h $ %s'",
        // ...including a literal `$'` that is itself quoted into prose.
        "git commit -m \"cost: $'5' per unit\"",
    ] {
        assert_eq!(
            unclassifiable_command(command),
            None,
            "ordinary command must not be refused: {command}"
        );
    }
}

/// Why (#6660): the unwrapping must not turn ordinary wrapped work into a
/// denial — a guard that denies `bash -c 'cargo build'` is retried differently
/// and worse (ADR-0048 decision 6).
/// Test: itself.
#[test]
fn wrappers_around_benign_commands_still_allow() {
    for command in [
        "sh -c 'git status --porcelain'",
        "bash -c \"git log --oneline -5\"",
        "xargs git add",
        "sh -c 'echo hello'",
        "bash -c 'cargo build'",
        "eval \"git status --porcelain\"",
        "eval \"$(ssh-agent -s)\"",
    ] {
        assert_eq!(
            evaluate_bash_command(command),
            None,
            "expected allow for benign wrapped command: {command}"
        );
    }
}

/// Why (#6982): two rust-engineers in isolation worktrees reported a `for` loop
/// over `crates/trusty-git-analytics/**` and a `python3 - <<'PY'` scratch
/// script being refused for "naming git". Nothing in THIS classifier matches
/// `git` as a substring — `shell_lex::git_subcommand` compares the program's
/// basename as a token — and these cases pin that, so a later rule cannot
/// introduce the substring match the report describes. See #6982 for where the
/// reported refusals actually come from.
/// Test: itself.
#[test]
fn git_inside_a_path_or_a_word_is_not_a_git_command() {
    for command in [
        // AC (a): the only `git` is a directory name.
        "for f in crates/trusty-git-analytics/src/collect/jira/*.rs; do printf '%s' \"$f\"; done",
        "ls crates/trusty-git-analytics/src",
        "rg --files crates/trusty-git-analytics | head",
        // `git` as a substring of another word, and inside a flag name.
        "echo digit legit gitignore",
        "grep -n legit crates/trusty-git-analytics/README.md",
        "cargo run -- --git-dir /tmp/x",
        "./scripts/check_line_cap.sh",
    ] {
        assert_eq!(
            evaluate_bash_command(command),
            None,
            "expected allow, the only `git` here is not in command position: {command}"
        );
    }
}

/// AC (c): a here-document body is DATA. [`split_shell_segments_raw`] frames it
/// (#6946), so a scratch script that merely mentions a git command is not one.
/// Test: itself.
#[test]
fn git_inside_a_heredoc_body_is_not_a_git_command() {
    for command in [
        "python3 - <<'PY'\nprint('git apply patch.diff')\nPY",
        "cat <<'EOF'\ngit apply patch.diff\nsed -i s/a/b/ f\nEOF",
        "python3 - <<'PY'\nif a > b:\n    print('git apply x')\nPY",
    ] {
        assert_eq!(
            evaluate_bash_command(command),
            None,
            "a here-document body is data, not syntax: {command}"
        );
    }
}

/// AC (b): the other direction. A real `git apply` in command position after
/// any composition operator still denies, so the token-position rule above is
/// not an escape hatch.
/// Test: itself.
#[test]
fn git_in_command_position_after_a_separator_still_denies() {
    for command in [
        "echo hi && git apply p.diff",
        "echo hi; git apply p.diff",
        "cat p.diff | git apply -",
        "echo hi || git apply p.diff",
        "true & git apply p.diff",
        "ls crates/trusty-git-analytics && git apply p.diff",
        "git -C crates/trusty-git-analytics apply p.diff",
    ] {
        assert_eq!(
            evaluate_bash_command(command),
            Some(SHELL_EDIT_REASON),
            "expected shell-edit deny for: {command}"
        );
    }
}

/// The expansion set [`resolve_target_path`] performs is what makes a leftover
/// `$NAME` meaningful, so the detector is pinned on both spellings (#7098,
/// #7100).
/// Test: itself.
#[test]
fn unexpanded_shell_variable_finds_both_spellings() {
    for (path, expected) in [
        ("/repo/$MAIN/.claude/worktrees/a", "$MAIN"),
        ("/repo/${MAIN}/wt", "${MAIN}"),
        ("$WT", "$WT"),
        ("/repo/a/${WORKTREE_ROOT}", "${WORKTREE_ROOT}"),
        ("/repo/$1/wt", "$1"),
    ] {
        assert_eq!(
            unexpanded_shell_variable(Path::new(path)).as_deref(),
            Some(expected),
            "path: {path}"
        );
    }
}

/// A path with nothing left to expand — including a directory literally called
/// `$` — must not read as carrying a variable.
/// Test: itself.
#[test]
fn unexpanded_shell_variable_is_none_for_ordinary_paths() {
    for path in [
        "/repo/.claude/worktrees/agent-x",
        "relative/path",
        "/repo/$",
        "/repo/$/wt",
        "/repo/${}/wt",
    ] {
        assert_eq!(
            unexpanded_shell_variable(Path::new(path)),
            None,
            "path: {path}"
        );
    }
}

/// A `~` reaches `resolve_target_path` as literal text whenever `$HOME` is
/// unset, survives as a path COMPONENT, and then reads as an ordinary relative
/// path joined onto the base — which is how the guard came to call an agent's
/// launch directory a main checkout (#7234). Both spellings a shell would
/// expand are pinned, and the refusal must quote the token AS WRITTEN rather
/// than the fabricated join.
/// Test: itself.
#[test]
fn unresolved_target_reports_a_surviving_tilde_as_written() {
    let no_home = PathEnv {
        tmpdir: None,
        tmp: None,
        home: None,
    };
    let base = Path::new("/launch/dir");
    for (token, expected_token, expected_shown) in [
        ("~/audit/repo", "~", "~/audit/repo"),
        ("~", "~", "~"),
        ("~bob/scratch", "~bob", "~bob/scratch"),
    ] {
        let resolved = resolve_target_path(token, base, &no_home);
        assert_eq!(
            resolved,
            base.join(token),
            "the join this rule exists to catch: {token}"
        );
        let unresolved =
            unresolved_target(&resolved).unwrap_or_else(|| panic!("must be unresolved: {token}"));
        assert_eq!(unresolved.token, expected_token, "token: {token}");
        assert_eq!(
            unresolved.shown,
            Path::new(expected_shown),
            "the refusal must not quote the launch directory: {token}"
        );
    }
}

/// The other half: with `$HOME` set the tilde expands, and an ordinary path
/// must not be reported unresolved — otherwise every `~`-written target would
/// deny with "cannot determine".
/// Test: itself.
#[test]
fn unresolved_target_is_none_once_home_expands_the_tilde() {
    let with_home = PathEnv {
        tmpdir: None,
        tmp: None,
        home: Some("/Users/bob".to_string()),
    };
    let resolved = resolve_target_path("~/audit/repo", Path::new("/launch/dir"), &with_home);
    assert_eq!(resolved, Path::new("/Users/bob/audit/repo"));
    assert!(
        unresolved_target(&resolved).is_none(),
        "an expanded tilde leaves nothing unresolved: {}",
        resolved.display()
    );
    for path in ["/repo/.claude/worktrees/agent-x", "/repo/a~b/c"] {
        assert!(
            unresolved_target(Path::new(path)).is_none(),
            "a `~` inside a component is not a tilde expansion: {path}"
        );
    }
}

/// #8572: a `$(…)` or backtick substitution survives resolution too, and
/// every rule asking [`unresolved_target`] must see it.
/// Test: itself.
#[test]
fn unresolved_target_reports_a_command_substitution() {
    let env = PathEnv {
        tmpdir: None,
        tmp: None,
        home: Some("/Users/bob".to_string()),
    };
    let base = Path::new("/repo/.claude/worktrees/agent-a");
    for (token, expected) in [
        ("$(cat /tmp/main)", "$("),
        ("`cat /tmp/main`", "`"),
        ("$(cat $MAIN)/sub", "$("),
    ] {
        let resolved = resolve_target_path(token, base, &env);
        let unresolved =
            unresolved_target(&resolved).unwrap_or_else(|| panic!("must be unresolved: {token}"));
        assert_eq!(unresolved.token, expected, "token: {token}");
        assert_eq!(unresolved.shown, resolved, "the whole path is quoted");
    }
}

/// Whether any composition segment of `command` runs `git` as its command
/// word — the question every git rule in this guard asks, resolved the way
/// the production path resolves it (#6982).
///
/// Why: the rules do not share one entry point, so a table over any single
/// rule would pin only that rule's verdict and would move whenever its policy
/// moved. Composing the two production pieces the rules DO share — the
/// quote-aware segment split and [`shell_lex::git_subcommand`] — pins the
/// position question itself: `git` counts when it is a segment's command word
/// and never when it is a substring of some other token.
/// What: splits on the composition operators, then asks each segment for its
/// git subcommand; `true` when any segment resolves one.
/// Test: `git_is_only_a_git_command_in_command_position`,
/// `git_in_command_position_is_still_a_git_command`.
fn command_runs_git(command: &str) -> bool {
    split_shell_segments(command)
        .iter()
        .any(|segment| shell_lex::git_subcommand(segment.trim()).is_some())
}

/// The allow side of #6982: `git` inside a longer token is not a git command.
///
/// Why: engineers in isolation worktrees reported `for` loops over
/// `crates/trusty-git-analytics/**` refused for "naming git". A classifier
/// that answered on the substring would deny every row here — a directory
/// name, a dotfile, a hostname, a word that merely contains the letters, and
/// a compound command quoted into prose.
/// What: asserts [`command_runs_git`] is `false` for each.
/// Test: itself.
#[test]
fn git_is_only_a_git_command_in_command_position() {
    for command in [
        // A path component, in the three shapes the issue reported.
        "ls crates/trusty-git-analytics/src",
        "for f in crates/trusty-git-analytics/src/*.rs; do printf '%s' \"$f\"; done",
        "cargo test -p trusty-git-analytics --no-fail-fast",
        // A dotfile whose name starts with the letters.
        "cat .gitignore",
        "grep -n target .gitignore",
        // A hostname that contains them.
        "echo https://github.com/bobmatnyc/trusty-tools",
        // A longer word that contains them.
        "printf '%s' digit-legit-gitignore",
        // Quoted prose — including a compound command quoted into an argument,
        // which the quote-aware split must not treat as syntax.
        "echo 'git status'",
        "echo \"cd x && git checkout -- .\"",
        // #6982 (2026-09-10): an argument whose TEXT contains the letters —
        // a grep pattern, a perl substitution, and a pgrep pattern inside a
        // command substitution. All three were refused by the harness with no
        // git command present anywhere.
        "grep -n 'git ls-remote' README.md",
        "perl -pi -e 's/gitlab/github/g' notes.md",
        "tm wait --for run --pid $(pgrep -f 'git-upload-pack')",
    ] {
        assert!(
            !command_runs_git(command),
            "no segment of this runs git as a command word: {command}"
        );
    }
}

/// The deny side of #6982: every position that IS a command word still counts.
///
/// Why: the allow side above is only safe if it narrows position, not
/// recognition. Each row here is a real git invocation the guard denied
/// before, in one of the positions a command word can occupy — first token of
/// a pipeline segment, after a composition operator, behind a wrapper or an
/// env-assignment prefix, or spelled as an absolute path.
/// What: asserts [`command_runs_git`] is `true` for each.
/// Test: itself.
#[test]
fn git_in_command_position_is_still_a_git_command() {
    for command in [
        // First token.
        "git worktree remove .claude/worktrees/agent-x",
        // After each composition operator.
        "cd crates/trusty-git-analytics && git checkout -- .",
        "echo a | git apply -",
        "true; git commit -m wip",
        "false || git reset --hard",
        // Behind a wrapper or an env-assignment prefix.
        "env git status",
        "sudo git clean -fdx",
        "command git apply -",
        "exec git reset --hard",
        "GIT_DIR=/tmp/x git status",
        // Spelled as an absolute path.
        "/usr/bin/git status",
        // A `-C` naming a path that itself contains the letters.
        "git -C crates/trusty-git-analytics apply p.diff",
        // #6982 (2026-09-10): the substitutes engineers reached for when the
        // harness refused a plain `git diff` are still git commands here, so
        // the rules that matter still see them.
        "git --no-pager diff --stat",
        "git -C /repo/.claude/worktrees/agent-x diff --stat",
        "git show 3350be5 -- crates/trusty-mpm/src/lib.rs",
    ] {
        assert!(
            command_runs_git(command),
            "git is the command word of a segment here: {command}"
        );
    }
}

/// Every command shape the Claude Code harness refused inside an isolation
/// worktree, as reported on #6982 between 2026-09-07 and 2026-09-10.
///
/// Why: the reports keep arriving in new forms rather than converging, and
/// each new form draws a fresh "fix the guard" dispatch to this repository.
/// One table naming the shapes, asserted against the guard that is actually
/// ours, is what settles that: a row here is evidence that `tm` clears the
/// shape, so the refusal came from the harness. The catalogue with the working
/// substitute for each row is `docs/reference/worktree-discipline.md`.
/// What: the literal commands, transcribed from the issue thread. Interpreter
/// heredocs carry real newlines because the guard frames heredoc bodies.
/// Test: `harness_refused_shapes_stay_classifiable_here`.
const HARNESS_REFUSED_SHAPES: &[&str] = &[
    // Read-only git, in the argument shapes reported: a three-dot range, a
    // `--cached` pathspec, a two-commit range, a `..` log range, an explicit
    // `-C`, the `--no-pager` workaround, a `$(git …)` pathspec, and a git
    // command inside BASE-AGENT's redirect-then-echo gate idiom.
    "git diff origin/main...HEAD --stat",
    // #7368: reported again as a too-narrow read-only-git allowlist here; this
    // guard has no `git diff` rule to widen, so the row joins the corpus.
    "git diff main..HEAD -- docs/",
    "git diff --cached -- crates/trusty-mpm/src/lib.rs",
    "git diff HEAD~2 HEAD -- crates/trusty-mpm/src/lib.rs",
    "git log origin/main..3350be5",
    "git -C . status --short",
    "git --no-pager diff --stat",
    "git grep -n fixture -- $(git diff --name-only origin/main...HEAD)",
    "git commit -F /tmp/msg.txt > /tmp/out.txt 2>&1; echo EXIT=$?",
    // A repo script invoked through an interpreter, relative and absolute.
    "bash scripts/check_line_cap.sh",
    "bash /repo/scripts/check_line_cap.sh",
    // An interpreter handed a program: as a file, as `-e`, and as a heredoc.
    "awk -f /tmp/prog.awk /tmp/build.log",
    "sed -f /tmp/prog.sed notes.md",
    "node -e 'console.log(1)'",
    "python3 - <<'PY'\nprint(1)\nPY",
    "awk -f /dev/stdin <<'AWK'\n{ print }\nAWK",
    "cat >> crates/trusty-mpm/tests/tools.rs <<'EOF'\nfn x() {}\nEOF",
    // Shell constructs: loops, a pipeline status read, an xargs pipe, a
    // variable-built path, an env assignment computed from `$PWD`, a `cd`
    // prefix, and a command substitution feeding an argument.
    "for f in crates/trusty-git-analytics/src/collect/jira/*.rs; do printf '%s\\n' \"$f\"; done",
    "for i in $(seq 20); do cargo test -p trusty-mpm; done",
    "for n in 102 124; do sed -n \"$((n - 8)),$((n + 8))p\" src/lib.rs; done",
    "cargo test -p trusty-mpm | tail -5; echo ${PIPESTATUS[0]}",
    "ls crates | xargs grep -l fixture",
    "sed -n '/running/,$p' \"$SP/full.txt\"",
    "export TD=/repo/target-worktree && cargo check -p trusty-mpm",
    "CARGO_TARGET_DIR=$PWD/target-worktree cargo check -p trusty-mpm",
    "cd /repo/.claude/worktrees/agent-x && git diff --stat",
    "S=/repo/fixtures && ./tm hook --pm-guard < $S/p1.json",
    "tm wait --for run --pid $(pgrep -f cargo)",
    // An argument whose text merely contains `git`, with no git command.
    "grep -n 'git ls-remote' README.md",
    "perl -pi -e 's/gitlab/github/g' notes.md",
];

/// #6982: the guard can say what each harness-refused shape would run.
///
/// Why: the harness refuses these as "too complex to verify that it stays
/// inside the worktree" and "cannot be shown not to be git" — the same
/// question [`unclassifiable_command`] answers, from the ABSOLUTE band a
/// dispatched subagent actually reaches. A `None` here is the whole finding of
/// this issue in mechanical form: the shape is classifiable, so a further fix
/// routed to this guard would be routed to the wrong codebase.
/// What: asserts [`unclassifiable_command`] is `None` for every row of
/// [`HARNESS_REFUSED_SHAPES`].
/// Test: itself.
#[test]
fn harness_refused_shapes_stay_classifiable_here() {
    for command in HARNESS_REFUSED_SHAPES {
        assert_eq!(
            unclassifiable_command(command),
            None,
            "the harness refused this as unverifiable; this guard must still \
             establish what it runs: {command:?}"
        );
    }
}

/// #6982: `$'…'` is the one reported shape this guard also refuses.
///
/// Why: the catalogue above would read as "the harness is wrong about
/// everything" without this row. `$'…'` quoting is refused here too, for a
/// reason of our own that predates the issue (#6660): the lexer cannot decode
/// it, so `sh -c $'git worktree remove x'` reads as `$git` and matches no
/// rule. An engineer who hits it in a worktree should rewrite the quoting
/// rather than report it as another harness misfire.
/// What: asserts the ANSI-C row denies with [`ANSI_C_QUOTING_REASON`] while a
/// plain-quoted spelling of the same command classifies.
/// Test: itself.
#[test]
fn ansi_c_quoting_is_refused_by_this_guard_too() {
    assert_eq!(
        unclassifiable_command(r"grep -n $'\tfixture' README.md"),
        Some(ANSI_C_QUOTING_REASON)
    );
    assert_eq!(
        unclassifiable_command(r"grep -n '\tfixture' README.md"),
        None
    );
}

/// #7368: every read-only `git diff` spelling the issue reports is allowed.
///
/// Why: the issue reads the refusal of `git diff main..HEAD -- docs/` as a
/// too-narrow read-only-git allowlist here. This guard has no `git diff` rule
/// to widen — it classifies `git` by subcommand and only `apply` denies — so
/// the rows below already pass and the refusal belongs to the
/// [`HARNESS_REFUSED_SHAPES`] family instead. The table is the mechanical form
/// of that finding, and it stops a later rule from quietly denying a read.
/// What: asserts both bands answer allow — [`unclassifiable_command`], the
/// ABSOLUTE band a dispatched subagent reaches, and [`evaluate_bash_command`],
/// the PM classifier.
/// Test: itself.
#[test]
fn readonly_git_diff_pathspecs_are_allowed() {
    for command in [
        "git diff main..HEAD -- docs/",
        "git diff origin/main..HEAD -- docs/",
        "git diff origin/main...HEAD -- docs/",
        "git diff --stat main..HEAD -- docs/",
        "git diff --cached -- docs/",
        "git diff HEAD~2 HEAD -- docs/",
        "git --no-pager diff main..HEAD -- docs/",
        "git -C /repo diff main..HEAD -- docs/",
    ] {
        assert_eq!(
            unclassifiable_command(command),
            None,
            "read-only diff must stay classifiable: {command}"
        );
        assert_eq!(
            evaluate_bash_command(command),
            None,
            "read-only diff must stay allowed: {command}"
        );
    }
}

/// #7374: a quoted command path with spaces gets the unquoted decision.
///
/// Why: the guard read `"/Applications/Google Chrome.app/…/Google Chrome"` as
/// the fragment `Google`, because the command name was resolved by
/// `split_whitespace`. The space-free control row is what makes this a claim
/// about AGREEMENT rather than about one string.
/// What: asserts the issue's literal command allows, in both quote spellings,
/// and that the equivalent space-free path allows too.
/// Test: itself.
#[test]
fn a_quoted_command_path_with_spaces_gets_the_unquoted_decision() {
    let unquoted = "/Applications/GoogleChrome.app/Contents/MacOS/GoogleChrome --headless";
    for command in [
        r#""/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --headless"#,
        r#"'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --headless"#,
    ] {
        assert_eq!(unclassifiable_command(command), None, "{command}");
        assert_eq!(
            evaluate_bash_command(command),
            evaluate_bash_command(unquoted),
            "quoted and unquoted spellings must agree: {command}"
        );
        assert_eq!(evaluate_bash_command(command), None, "{command}");
    }
}

/// #7374: no quoting spelling buys a forbidden verb an exemption.
///
/// Why: the fix is "resolve the program bash would exec", not "strip quotes and
/// allow". Three spellings were slipping the deny for the same reason — a
/// quoted path read as `My`, split quoting read as the literal `s"e"d`, a
/// backslash-escaped space read as `my\` — and each is closed by lexing rather
/// than by naming the spelling.
/// What: asserts every spelling denies with its own reason, and that the
/// false-DENY direction — a benign program under a directory named `make` —
/// now allows.
/// Test: itself.
#[test]
fn a_quoted_path_to_a_forbidden_verb_is_still_refused() {
    for command in [
        r#""/Applications/My Tools/sed" -i s/a/b/ f"#,
        r#"'/Applications/My Tools/patch' -p1 x"#,
        r#""/Applications/My Tools/awk" -i inplace '{print}' f"#,
        // #7374 round 2: split across adjacent quote fragments, and a
        // backslash-escaped space — both invisible to a whitespace scan.
        r#"s"e"d -i s/a/b/ f"#,
        r#"'se'"d" -i s/a/b/ f"#,
        r#""se"'d' -i s/a/b/ f"#,
        r"/opt/my\ tools/sed -i x f",
    ] {
        assert_eq!(
            evaluate_bash_command(command),
            Some(SHELL_EDIT_REASON),
            "a quoted path must not hide the verb: {command}"
        );
    }
    assert_eq!(
        evaluate_bash_command(r#"c"u"rl http://x"#),
        Some(NETWORK_REASON)
    );
    assert_eq!(
        evaluate_bash_command(r#""/opt/My Tools/npm" test"#),
        Some(BUILD_TEST_REASON)
    );
    assert_eq!(
        evaluate_bash_command(r#"n"p"m test"#),
        Some(BUILD_TEST_REASON)
    );
    assert_eq!(evaluate_bash_command(r#""/opt/make tools/echo" hi"#), None);
}

/// #7399: a git `--output` option writes a file and is refused as one.
///
/// Why: `git diff --output=/tmp/o.diff` puts the same bytes on disk that
/// `git diff > /tmp/o.diff` does, but carries no `>`, so
/// [`has_file_write_redirection`] never saw it and the write boundary
/// (ADR-0044, ADR-0048) had a hole a PM could walk through. `--output` is a
/// git DIFF option, so the rows below cover every subcommand that generates a
/// diff, both spellings git accepts, and the wrapper and global-flag
/// positions that hid other git verbs before.
/// What: asserts each spelling denies with [`SHELL_EDIT_REASON`] — the same
/// reason a `>` redirection denies with — and that the denial names the file,
/// so the routing hint points at the written path rather than falling back.
/// Test: itself.
#[test]
fn git_diff_output_flag_is_refused_as_a_file_write() {
    for command in [
        "git diff --output=/tmp/o.diff",
        "git diff --output=/tmp/o.diff origin/main...HEAD",
        "git diff --output /tmp/o.diff origin/main...HEAD",
        "git diff origin/main...HEAD --output=/tmp/o.diff -- docs/",
        "git --no-pager diff --output=/tmp/o.diff",
        "git -C /repo diff --output /tmp/o.diff",
        "git log -1 --output=/tmp/log.txt",
        "git show HEAD --output=/tmp/show.txt",
        "git format-patch -1 --output=/tmp/p.patch",
        r#"git diff --output="/tmp/my out.diff""#,
        "sh -c 'git diff --output=/tmp/o.diff'",
        "cargo check -p trusty-mpm && git diff --output=/tmp/o.diff",
    ] {
        assert_eq!(
            evaluate_bash_command(command),
            Some(SHELL_EDIT_REASON),
            "a git --output option is a file write: {command}"
        );
    }
    assert_eq!(
        extract_shell_edit_target("git diff --output=/tmp/o.diff"),
        Some("/tmp/o.diff".to_string())
    );
    assert_eq!(
        extract_shell_edit_target("git diff --output /tmp/o.diff HEAD"),
        Some("/tmp/o.diff".to_string())
    );
}

/// #7399 round 2: `-o`, `--output-directory` and `bundle create` write too.
///
/// Why: the round-1 rule matched only `--output`, and a critic ran the three
/// gaps against git 2.54.0 in a scratch repo: `git format-patch -o <dir> -1
/// HEAD` wrote `0001-init.patch`, `git format-patch --output-directory=<dir>
/// -1 HEAD` wrote a patch, `git archive -o <file> HEAD` wrote a 10KB tar. Two
/// more writes carry no option at all — a bare `git format-patch` drops patch
/// files into the working directory, and `git bundle create <file>` names its
/// output as a positional.
/// What: asserts every write spelling denies with [`SHELL_EDIT_REASON`], and
/// that the read-only siblings still allow — `--stdout`, an archive to stdout,
/// `git diff -o` (a revision there), and `git clone -o` (the origin remote).
/// Test: itself.
#[test]
fn git_short_output_options_are_refused_as_file_writes() {
    for command in [
        "git format-patch -o /tmp/d -1 HEAD",
        "git format-patch -1 -o/tmp/d HEAD",
        "git format-patch --output-directory=/tmp/d -1 HEAD",
        "git format-patch --output-directory /tmp/d -1 HEAD",
        "git format-patch -1 HEAD",
        "git archive -o /tmp/a.tar HEAD",
        "git archive -o/tmp/a.tar HEAD",
        "git archive --output=/tmp/a.tar HEAD",
        "git bundle create /tmp/x.bundle HEAD",
        "git bundle create -q /tmp/x.bundle --all",
        "git -C /repo format-patch -o /tmp/d -1 HEAD",
        "sh -c 'git archive -o /tmp/a.tar HEAD'",
    ] {
        assert_eq!(
            evaluate_bash_command(command),
            Some(SHELL_EDIT_REASON),
            "a git write option is a file write: {command}"
        );
    }
    for command in [
        "git format-patch --stdout -1 HEAD",
        "git format-patch -1 HEAD --stdout",
        "git archive --format=tar HEAD | tar -t",
        "git bundle create - HEAD",
        "git bundle verify /tmp/x.bundle",
        "git diff -o /tmp/o.diff HEAD",
        "git clone -o upstream https://x/y.git",
    ] {
        assert_eq!(
            evaluate_bash_command(command),
            None,
            "a read-only spelling must stay allowed: {command}"
        );
    }
    assert_eq!(
        extract_shell_edit_target("git archive -o /tmp/a.tar HEAD"),
        Some("/tmp/a.tar".to_string())
    );
}

/// #7399: the read-only `git diff` shapes stay allowed beside that deny.
///
/// Why: the deny above must match the OPTION, not its prefix.
/// `--output-indicator-new=+` changes one character of the patch body and
/// writes nothing; a `--output=…` past the `--` separator is a pathspec git
/// never parses as an option (verified against git 2.x — no file appears).
/// `git diff --no-index a b` between two readable paths is a pure read and is
/// the shape #7368 already pinned as allowed.
/// What: asserts each row still allows, in both bands —
/// [`unclassifiable_command`] and [`evaluate_bash_command`].
/// Test: itself.
#[test]
fn git_diff_read_only_shapes_survive_the_output_deny() {
    for command in [
        "git diff --no-index /tmp/a.txt /tmp/b.txt",
        "git diff --stat",
        "git diff -- docs/",
        "git diff --output-indicator-new=+",
        "git diff --output-indicator-old=- --stat main..HEAD",
        "git diff -- --output=/tmp/o.diff",
        "git log --oneline -5",
        "git show HEAD --stat",
    ] {
        assert_eq!(
            unclassifiable_command(command),
            None,
            "read-only diff must stay classifiable: {command}"
        );
        assert_eq!(
            evaluate_bash_command(command),
            None,
            "read-only diff must stay allowed: {command}"
        );
    }
}

/// #7399: a git segment the guard cannot lex loses no existing deny.
///
/// Why: the `--output` rule reads its answer from a shlex split, which fails
/// on unbalanced quotes. The failure direction must be "no NEW deny", never
/// "an existing deny becomes an allow" — a bypass that would be worse than
/// the hole being closed.
/// What: asserts the unlexable spellings of already-denied shapes still deny,
/// and that the unlexable `--output` spelling is merely no worse than before
/// the fix (it allows here, as it did before, and bash refuses to run an
/// unterminated quote at all).
/// Test: itself.
#[test]
fn an_unlexable_git_segment_keeps_every_deny_it_already_had() {
    assert_eq!(
        evaluate_bash_command("git diff '/tmp/o.diff > /tmp/w.diff"),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        evaluate_bash_command("sed -i s/a/b/ '/tmp/f.rs"),
        Some(SHELL_EDIT_REASON)
    );
    assert_eq!(
        shell_lex::git_file_write_target("git diff --output='/tmp/o.diff"),
        None,
        "an unbalanced segment withholds the new deny rather than granting one"
    );
    assert_eq!(
        shell_lex::git_file_write_target("git archive -o '/tmp/a.tar"),
        None,
        "the round-2 spellings inherit the same withhold-only failure"
    );
}

// #7399: the write boundary decides on `shell_write_targets`, so a redirect
// and a git write option must both resolve to the file they name.
#[test]
fn shell_write_targets_reads_redirects_and_git_output() {
    for (command, target) in [
        ("echo hi > /tmp/o.diff", "/tmp/o.diff"),
        ("cat a >> /tmp/o.diff", "/tmp/o.diff"),
        ("git diff --output=/tmp/o.diff HEAD~1 HEAD", "/tmp/o.diff"),
        ("git diff --output /tmp/o.diff HEAD", "/tmp/o.diff"),
        ("git -C /repo log -1 --output=/tmp/l.txt", "/tmp/l.txt"),
        ("git show HEAD --output=/tmp/s.txt", "/tmp/s.txt"),
        ("git format-patch -o /tmp/d -1 HEAD", "/tmp/d"),
        ("git archive -o /tmp/a.tar HEAD", "/tmp/a.tar"),
        ("git bundle create /tmp/x.bundle HEAD", "/tmp/x.bundle"),
        (
            "cargo check -p trusty-mpm && git diff --output=/tmp/o.diff",
            "/tmp/o.diff",
        ),
    ] {
        assert_eq!(
            shell_write_targets(command),
            Ok(vec![target.to_string()]),
            "{command}"
        );
    }
}

// #7399: the boundary must not deny a read. Everything here either writes
// nothing or names its file in a position that can also be a read.
#[test]
fn shell_write_targets_ignores_reads() {
    for command in [
        "git diff HEAD~1 HEAD",
        "git diff --no-index /tmp/a.txt /tmp/b.txt",
        "git diff --stat -- docs/",
        "git diff --output-indicator-new=+",
        "git format-patch --stdout -1 HEAD",
        "git bundle create - HEAD",
        "cargo test -p trusty-mpm 2>&1",
        "echo hi > /dev/null",
        // The sed/awk trailing token is a routing HINT, never a write the
        // boundary may act on: `sed -n` only reads this file.
        "sed -n '1,5p' /tmp/f.rs",
        "git apply /tmp/f.patch",
        // Unlexable: withholds, never invents, a target.
        "git diff --output='/tmp/o.diff",
    ] {
        assert!(
            shell_write_targets(command).is_ok_and(|t| t.is_empty()),
            "{command} -> {:?}",
            shell_write_targets(command)
        );
    }
    // A write that names no readable path still denies through
    // `classify_bash_segment`; it just gives the boundary nothing to place.
    assert_eq!(shell_write_targets("git diff --output"), Ok(Vec::new()));
    assert_eq!(
        evaluate_bash_command("git diff --output"),
        Some(SHELL_EDIT_REASON)
    );
}

// #8468 option B: every composition segment that names a write must be
// judged, not only the first one found across the whole command. Before the
// fix, a benign first write (`notes.md`) hid a later source write
// (`crates/x/src/lib.rs`) from the boundary entirely.
#[test]
fn shell_write_targets_collects_every_segments_write() {
    assert_eq!(
        shell_write_targets("echo hi > notes.md && echo bye > crates/x/src/lib.rs"),
        Ok(vec![
            "notes.md".to_string(),
            "crates/x/src/lib.rs".to_string()
        ])
    );
    // A `cd` segment's own redirect is a write like any other segment's.
    assert_eq!(
        shell_write_targets("cd . > crates/x/src/lib.rs"),
        Ok(vec!["crates/x/src/lib.rs".to_string()])
    );
}

// #7399 review, HIGH: `redirection_target` was the one copy of the redirect
// scan that never learned #5356's heredoc skip, and `split_shell_segments_raw`
// keeps the operator line, the body and the terminator as ONE segment (#6946).
// A `>` in here-document PROSE would therefore have named a write target and
// driven a hard ADR-0044 deny on a command that writes nothing.
#[test]
fn shell_write_targets_ignores_a_heredoc_body_redirect() {
    for command in [
        "cat <<'EOF'\nsee: git diff > crates/x/src/lib.rs\nEOF",
        "python3 <<'PY'\nprint([k for k in d if len(k) > 3])\nPY",
        "cat <<EOF\nthe pipeline is read -> parse -> write\nEOF",
    ] {
        assert_eq!(shell_write_targets(command), Ok(Vec::new()), "{command}");
        assert_eq!(extract_shell_edit_target(command), None, "{command}");
        assert_eq!(evaluate_bash_command(command), None, "{command}");
    }
    // The skip must not fail open: only the BODY is data. A redirect on the
    // operator line, or after the terminator, still names its file — the
    // mirror of `has_file_write_redirection_detects_redirect_on_a_heredoc_operator_line`.
    assert_eq!(
        shell_write_targets("python3 <<'PY' > out.rs\nprint(1)\nPY"),
        Ok(vec!["out.rs".to_string()])
    );
    assert_eq!(
        shell_write_targets("python3 <<'PY'\nprint(1)\nPY\necho done > f.rs"),
        Ok(vec!["f.rs".to_string()])
    );
}

// ── #7497: the disk-usage half of the worktree-add gate ──────────────────────

/// Why (#7497): the disk rule reads the SAME targets the temp-root rule does,
///      so the shared resolver has to survive `cd` and `git -C` intact.
/// What: both forms resolve to the same absolute target, and a relative target
///      resolves against the hook's working directory.
/// Test: this test.
#[test]
fn worktree_add_targets_resolves_cd_and_dash_c() {
    let cwd = Path::new("/projects/example-repo");
    assert_eq!(
        worktree_add_targets("cd /srv/base && git worktree add wt-foo", cwd),
        vec![PathBuf::from("/srv/base/wt-foo")]
    );
    assert_eq!(
        worktree_add_targets("git -C /srv/base worktree add wt-foo", cwd),
        vec![PathBuf::from("/srv/base/wt-foo")]
    );
    assert_eq!(
        worktree_add_targets("git worktree add .claude/worktrees/wt-x", cwd),
        vec![PathBuf::from(
            "/projects/example-repo/.claude/worktrees/wt-x"
        )]
    );
}

/// Why (#7497): gating `list`/`remove`/`prune` would block reading and cleanup
///      on exactly the full disk where an operator needs both most.
/// What: no `worktree add` means no targets, so nothing is measured and nothing
///      can be denied.
/// Test: this test.
#[test]
fn worktree_list_and_remove_produce_no_disk_targets() {
    let cwd = Path::new("/projects/example-repo");
    for cmd in [
        "git worktree list",
        "git worktree remove .claude/worktrees/wt-x",
        "git worktree prune",
        "cargo test -p trusty-mpm",
    ] {
        assert!(
            worktree_add_targets(cmd, cwd).is_empty(),
            "`{cmd}` must not be gated on disk usage"
        );
    }
}

/// Why (#7497): the rule must not sample the disk for the overwhelming
///      majority of Bash calls, which create no worktree.
/// What: an empty target list never invokes the measurement closure.
/// Test: this test.
#[test]
fn no_targets_means_no_measurement() {
    let called = std::cell::Cell::new(false);
    let reason = super::disk_usage::refusal_for_targets(&[], |_| {
        called.set(true);
        Some("denied".to_string())
    });
    assert!(reason.is_none());
    assert!(!called.get(), "an empty target list must measure nothing");
}

/// Why (#7497): a command can add several worktrees; the first one that would
///      overfill the disk has to stop the whole call.
/// What: the second target refuses, and that refusal is what comes back.
/// Test: this test.
#[test]
fn the_first_refusing_target_wins() {
    let targets = vec![PathBuf::from("/ok/wt-a"), PathBuf::from("/full/wt-b")];
    let reason = super::disk_usage::refusal_for_targets(&targets, |p| {
        p.starts_with("/full").then(|| "over threshold".to_string())
    });
    assert_eq!(reason.as_deref(), Some("over threshold"));
}

/// #8439: `classify_bash_segment` and the worktree-add walker do not read an
/// unknown git global option as "not this verb" — every later token is a
/// candidate subcommand, so the deny still fires.
/// Test: itself.
#[test]
fn an_unknown_git_global_option_does_not_hide_a_denied_verb() {
    for command in [
        "git --shallow-file x apply p.diff",
        "git --shallow-file status diff --output=/tmp/o.diff",
    ] {
        assert!(
            evaluate_bash_command(command).is_some(),
            "must deny: {command}"
        );
    }
    assert_eq!(
        extract_shell_edit_target("git --shallow-file x diff --output=/tmp/o.diff").as_deref(),
        Some("/tmp/o.diff")
    );
    assert_eq!(
        evaluate_worktree_add_command(
            "git --shallow-file x worktree add /tmp/wt",
            Path::new("/Users/x/proj")
        ),
        Some(WORKTREE_TMP_REASON)
    );
}