iron-shell 14.0.3

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
//! Safety core for IronShell's agentic-first design.
//!
//! Implements the capability → policy → approval → audit model from
//! `docs/AGENTIC_FIRST_DESIGN.md` (§5.3, §7). Every effecting builtin can route
//! through [`guard`], which:
//!
//! 1. classifies the call by [`Effect`] (the effect taxonomy),
//! 2. enforces the workspace jail for filesystem-effecting classes,
//! 3. consults the active [`Policy`] for the current [`Mode`] to get a
//!    [`Decision`] (allow / deny / approve),
//! 4. resolves `approve` against supplied/granted approval tokens, and
//! 5. appends a tamper-evident entry to the hash-chained audit log.
//!
//! ## Default behaviour
//!
//! Defaults preserve the human REPL exactly (default-allow, no audit file) while
//! the agent surface is default-deny for the dangerous effect classes. Mode is
//! selected by `IRONSHELL_MODE=agent` (or `IRONSHELL_AGENT=1`); everything else is
//! human mode. This means existing scripts and tests are unaffected unless they
//! opt into agent mode.
//!
//! | Effect        | Human  | Agent    |
//! |---------------|--------|----------|
//! | Pure          | allow  | allow    |
//! | ReadLocal     | allow  | allow    |
//! | WriteLocal    | allow  | allow*   | (* jailed to workspace)
//! | Network       | allow  | approve† |
//! | Process       | allow  | approve  |
//! | Destructive   | allow  | approve* | (* jailed to workspace)
//! | Exec          | allow  | approve  |
//! | Privileged    | allow  | deny     |
//!
//! † `allow` once `IRONSHELL_NET_ALLOW` names destinations. `decide()` returns
//! the table's answer; `effective_decision()`, which `guard` applies, asks for
//! approval for `Network` in agent mode until an allowlist is set.
//!
//! `IRONSHELL_POLICY=permissive` makes agent mode behave like human mode (allow
//! all) for trusted automation; `IRONSHELL_POLICY=strict` is the default.

use ironcrypto::core_types::traits::Digest as _;
use ironcrypto::hash::Sha256;
use lazy_static::lazy_static;
use serde_json::{json, Value as Json};
use std::collections::HashSet;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Mutex;

const GENESIS_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000";

// ════════════════════════════════════════════════════════════════════════
// Effect taxonomy (§5.3)
// ════════════════════════════════════════════════════════════════════════

/// The effect class of a builtin — the single property the safety model reasons
/// about. Travels with the builtin so every surface (REPL, API, MCP, agent) is
/// gated identically.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Effect {
    /// No observable effect (math, string ops, pure transforms).
    Pure,
    /// Reads local state (filesystem reads, process listing, env).
    ReadLocal,
    /// Creates or modifies local state non-destructively (file write, mkdir).
    WriteLocal,
    /// Irreversibly removes or overwrites local state (rm, truncate, db delete).
    Destructive,
    /// Affects other processes (kill, signal).
    Process,
    /// Performs network I/O.
    Network,
    /// Executes an arbitrary external command (shell passthrough).
    Exec,
    /// Requires elevated privileges or affects system-wide state.
    Privileged,
}

impl Effect {
    /// Whether re-running an operation of this class is safe after an ambiguous
    /// failure — a timeout, a dropped connection, a killed process — where the agent
    /// cannot tell whether the first attempt took effect.
    ///
    /// This is a different question from [`ErrorCode::retryable`], which describes
    /// the *error*: a network timeout is a retryable error, but re-issuing the POST
    /// behind it may charge a card twice. An agent needs both, and conflating them
    /// is how duplicate side effects happen.
    ///
    /// Deliberately conservative — only `Pure` and `ReadLocal` are safe by class,
    /// and everything else must opt in per builtin via [`idempotent`]. The asymmetry
    /// is intentional: a false "unsafe" costs one stalled retry, a false "safe"
    /// costs a duplicated effect that cannot be taken back.
    pub fn retry_safe_by_class(&self) -> bool {
        matches!(self, Effect::Pure | Effect::ReadLocal)
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Effect::Pure => "pure",
            Effect::ReadLocal => "read_local",
            Effect::WriteLocal => "write_local",
            Effect::Destructive => "destructive",
            Effect::Process => "process",
            Effect::Network => "network",
            Effect::Exec => "exec",
            Effect::Privileged => "privileged",
        }
    }

    /// Whether this effect touches the local filesystem in a way that must be
    /// confined to the workspace jail.
    pub fn is_filesystem(&self) -> bool {
        matches!(self, Effect::WriteLocal | Effect::Destructive)
    }
}

/// Whether FIPS-strict mode is active (`IRONSHELL_FIPS` ∈ {`1`,`on`,`true`}). In FIPS
/// mode, non-FIPS-approved cryptographic algorithms (MD5, SHA-1) are refused, so any
/// security-relevant operation uses only FIPS-approved algorithms (SHA-2 family).
/// Note: this enforces *approved-algorithm-only* at the application layer; it does
/// not by itself make the underlying crypto a FIPS-140-*validated* module (see
/// `docs/security/CRYPTO_AND_FIPS.md`).
pub fn fips_enabled() -> bool {
    std::env::var("IRONSHELL_FIPS")
        .map(|v| {
            let v = v.trim();
            v.eq_ignore_ascii_case("1")
                || v.eq_ignore_ascii_case("on")
                || v.eq_ignore_ascii_case("true")
        })
        .unwrap_or(false)
}

/// Reject a non-FIPS-approved hash algorithm when FIPS mode is active. Returns an
/// `E_FIPS_DISALLOWED` error for `md5`/`sha1`; approved algorithms (and all calls
/// when FIPS mode is off) pass through. Pure aside from reading the FIPS flag.
pub fn require_fips_hash(algo: &str) -> anyhow::Result<()> {
    if fips_enabled() && is_weak_hash(algo) {
        // The builtin name is left empty: `ensure_structured` fills it in at the
        // boundary, as it does for `arg_err`.
        return Err(anyhow::Error::new(SafetyError {
            code: ErrorCode::FipsDisallowed,
            message: format!(
                "hash algorithm '{algo}' is not FIPS-approved (IRONSHELL_FIPS active)"
            ),
            builtin: String::new(),
            hint: "use sha256, sha384 or sha512; MD5 and SHA-1 are refused in FIPS mode"
                .to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: "a FIPS-approved hash algorithm".to_string(),
            got: algo.to_string(),
            extra: serde_json::Map::new(),
        }));
    }
    Ok(())
}

/// Whether `algo` names a non-FIPS-approved (legacy/broken) hash: MD5 or SHA-1.
pub fn is_weak_hash(algo: &str) -> bool {
    matches!(
        algo.trim().to_ascii_lowercase().as_str(),
        "md5" | "sha1" | "sha-1"
    )
}

/// Best-effort classifier for a builtin name, used by the ontology and audit
/// when an explicit [`Effect`] was not supplied at the call site. Conservative:
/// known-dangerous names are classified precisely; unknown names default to
/// [`Effect::Pure`] (callers that need gating pass the effect explicitly).
/// Whether re-running `name` after an ambiguous failure is safe — i.e. whether the
/// operation is idempotent, not whether the error was transient.
///
/// Most builtins inherit the answer from their effect class (see
/// [`Effect::retry_safe_by_class`]). The list below is the opt-in for
/// side-effecting builtins that are nonetheless idempotent because they express a
/// *desired end state* rather than an increment: writing a whole file, creating a
/// directory that may exist, deleting something already gone. Each is safe because
/// running it twice leaves the same state as running it once.
///
/// Anything absent is reported unsafe. That is the honest default for a table this
/// large — an unlisted builtin means "nobody has established that this is
/// idempotent", which is exactly what an agent should assume.
pub fn idempotent(name: &str) -> bool {
    // End-state writes: the content is fully specified, so a repeat is a no-op.
    const END_STATE: &[&str] = &[
        "write_file",
        "write_json",
        "text_write",
        "save_json",
        "fs_write",
        "mkdir",
        "fs_mkdir",
        "create_dir",
        "chmod",
        "fs_chmod",
        "chown",
        "fs_chown",
        "symlink",
        "fs_symlink",
    ];
    // Removals: the second attempt finds nothing to remove and converges.
    const REMOVALS: &[&str] = &[
        "rm",
        "remove_file",
        "fs_remove",
        "delete_file",
        "rmdir",
        "remove_dir",
        "kubectl_delete",
        "svc_delete",
        "role_delete",
        "delete_role",
    ];
    if END_STATE.contains(&name) || REMOVALS.contains(&name) {
        return true;
    }
    // Reads over the network are safe to repeat; writes over it are the canonical
    // non-idempotent case, so `Network` as a class does not qualify.
    if name.starts_with("http_get") || name.starts_with("web_get") {
        return true;
    }
    effect_of(name).retry_safe_by_class()
}

/// The effect a builtin declares, falling back to [`Effect::Pure`].
///
/// **A `Pure` from this function is not a finding.** It is either a
/// classification or the fall-through, and the two are indistinguishable here
/// by design — every caller that only needs to gate an action wants the
/// conservative answer without caring which. Callers that report the effect to
/// an *agent* should ask [`effect_is_declared`] as well, so a builtin nobody
/// has classified is not advertised with the same confidence as one that was
/// read and found pure.
pub fn effect_of(name: &str) -> Effect {
    // A manifest builtin runs arbitrary IronShell, which this classifier
    // cannot see into. It takes the strictest class that is centrally enforced
    // (agent mode needs approval per call), and each builtin its body calls is
    // still guarded as it runs. Checked before the cache, because it changes
    // with plugin_load and plugin_unload.
    if crate::plugins::is_manifest_builtin(name) {
        return Effect::Exec;
    }
    // Every builtin call asks this at least once. `classified_effect` is a
    // string match of about a thousand arms, and the answer is a pure function
    // of the name, so it is computed once per name per thread.
    thread_local! {
        static CACHE: std::cell::RefCell<rustc_hash::FxHashMap<String, Effect>> =
            std::cell::RefCell::new(rustc_hash::FxHashMap::default());
    }
    if let Some(e) = CACHE.with(|c| c.borrow().get(name).copied()) {
        return e;
    }
    let e = classified_effect(name)
        .or_else(|| inherited_effect(name))
        .unwrap_or(Effect::Pure);
    CACHE.with(|c| {
        c.borrow_mut().insert(name.to_string(), e);
    });
    e
}

/// How strictly an effect is treated, for picking between siblings.
///
/// This orders *enforcement*, not danger: the four classes
/// [`centrally_enforced`] gates rank above the three it lets through, so
/// inheriting always picks the answer that keeps a gate rather than the one that
/// removes it. Within each band the order is the enum's own.
fn severity(effect: Effect) -> u8 {
    match effect {
        Effect::Pure => 0,
        Effect::ReadLocal => 1,
        Effect::WriteLocal => 2,
        Effect::Network => 3,
        Effect::Process => 4,
        Effect::Destructive => 5,
        Effect::Exec => 6,
        Effect::Privileged => 7,
    }
}

lazy_static! {
    /// The effect a name inherits from the other spellings of its own
    /// implementation.
    ///
    /// Dispatch is by implementation; classification is by name. `lldb_run` and
    /// `lldb` are one dispatch index, `vault_convert` and `vault-convert` are one
    /// match arm — and only one spelling of each was ever classified. The other
    /// read as `Pure`, `centrally_enforced(Pure)` is false, so
    /// [`guard_dispatch`] returned `Ok` before any policy ran and, because the
    /// audit line covers only `WriteLocal`/`Network`, left no trace either.
    ///
    /// Measured, not argued: 104 alias groups disagreed with themselves, 26 of
    /// them produced *different guard decisions* for the same implementation, and
    /// `lldb` ran an external debugger to completion in agent mode one call after
    /// `lldb_run` was refused for requiring approval.
    ///
    /// Built from `builtins::alias_groups`, so it cannot drift from the
    /// dispatcher the way a hand-written alias list would. A name classified in
    /// its own right is untouched — this only fills the fall-through, and it
    /// fills it with the strictest classification any sibling carries, because
    /// the failure that matters is a gate that quietly is not there.
    static ref INHERITED_EFFECT: std::collections::HashMap<&'static str, Effect> = {
        let mut map = std::collections::HashMap::new();
        for group in crate::builtins::alias_groups() {
            let strictest = group
                .iter()
                .filter_map(|n| classified_effect(n))
                .max_by_key(|e| severity(*e));
            let Some(strictest) = strictest else { continue };
            for name in group {
                if classified_effect(name).is_none() {
                    map.insert(name, strictest);
                }
            }
        }
        map
    };
}

fn inherited_effect(name: &str) -> Option<Effect> {
    INHERITED_EFFECT.get(name).copied()
}

/// Whether [`effect_of`]'s answer came from a rule rather than the fall-through.
///
/// A rule the name inherited from another spelling of its own implementation
/// counts: `lldb` is not classified in its own right, but `lldb_run` is, and
/// they are one dispatch index — the label `lldb` now carries was reasoned
/// about, just under the other name.
///
/// This is a claim about what has been *looked at*, which is weaker than a
/// claim that the rest do not act: that one belongs to the body-evidence
/// ratchet (`tests/effect_ratchet.rs`), which reports zero builtins acting while
/// classified `Pure` across both halves of the dispatcher. Agents deciding
/// whether to trust a label deserve to know which of the two they are reading.
pub fn effect_is_declared(name: &str) -> bool {
    classified_effect(name).is_some() || inherited_effect(name).is_some()
}

fn classified_effect(name: &str) -> Option<Effect> {
    match name {
        // Native regex substitution only: no process or file access.
        "sd_replace" => Some(Effect::Pure),
        // Pairs each element with its position: no input but its argument.
        "enumerate" => Some(Effect::Pure),
        // In-memory base64 of a String: neither reads a file nor touches the
        // environment (it was listed ReadLocal with the neighbouring crypto reads).
        "crypto_base64_decode" | "crypto_base64_encode" => Some(Effect::Pure),
        // Stated Pure until pure-audit-3, which read each body. ReadLocal: reads
        // mutable in-process state (a lock, an atomic, a registry), walks a
        // directory tree, reads the cwd or an environment variable, or stats a
        // local path. Every alias group is listed whole, so no spelling answers
        // differently from another.
        "find"
        | "pwd"
        | "is_linux"
        | "check_permission"
        | "has_permission"
        | "get_roles"
        | "user_roles"
        | "list_roles"
        | "roles_list"
        | "check_compliance"
        | "compliance_check"
        | "compliance_report"
        | "generate_compliance"
        | "feature_enabled"
        | "has_feature"
        | "features"
        | "feature_list"
        | "marketplace_list"
        | "mcp_cache_status"
        | "mcp-cache-status"
        | "safety_status"
        | "governor_status"
        | "sess_usage"
        | "session_id" => Some(Effect::ReadLocal),
        // Stated Pure until pure-audit-3, which read each body. ReadLocal:
        // from-json and from_json stat their input (Path::is_file) when it does
        // not parse as JSON, and the sha256, md5, crypto_sign and
        // crypto_verify_signature bodies read IRONSHELL_FIPS (safety::fips_enabled,
        // through require_fips_hash and digital_signatures::policy). Each alias
        // group is listed whole.
        "from-json" | "from_json" | "sha256" | "md5" | "crypto_sign" | "crypto_verify_signature" => {
            Some(Effect::ReadLocal)
        }
        // WriteLocal: changes an in-process table (session store, caches, the
        // MCP cache, a counter) or the journal directory. A process-memory
        // change is not restored by a rollback, so these are HARMLESS in
        // tests/tx_irreversible.rs; try_repair takes and restores its own
        // savepoint (SELF_COVERED there).
        "try_repair"
        | "sess_open"
        | "sess_close"
        | "session_start"
        | "mcp_cache_clear"
        | "mcp-cache-clear"
        | "semantic_cache_get"
        | "cache_get" => Some(Effect::WriteLocal),
        // The privilege boundary itself. `decide(Privileged, Agent)` is `Deny`,
        // and until these names arrived the class governed nothing: every other
        // privilege-shaped builtin in the catalog (`sudo_exec`, `user_add`,
        // `acl_set`, `fs_unmount`) is a stub that performs no effect, so `Pure`
        // is honest for them -- measured, not assumed.
        //
        // These are not stubs. `rbac_grant` writes into the permission store
        // `guard` consults, and `rbac_principal` decides which entry of that
        // store applies -- and an authorized principal *skips approval
        // entirely*. Classified `Pure`, they let an agent grant itself
        // `effect:*`, become that principal, and walk past the gate it had just
        // been refused by. `tests/privilege_escalation.rs` runs exactly that
        // sequence.
        //
        // Human mode still allows both: `Privileged` is `Allow` there, which is
        // how an operator administers RBAC in the first place.
        // `rbac_login`/`rbac_register` join them: authenticating is how
        // authority is acquired, so an agent able to do it unassisted has
        // none. `rbac_logout` is deliberately *not* here -- giving up
        // authority is the one privilege operation that cannot escalate --
        // and `rbac_session`/`rbac_can` only read.
        "rbac_grant" | "rbac_principal" | "rbac_login" | "rbac_register" => {
            Some(Effect::Privileged)
        }
        "rbac_logout" => Some(Effect::WriteLocal),
        "rbac_session" | "rbac_can" => Some(Effect::ReadLocal),
        // The `monitor_*` names dispatch to functions named differently
        // (`monitor_iftop` -> `bi_iftop_info`), and the body-evidence ratchet
        // only paired a name with `bi_<name>`, so none of these bodies had ever
        // been read. All 13 spawn a process and were Pure.
        //
        // Packet capture: reads every process's traffic and needs root or
        // CAP_NET_RAW. An agent doing it unassisted is the privilege boundary.
        // mcp_call runs an OS program from the tool catalogue (cp, mv, make,
        // deno, kubectl, sed, ...) with caller-supplied arguments, through a
        // method call the body-evidence ratchet does not follow. Classified
        // Pure it skipped the gate entirely: in agent mode `cp` to a path
        // outside the workspace was refused and `mcp_call("cp", ...)` made the
        // same copy. tests/mcp_call_is_gated.rs runs that sequence.
        "mcp_call" | "mcp_call_tool" => Some(Effect::Exec),
        // Persists the shell config file (ShellConfig::save), found once the
        // effect ratchet followed typed method calls.
        "config_set" => Some(Effect::WriteLocal),
        "monitor_tcpdump" => Some(Effect::Privileged),
        // System administration: accounts, groups, mounts, services, ACLs,
        // packages and elevation. Most were Pure while their bodies refused;
        // implemented, each changes who may do what on the machine, or what
        // runs on it, and needs root. An agent doing any of it unassisted is
        // the privilege boundary.
        "user_add" | "user_del" | "user_mod" | "user_passwd" | "user_lock" | "user_unlock"
        | "group_add" | "group_del" | "group_mod" | "acl_set" | "fs_mount" | "fs_unmount"
        | "svc_create" | "svc_delete" | "sudo_exec" | "pkg_install" | "pkg_remove"
        | "pkg_update" | "pkg_upgrade" | "pkg_clean" | "pkg_add_source" | "pkg_hold"
        | "pkg_unhold" | "pkg_autoremove" => Some(Effect::Privileged),
        "acl_get" => Some(Effect::ReadLocal),
        // Run `sh -c <command>` under perf: arbitrary execution, exactly as the
        // `perf_stat`/`perf_record` spellings are classified.
        "monitor_perf_stat" | "monitor_perf_record" => Some(Effect::Exec),
        // Read-only system queries that spawn a tool (`ip`, `ss`, `who`,
        // `last`, `journalctl`, `ethtool`, ...), classified like
        // `netstat_info` and `journalctl`.
        "monitor_ethtool" | "monitor_iftop" | "monitor_ip_addr" | "monitor_ip_link"
        | "monitor_ip_route" | "monitor_logins" | "monitor_nethogs" | "monitor_sockets"
        | "monitor_syslog" | "monitor_users"
        // In-process system readings, and the alert store read back.
        | "monitor_alert_history" | "monitor_alert_list" | "monitor_dstat" | "monitor_glances"
        | "monitor_health_check" | "monitor_htop" | "monitor_iotop" | "monitor_memory"
        | "monitor_nmon" | "monitor_watch_cpu" | "monitor_watch_disk"
        | "monitor_watch_memory"
        // Reads the OS uptime and load average, and the host name, the way
        // `sys_uptime`, `sys_load_avg` and `sys_hostname` do. No clock-only read.
        | "monitor_uptime" => Some(Effect::ReadLocal),
        // They write the alert store under the data directory.
        "monitor_alert_create" | "monitor_alert_remove" => Some(Effect::WriteLocal),
        // Read the in-process cluster node table and workspace registry, then
        // refuse: `remote_exec` sends no command, because no transport is wired,
        // and `workspace_sync` syncs nothing. Both are classified like
        // `cluster_nodes` and `workspace_members`.
        // `remote_exec` has to become `Exec` in the same change that wires a
        // transport. `exec_remote` is its alias and inherits this class.
        "remote_exec" | "workspace_sync" => Some(Effect::ReadLocal),
        // Reads the user database. It inherited ReadLocal from `sys_users`
        // while it was that builtin's alias; it has its own body now.
        "whoami" => Some(Effect::ReadLocal),
        "rm"
        | "rmdir"
        | "file_delete"
        | "file_delete_lines"
        | "db_kv_delete"
        | "db_sqlite_delete"
        | "docker_rm"
        | "podman_rm"
        | "docker_compose_down"
        | "truncate"
        | "k8s_delete"
        | "platform_db_delete"
        // Found by `tests/effect_coverage.rs`: these name a destructive action
        // and fell through to `Pure`, so `x-effect` advertised them to agents as
        // side-effect-free and `guard()` would have allowed them outright.
        | "cloud_instance_destroy"
        | "db_sqlite_drop_table"
        | "delete_lines"
        | "delete_role"
        | "kubectl_delete"
        | "role_delete"
        | "cron_remove" | "at_remove"
        | "terraform_destroy"
        | "helm_uninstall"
        | "marketplace_uninstall" => Some(Effect::Destructive),
        // `sudo_check` shells out to determine admin status — it spawns a process,
        // so it is not pure even though it only reports.
        // Restarting a service is process-lifecycle control, not a data write:
        // it interrupts whatever that service was doing.
        // Cancelling, pausing or resuming a workflow is lifecycle control over
        // something that is running, which is what Process means here.
        "workflow_cancel" | "workflow_pause" | "workflow_resume"
        | "workflow_create" | "circuit_breaker_create"
        | "proc_kill" | "kill" | "signal" | "pkill" | "sudo_check"
        | "proc_suspend" | "proc_resume" | "proc_set_priority"
        | "cron_disable"
        // Ending a tmux session runs no command, so it is process lifecycle
        // control like `kill`. tmux_new and tmux_send run caller text: Exec.
        | "tmux_kill"
        | "svc_restart" | "k8s_rollout_restart" => Some(Effect::Process),
        // Every builtin whose argument *is* a command to run. These are the
        // same capability as `sh` under different names; classifying them as
        // `Pure` told `agent_api`'s discovery — and any other consumer of this
        // function — that `timeout("rm -rf /")` was a side-effect-free call.
        // Keep in step with the `guard_exec` call sites in `builtins.rs`.
        // A workflow step names a builtin to run, so executing one is the same
        // capability as `sh` wearing a template. Every step is gated again on
        // its own way through `call_with_input`, but an agent asking whether it
        // may run a workflow must not be told the call is side-effect free.
        | "workflow_execute"
        // These build a template out of caller-supplied step records. Nothing
        // runs yet, but what they store is the list of commands `workflow_execute`
        // will later run, so they are not reads.
        | "workflow_register" | "workflow_pipeline" | "workflow_map_reduce"
        | "workflow_saga" | "workflow_fan_out" | "workflow_scatter_gather"
        | "cron_enable" | "cron_add" | "at_schedule"
        | "sh" | "exec" | "system" | "timeout" | "timeout_cmd" | "xargs" | "xargs_exec"
        | "proc_spawn" | "strace" | "strace_cmd" | "ltrace" | "ltrace_cmd"
        | "perf_stat" | "perf_record" | "tmux_new" | "tmux_send"
        // Also found by `tests/effect_coverage.rs`. Each of these runs a program
        // (locally, in a container, or on another host) with caller-supplied
        // input; `ssh_exec` classifying as `Pure` was
        // the same defect as `timeout("rm -rf /")` classifying as `Pure`.
        | "docker_exec" | "podman_exec" | "k8s_exec" | "kubectl_exec"
        | "ssh_exec"
        | "rlm_spawn" | "spawn_agent"
        | "tool_exec" | "tool_execute"
        // These run the sqlite binary against a caller-supplied statement, which
        // includes DDL. Note this changes what is *advertised* and what `guard()`
        // would decide — neither is currently guarded, so nothing is newly gated.
        | "db_sqlite_exec" | "sqlite_exec"
        // Package installers. Each shells out to a package manager, which fetches
        // remote code and runs its install scripts — the supply-chain surface
        // (CWE-494). Classifying these `Pure` told every consumer of `effect_of`
        // that `npm_install("anything")` was side-effect-free.
        | "npm_install" | "yarn_install" | "pnpm_install" | "bun_install"
        | "pipx_install" | "poetry_install" | "asdf_install"
        // `uv pip install` builds sdists, running their build backends.
        | "uv_pip"
        // Installs toolchains: binaries that later commands run.
        | "rustup_update"
        | "helm_install" | "helm_upgrade" | "marketplace_install" | "pre_commit_install" => Some(Effect::Exec),
        // Egress by name. `scp_*` moves bytes to/from another host; the
        // `marketplace_publish` case sends a package somewhere it cannot be
        // recalled from.
        "scp_upload" | "scp_download" | "wget_download" | "marketplace_publish" => Some(Effect::Network),
        // The rest of the marketplace family reaches the same registry over
        // HTTPS via `packages::RegistryClient`, and all three were `Pure` by
        // fall-through. Measured, not assumed: in agent mode with
        // `--policy strict` and `IRONSHELL_MAX_NET=0`, `marketplace_search("x")`
        // exited 0 after a 20-second round trip to packages.nervosys.ai. An
        // agent with networking budgeted to zero could still make an outbound
        // request.
        //
        // `effect_ratchet.rs` could not catch it: it reads builtin *bodies*
        // for socket construction, and the socket here is opened inside
        // `RegistryClient`. That is the false negative its own documentation
        // names as a lower bound, and this is a concrete instance of it.
        // `marketplace_publish` being classified already is why the omission
        // reads as an oversight rather than a decision.
        "marketplace_search" | "marketplace_info" | "marketplace_update" => Some(Effect::Network),

        // The NERVOSYS stack. `ai_gateway` probes IronGate over HTTP; it reads
        // and reports, so Network rather than Exec.
        "ai_gateway" => Some(Effect::Network),
        // Model calls leave the machine. These were unclassified, so `Pure`, so
        // `IRONSHELL_MAX_NET=0` did not apply to them: under `--agent --policy
        // strict` each one connected to IronGate (:7700), `ai_backends` swept
        // five local model ports and `mcp_client` seven MCP ports. Found by
        // `benches/agentic/network-egress.mjs`, which traces connect(2) across
        // the whole catalogue rather than trusting this table.
        "ai" | "agent" | "agent_with_mcp" | "swarm" | "rlm_agent" | "ai_backends" | "mcp_client"
        | "mcp_detect"
        | "mcp_servers" => {
            Some(Effect::Network)
        }
        // Declaring the fallback ai_* builtins (2026-10-23) showed these
        // falling through to Pure. `ai_detect` sweeps the same model ports as
        // `ai_backends`; `ai_local_generate` posts to IronGate whenever no
        // in-process backend is compiled in, which is the default build.
        // `ai-backends` is the fallback spelling of `ai_backends`: its twin is
        // served by BUILTIN_LOOKUP, so `alias_groups` never pairs them and it
        // inherited nothing.
        "ai_detect" | "ai_local_generate" | "ai-backends" => Some(Effect::Network),
        // `ai_gpu_memory` and `ai_model_fits` run nvidia-smi to read the GPUs,
        // as `hw_gpu` and `platform_gpu_memory` do; `ai_local_load` reads the
        // model file it is given.
        "ai_gpu_memory" | "ai_model_fits" | "ai_local_load" => Some(Effect::ReadLocal),
        // Undo, redo and forgetting the journal write and delete files: undo
        // and redo put recorded contents back or remove what a step created,
        // and the journal itself lives on disk. They were Pure. WriteLocal, as
        // `session_restore` is, so an agent still rewinds without an approval
        // round-trip; `journal::undo` and `journal::redo` refuse a recorded
        // path outside an enforced jail themselves, because these calls carry
        // no path argument for the central jail check to see.
        "undo" | "rewind" | "session_undo" | "session_redo" | "journal_clear" | "session_end" => {
            Some(Effect::WriteLocal)
        }
        // The vault builtins spawn the `iv` binary. `vault_models` and
        // `vault_conversions` only read, but they still hand arguments to a
        // process, which is what Exec is about — the ratchet reads
        // `Command::new` in `model_plane::vault_run` and would refuse anything
        // weaker. `vault_convert` additionally writes a converted model.
        "vault_models" | "vault_conversions" | "ai_supported_conversions" => Some(Effect::Exec),
        "vault_convert" | "ai_convert_model" => Some(Effect::Exec),

        // ════════════════════════════════════════════════════════════
        // Process-spawning builtins, classified from their argv (§12).
        //
        // These 306 were found by `tests/effect_ratchet.rs`, which reads function
        // bodies rather than names — the name-based reasoning is what produced the
        // original misclassifications. Each one below constructs an OS process while
        // `effect_of` returned `Pure`, i.e. every consumer of this function was told
        // it was side-effect-free.
        //
        // The tier comes from the argv the body actually builds, in this order:
        // deletes irrecoverably → Destructive; contacts another host → Network;
        // controls a process or window lifecycle → Process; writes a file or rewrites
        // source → WriteLocal; only reads *and* executes no caller- or project-supplied
        // code → ReadLocal; anything else → Exec. The default is the unsafe-side one:
        // an unclear argv is `Exec`, never `ReadLocal`.
        //
        // Three were not merely unclassified but actively dangerous while advertised
        // as pure: `git_clean -d` deletes untracked files, `session_rollback` is
        // `git reset --hard`, and `dd_copy` can overwrite a block device. Note also
        // `diag_fix`/`refactor_remove_unused`, which run `cargo fix --allow-dirty`
        // and rewrite sources with the net switched off. `db_sqlite_query` was
        // `Exec` here while it passed caller SQL to the sqlite3 binary; it now runs
        // in-process behind a read-only authorizer (src/sql.rs), so it reads.
        //
        // Linters divide on whether they execute project-supplied code: `eslint`
        // loads and runs `eslint.config.js`, so it is `Exec`; `shellcheck`,
        // `hadolint` and `yamllint` only parse, so they are `ReadLocal`.
        // ---- Destructive (5) ----
        | "dd_copy"
        | "git_clean"
        | "git_reset"
        // Overwrites destination files, and its `delete` option removes them.
        | "rsync_sync"
        // `fs::rename` removes the source and can overwrite the destination;
        // it was classified `ReadLocal`.
        | "file_move" | "file_rename"
        | "session_rollback" => Some(Effect::Destructive),

        // ---- Network (22) ----
        | "gh_issue"
        | "gh_pr"
        | "gh_repo_cmd"
        | "git_fetch"
        | "git_pull"
        | "git_push"
        | "glab_issue"
        | "glab_mr"
        | "host_lookup"
        | "iperf3_client"
        | "iperf3_server"
        | "mtr_trace"
        | "nmap_quick"
        | "nmap_scan"
        | "pkg_changelog"
        | "skopeo_copy"
        | "skopeo_inspect"
        | "socat_relay"
        | "ssh_copy_id"
        | "ssh_tunnel"
        | "trivy_image"
        | "trivy_scan" => Some(Effect::Network),

        // ---- Process (13) ----
        | "gui_close_window"
        | "gui_focus_window"
        | "gui_maximize_window"
        | "gui_minimize_window"
        | "gui_move_window"
        | "gui_resize_window"
        | "screen_attach"
        | "screen_new"
        | "svc_disable"
        | "svc_enable"
        | "svc_start"
        | "svc_stop"
        | "tmux_attach" => Some(Effect::Process),

        // ---- WriteLocal (68) ----
        | "add_entity"
        | "add_node"
        | "add_relation"
        | "age_decrypt"
        | "age_encrypt"
        | "age_keygen"
        | "audit_log"
        | "black_format"
        | "bzip2_compress"
        | "bzip2_decompress"
        | "cache_ai"
        | "chgrp"
        | "clipboard_set"
        | "clipboard_set_image"
        | "cluster_add_node"
        | "cluster_create"
        | "code_format"
        | "config_init"
        | "crypto_decrypt"
        | "crypto_encrypt"
        | "db_sqlite_backup"
        | "env_set"
        | "feature_set"
        | "fs_tempdir"
        | "fs_tempfile"
        | "gui_screenshot"
        | "gui_screenshot_window"
        | "gzip_compress"
        | "gzip_decompress"
        | "index_docs"
        | "kg_add"
        | "kg_relate"
        | "marketplace_rate"
        | "mypy_check"
        | "platform_db_export"
        | "platform_db_import"
        | "platform_db_init"
        | "platform_db_store"
        | "plugin_disable"
        | "plugin_enable"
        | "plugin_load"
        | "plugin_unload"
        | "rag_index"
        | "refactor_rename_file"
        | "ruff_check"
        | "ruff_format"
        | "sed_replace"
        | "semantic_cache"
        | "semantic_cache_clear"
        | "session_checkpoint"
        | "session_restore"
        | "set_env"
        | "shfmt_format"
        | "ssh_keygen"
        | "sso_init"
        | "tar_create"
        | "tar_extract"
        | "tee_output"
        | "telemetry_reset"
        | "uv_venv"
        | "xz_compress"
        | "xz_decompress"
        | "zip_add"
        | "zip_create"
        | "zip_extract"
        | "zoxide_add"
        | "zstd_compress"
        | "zstd_decompress" => Some(Effect::WriteLocal),

        // ---- Exec (83) ----
        | "act_run"
        | "apply"
        | "buildah_build"
        | "bun_run"
        | "cargo_build_cmd"
        | "cargo_run"
        | "cargo_test_cmd"
        | "cmake_build"
        | "cmake_configure"
        | "deno_run"
        | "deno_task"
        | "diag_check"
        | "diag_errors"
        | "diag_fix"
        | "diag_lint"
        | "diag_warnings"
        | "direnv_allow"
        | "docker_run"
        | "docs_generate"
        | "entr_watch"
        | "eslint_check"
        | "fzf_select"
        | "gdb_bt"
        | "gdb_run"
        | "git_add"
        | "git_checkout"
        | "git_cherry_pick"
        | "git_commit"
        | "git_merge"
        | "git_rebase"
        | "git_stash"
        | "git_stash_pop"
        | "go_build"
        | "go_run"
        | "go_test"
        | "gui_dialog_file_open"
        | "gui_dialog_folder"
        | "gui_dialog_input"
        | "gui_dialog_message"
        | "gui_key_combo"
        | "gui_key_press"
        | "gui_mouse_click"
        | "gui_mouse_drag"
        | "gui_mouse_move"
        | "gui_mouse_scroll"
        | "gui_notify"
        | "gui_type_text"
        | "hyperfine_bench"
        | "input_editor"
        | "input_read_password"
        | "jq_filter"
        | "just_run"
        | "lazygit"
        | "lazygit_open"
        | "lldb_run"
        | "lnav_open"
        | "logrotate_run"
        | "mage_run"
        | "make_run"
        | "mise_use"
        | "multitail_open"
        | "ninja_build"
        | "node_run"
        | "nodemon_run"
        | "npm_run"
        | "pnpm_run"
        | "podman_run"
        | "poetry_run"
        | "pre_commit_run"
        | "prettier_format"
        | "pytest_run"
        | "refactor_remove_unused"
        | "rga_search"
        | "task_run"
        | "test_bench"
        | "test_list"
        | "test_run"
        | "test_run_file"
        | "test_run_function"
        | "test_watch"
        | "uv_run"
        | "valgrind_memcheck"
        | "valgrind_run"
        | "watchexec_run"
        | "yarn_run"
        | "yq_query" => Some(Effect::Exec),

        // ---- ReadLocal (153) ----
        | "archive_test"
        | "asdf_list"
        | "at_list"
        | "audit_tail"
        | "audit_verify"
        | "bat_view"
        | "blkid"
        | "buildah_images"
        | "capabilities"
        | "clipboard_get"
        | "clipboard_get_image"
        | "clipboard_history"
        | "clipboard_types"
        | "cron_list"
        | "crypto_cert_info"
        | "crypto_cert_verify"
        | "crypto_hash"
        | "crypto_hash_file"
        | "crypto_hmac"
        | "crypto_jwt_decode"
        | "crypto_password_hash"
        | "crypto_random_bytes"
        | "crypto_random_string"
        | "crypto_uuid"
        | "csv_columns"
        | "db_csv_query"
        | "db_csv_to_json"
        | "db_json_query"
        | "db_json_to_csv"
        | "db_sqlite_dump"
        | "db_sqlite_query"
        | "delta_diff"
        | "diag_explain"
        | "direnv_status"
        | "docs_search"
        | "env_docker"
        | "env_dotnet"
        | "env_go"
        | "env_java"
        | "env_node"
        | "env_python"
        | "env_ruby"
        | "env_rust"
        | "eza_list"
        | "fd_find"
        | "file_diff"
        | "fs_df"
        | "git_blame"
        | "git_branch"
        | "git_branches"
        | "git_diff"
        | "git_diff_staged"
        | "git_log"
        | "git_remote"
        | "git_rev_parse"
        | "git_root"
        | "git_show"
        | "git_stash_list"
        | "git_status"
        | "git_tags"
        | "group_members"
        | "gui_color_picker"
        | "gui_find_image"
        | "gui_get_active_window"
        | "gui_list_windows"
        | "gui_mouse_position"
        | "gui_ocr"
        | "gui_screen_size"
        | "hadolint_check"
        | "hw_audio"
        | "hw_battery"
        | "hw_gpu"
        | "hw_pci"
        | "hw_sensors"
        | "hw_usb"
        | "journalctl"
        | "just_list"
        | "lsof"
        | "mise_list"
        | "netstat_info"
        | "nm_symbols"
        | "objdump_disasm"
        | "objdump_headers"
        | "open"
        | "pgrep"
        | "pipx_list"
        | "pkg_deps"
        | "pkg_files"
        | "pkg_info"
        | "pkg_list"
        | "pkg_owner"
        | "pkg_rdeps"
        | "pkg_search"
        | "pkg_verify"
        | "platform_build"
        | "platform_capabilities"
        | "platform_cpu"
        | "platform_cpu_freq"
        | "platform_cuda_version"
        | "platform_disk_usage"
        | "platform_disks"
        | "platform_gpu_memory"
        | "platform_gpus"
        | "platform_has_admin"
        | "platform_hostname"
        | "platform_kernel"
        | "platform_lib_version"
        | "platform_libc"
        | "platform_libcpp"
        | "platform_libs"
        | "platform_memory"
        | "platform_memory_free"
        | "platform_memory_total"
        | "platform_network_interfaces"
        | "platform_os_version"
        | "platform_sdk_version"
        | "platform_snapshot"
        | "platform_ssl_version"
        | "platform_system_libs"
        | "project_loc"
        | "project_root"
        | "project_version"
        | "readelf_headers"
        | "readelf_sections"
        | "rg_search"
        | "rustup_show"
        | "screen_list"
        | "search_by_size"
        | "search_by_type"
        | "search_code"
        | "search_files"
        | "search_fixmes"
        | "search_modified"
        | "search_recent"
        | "search_symbols"
        | "search_todos"
        | "session_diff_since"
        | "shellcheck_check"
        | "sql_value"
        | "startup_list"
        | "strings_extract"
        | "svc_list"
        | "svc_logs"
        | "svc_status"
        | "tar_list"
        | "task_list"
        | "tmux_list"
        | "tokei_count"
        | "top_snapshot"
        | "yamllint_check"
        | "zip_list"
        | "zoxide_query" => Some(Effect::ReadLocal),

        // ════════════════════════════════════════════════════════════
        // Builtins that act through a *helper* (§12).
        //
        // The 306 above were found by reading each builtin's own body. That
        // missed everything that hands its side effect to a helper: a builtin
        // calling `cloud_run_cmd`, or `kubectl_text`, or another builtin, is
        // exactly as dangerous as one spawning the process itself — only the
        // lint could not tell, which made the difference a blind spot rather
        // than a fact. Following calls two levels deep found 116 more.
        //
        // Each is classified from what its helper actually runs, and a builtin
        // that delegates to another builtin inherits that builtin's effect.
        // Two groups are deliberately *not* inherited: the `db_sqlite_*`
        // wrappers build their own statements, and the only reason
        // `db_sqlite_exec`/`_query` are `Exec` is that a caller can supply
        // arbitrary SQL — which these do not permit. They are the write/read
        // they appear to be.
        //
        // `syntax_*` are `WriteLocal` for an honest but unobvious reason: their
        // store is created lazily, so a lookup really does create a directory
        // the first time. `WriteLocal` is `Allow` in agent mode, so saying so
        // costs no friction and beats pretending the write does not happen.
        // ---- delegated: ReadLocal (41) ----
        | "clipboard_has_text"
        | "crypto_checksum"
        | "crypto_password_verify"
        | "db_kv_get"
        | "db_kv_keys"
        | "db_sqlite_count"
        | "db_sqlite_schema"
        | "db_sqlite_tables"
        | "db_sqlite_to_json"
        | "docker_images"
        | "docker_networks"
        | "docker_ps"
        | "docker_stats"
        | "docker_volumes"
        | "gpg_list_keys"
        | "group_list"
        | "hw_cpu"
        | "hw_disk"
        | "hw_memory"
        | "hw_network"
        | "openssl_cert_info"
        | "platform_build_systems"
        | "platform_cloud_clis"
        | "platform_compilers"
        | "platform_containers"
        | "platform_databases"
        | "platform_fingerprint"
        | "platform_hardware_summary"
        | "platform_iac_tools"
        | "platform_linters"
        | "platform_pkg_lang"
        | "platform_runtimes"
        | "platform_tool_version"
        | "platform_tool_versions"
        | "platform_vcs"
        | "podman_images"
        | "podman_ps"
        | "search_grep"
        | "search_regex"
        | "session_changes"
        | "session_checkpoints"
        | "svc_info"
        | "user_list" => Some(Effect::ReadLocal),

        // ---- delegated: WriteLocal (21) ----
        | "clipboard_clear"
        | "crypto_generate_key"
        | "db_csv_to_sqlite"
        | "db_json_to_sqlite"
        | "db_kv_set"
        | "db_kv_store"
        | "db_sqlite_create_table"
        | "db_sqlite_import"
        | "db_sqlite_insert"
        | "db_sqlite_open"
        | "db_sqlite_to_csv"
        | "db_sqlite_update"
        | "db_sqlite_vacuum"
        | "gpg_decrypt"
        | "gpg_encrypt"
        | "openssl_genrsa"
        | "syntax_add"
        | "syntax_categories"
        | "syntax_get"
        | "syntax_list"
        | "syntax_search" => Some(Effect::WriteLocal),

        // `helm repo list` reads helm's own repository file and nothing else.
        "helm_repos" => Some(Effect::ReadLocal),

        // ---- delegated: Network (22) ----
        | "helm_list"
        | "helm_search"
        | "helm_status"
        | "k8s_apply"
        | "k8s_cluster_info"
        | "k8s_configmaps"
        | "k8s_context"
        | "k8s_contexts"
        | "k8s_describe"
        | "k8s_events"
        | "k8s_get"
        | "k8s_ingresses"
        | "k8s_logs"
        | "k8s_namespaces"
        | "k8s_nodes"
        | "k8s_pods"
        | "k8s_rollout_status"
        | "k8s_scale"
        | "k8s_secrets"
        | "k8s_top_nodes"
        | "k8s_top_pods" => Some(Effect::Network),

        // ---- delegated: Exec (31) ----
        | "ansible_galaxy"
        | "ansible_inventory"
        | "ansible_playbook"
        | "ansible_vault"
        | "diag_all"
        | "docker_build"
        | "docker_compose_ps"
        | "docker_compose_up"
        | "docker_cp"
        | "docker_inspect"
        | "docker_logs"
        | "docker_pull"
        | "docker_push"
        | "docker_stop"
        | "docker_tag"
        | "docker_top"
        | "gui_mouse_double_click"
        | "podman_build"
        | "podman_logs"
        | "podman_pull"
        | "podman_stop"
        | "terraform_apply"
        | "terraform_init"
        | "terraform_output"
        | "terraform_plan"
        | "terraform_state"
        | "terraform_validate"
        | "terraform_workspace" => Some(Effect::Exec),
        // ════════════════════════════════════════════════════════════
        // Found only after the lint stopped reading a single file (§12).
        //
        // The ratchet read `builtins.rs` alone, so an effect reached through
        // `security`, `os_tools` or any other module was invisible —
        // `Command::new` appears in six other modules, `fs::write` in ten.
        // Reading the whole crate, with precise markers, surfaced these six.
        //
        // `platform_has_network` binds a loopback socket and immediately drops
        // it to test whether networking works; nothing leaves the machine, so
        // it is a read rather than egress. `platform_machine_id` shells out to
        // `ioreg`/equivalent purely to read an identifier.
        "fs_link" | "fs_symlink" | "git_ignore" | "perm_set" => Some(Effect::WriteLocal),
        "platform_has_network" | "platform_machine_id" => Some(Effect::ReadLocal),
        // The `web_*` fetch family already routes through `guard_network` at each
        // call site, so it was *gated* as Network at runtime while `effect_of`
        // reported `Pure` — meaning the agent-facing ontology advertised
        // `web_post` as side-effect-free. Make the label agree with the control.
        n if n.starts_with("http")
            || n.starts_with("web_")
            || n.starts_with("net_")
            || n.starts_with("nc_") =>
        {
            Some(Effect::Network)
        }
        // A loopback listener that evaluates a peer's code, and the client that
        // sends it. What the remote code does is judged per call when it runs.
        "repl_serve" | "repl_connect" => Some(Effect::Network),
        // `kubectl get` against a cluster endpoint: a read, but a *remote* one
        // that ships credentials off the machine, so it is metered as egress.
        "k8s_deployments" | "k8s_services" => Some(Effect::Network),
        // Listing mounts is a read; mounting one is not. Order matters here.
        "fs_mounts" => Some(Effect::ReadLocal),
        // Permission and ownership changes modify filesystem metadata.
        // `file_mkdir` is the same dispatch index as `mkdir`; without it the
        // `file_*` prefix rule below claimed the directory-creating spelling only
        // read. `tests/effect_alias_agreement.rs` is what noticed.
        "file_write" | "json_set" | "file_append" | "file_copy" | "mkdir" | "mkdirp" | "file_mkdir" | "touch"
        // `file_edit`, `file_insert` and `file_patch` read a file, change it and
        // write it back — the `file_*` prefix rule below saw only the read. The
        // jail keys on `WriteLocal`, so all three modified files anywhere on disk
        // in agent mode while `file_write` to the same path was refused.
        // `session_export` is the same shape one family over: labelled a read,
        // writes the diff to a caller-named path.
        | "file_edit" | "file_insert" | "file_patch" | "session_export"
        // `file_backup` copies onto `<path><suffix>`; the label said read.
        | "file_backup"
        // `file_replace` calls `file_patch`, which rewrites the file. It was
        // classed ReadLocal by the `file_` prefix rule, so nothing journalled it
        // and `undo()` left the replacement in place (AS-2026-27). Its two
        // aliases are named too, rather than inheriting through the group.
        | "file_replace" | "text_replace" | "str_replace_in_file"
        | "write_file" | "write_json" | "text_write" | "save_json"
        | "gui_dialog_file_save"
        | "chmod" | "fs_chmod" | "fs_chown"
        // Changes what every later relative path means; `pwd()` answers
        // differently afterwards, so it is emphatically not Pure.
        | "cd" => Some(Effect::WriteLocal),
        // Found by body evidence, not by name: each of these opens a file,
        // lists a directory, stats a path or reads the environment, and every
        // one of them was falling through to `Pure`.
        //
        // This changes no policy -- `decide()` returns Allow for `Pure` and
        // `ReadLocal` alike -- it changes a *claim*. `Pure` says the call is
        // referentially transparent, so an agent may cache it, reorder it, or
        // skip a repeat. `ls` and `cat` are the plain counterexamples: their
        // answers change the moment anything touches the directory.
        "archive_info" | "cat" | "code_comments" |
        "code_exports" | "code_imports" | "code_parse" | "code_symbols" |
        "code_todos" | "diag_config" | "docs_changelog" | "docs_examples" |
        "env" | "env_container" | "env_path" | "env_shell" |
        "env_var" | "env_vars" | "env_venv" | "fs_du" |
        "fs_glob" | "fs_lstat" | "fs_readlink" | "fs_realpath" |
        "fs_stat" | "fs_tree" | "fs_walk" | "fs_watch" | "fs_unwatch" | "grep" |
        "head" | "ls" | "make_targets" | "pager" |
        "perm_check" | "perm_get" | "pkg_history" | "pkg_sources" |
        "platform_db_compare" | "platform_db_list" | "platform_db_load" | "platform_has_gui" | "platform_shell_type" |
        "project_dependencies" | "project_dev_dependencies" | "project_gitignore" | "project_languages" |
        "project_license" | "project_name" | "project_readme" | "project_scripts" | "project_size" |
        "plan_diff" | "project_structure" | "project_test_files" | "read_text"
        | "refactor_organize_imports" |
        // PowerShell-style readers: Get-Content reads the file it names and
        // Get-Files lists a directory tree. They were unclassified, so `Pure`.
        "ssh_config" | "tail" | "wc" | "Get-Content" | "get-content" | "Get-Files"
        | "get-files" => Some(Effect::ReadLocal),
        n if n.starts_with("file_") || n.starts_with("proc_") || n.starts_with("sys_") => {
            Some(Effect::ReadLocal)
        }
        // ── Group 1: mutation and execution, reclassified from the stated-pure
        // baseline by reading each body (tests/effect_pure_class.rs).
        //
        // RBAC role store. These write RBAC_ROLES and USER_ROLES. That is the
        // store tests/rbac_legacy_store.rs says must be classified before it is
        // ever bridged to the store `guard` reads, and `rbac_grant` is
        // Privileged for the same reason: creating a role and granting it is
        // self-elevation if the two stores ever meet.
        "role_create" | "create_role" | "role_grant" | "grant_permission" | "role_revoke"
        | "revoke_permission" => Some(Effect::Privileged),
        // Empties the in-memory RAG index. Cache-clear class, as
        // `semantic_cache_clear` is.
        "rag_clear" => Some(Effect::WriteLocal),
        // The transaction state is an in-memory journal plus the backups under
        // `<workspace>/.ironshell/tx/`. Begin creates that directory; commit
        // and rollback delete only its own journal, and rollback restores paths
        // that a jailed WriteLocal or Destructive call recorded. Undo-class, as
        // `undo` and `session_restore` are, so the agent's undo tool needs no
        // approval round-trip. Savepoints touch only the in-memory frame.
        "tx_begin" | "tx_commit" | "tx_rollback" | "tx_rollback_to" | "tx_savepoint" => {
            Some(Effect::WriteLocal)
        }
        // Ends the host process, and with it any agent API server or session
        // running inside it. Process lifecycle, as `proc_kill` is.
        "exit" => Some(Effect::Process),
        // Evaluates caller-supplied IronShell code, which can name any builtin.
        // Each call inside passes its own guard; the wrapper is the same
        // capability as `sh` and `exec` in that it runs code the classifier
        // cannot see.
        "sess_eval" => Some(Effect::Exec),
        // Removes a process environment variable, as `env_set` does.
        "env_unset" => Some(Effect::WriteLocal),
        // Runtime feature table, in memory. Nothing reads it to decide a gate,
        // and `feature_set` is WriteLocal.
        "feature_enable" | "feature_disable" => Some(Effect::WriteLocal),
        // Deletes one handle from memory and from the session cache directory.
        // Cache-clear class, as `journal_clear` and `session_end` are.
        "handle_drop" => Some(Effect::WriteLocal),
        // Formats the in-memory audit log. Read only.
        "audit_export" | "export_audit" => Some(Effect::ReadLocal),
        // ── Group 2: the names that were presumed to reach the network. Read
        // by body (tests/effect_pure_class.rs). None of them does: no cloud,
        // SSO, cluster, workspace, telemetry, REPL or provider call exists in
        // these bodies. What they do is listed per arm. Stubs that refuse
        // before any effect stay Pure (see the report).
        //
        // Writes a process-static table: the cloud configuration, the SSO
        // session table, the cluster node table, the workspace and REPL-session
        // tables, the telemetry buffer and flag, and the AI provider registry or
        // cost tracker and local model table. None touches disk or the network.
        "cloud_config" | "sso_logout" | "logout_sso" | "cluster_remove_node"
        | "workspace_create" | "workspace_join" | "workspace_leave"
        | "workspace_share_agent" | "telemetry_enable" | "telemetry_disable"
        | "repl_disconnect" | "ai_add_route" | "ai-add-route" | "ai_set_default"
        | "ai-set-default" | "ai_set_load_balancing" | "ai-set-load-balancing"
        | "ai_reset_usage" | "ai-reset-usage" | "ai_local_unload" | "ai-local-unload" => {
            Some(Effect::WriteLocal)
        }
        // Read-only views of the same tables, the provider registry, the cost
        // tracker, the RAG index and the local model backends. `rag_query` joins
        // chunk text and `ai_local_embed` runs an already-loaded model; neither
        // calls a provider.
        "sso_validate" | "sso_status" | "sso_info" | "cluster_nodes" | "cluster_status"
        | "workspace_members" | "workspace_agents" | "workspace_list" | "telemetry_status"
        | "telemetry_report" | "telemetry_events" | "repl_sessions" | "rag_search"
        | "rag_query" | "ai_cost" | "ai-cost" | "ai_usage" | "ai-usage"
        | "ai_load_balancing" | "ai-load-balancing" | "ai_local_backends"
        | "ai-local-backends" | "ai_local_embed" | "ai-local-embed" | "ai_providers"
        | "ai-providers" | "ai_registry_stats" | "ai-registry-stats" | "ai_routes"
        | "ai-routes" => Some(Effect::ReadLocal),
        // ── Group 3: local reads. Each body was read (tests/effect_pure_class.rs).
        //
        // Reads a file or directory named by the caller or the working directory,
        // or the config file, the plugin registry, the OS disk and mount tables,
        // the PATH, the on-disk undo journal (cached after the first read), the
        // in-memory audit log, the transaction state and the handle store. The
        // config reload parses the file and discards the result, so it changes
        // nothing in this process.
        "code_dependencies" | "code_outline" | "docs_readme" | "config" | "config_get"
        | "config_path" | "config_reload" | "project_config_files" | "project_entry_points"
        | "project_type" | "plugin_list" | "plugin_info" | "lsblk" | "mount_info"
        | "platform_cpu_count" | "platform_detect_tools" | "platform_has_container"
        | "platform_has_sudo" | "platform_has_tool" | "platform_pkg_managers"
        | "session_history" | "journal" | "query_audit" | "audit_query" | "audit_statistics"
        | "audit_stats" | "tx_status" | "handle" | "handles" | "record_summary" => {
            Some(Effect::ReadLocal)
        }
        // Runs `<tool> --version` on a PATH binary the caller names, unsandboxed,
        // whenever a requirement is a version string (`get_tool_version`). A bare
        // presence check only scans PATH, but the call can execute any program on
        // it, so it is Exec. `platform_satisfies` delegates to `platform_require`.
        "platform_check_reqs" | "platform_require" | "platform_satisfies" => Some(Effect::Exec),
        // ── Group 4: the open names of the stated-pure list, each body read.
        //
        // a2a_*, nanda_*, job_*, finetune_* and kg_* act on process-static
        // tables (A2A_REGISTRY and A2A_MESSAGES, NANDA_PROPOSALS,
        // DISTRIBUTED_JOBS, FINETUNE_JOBS, KNOWLEDGE_GRAPH). Their writers change
        // those tables and nothing else: no file, network or process is reached,
        // and nothing is persisted, so a restart forgets them. Their readers only
        // read the tables. rlm_stats reads the record of the last recursive run.
        // Writes to a process-memory store are WriteLocal. The writers that stop,
        // commit or consume work, or that other builtins read back, are listed in
        // tx::IRREVERSIBLE.
        "a2a_send" | "a2a_receive" | "a2a_broadcast" | "a2a_register" | "a2a_unregister"
        | "nanda_propose" | "nanda_vote" | "nanda_commit" | "nanda_abort" | "job_cancel"
        | "finetune_cancel" | "cancel_finetune" => Some(Effect::WriteLocal),
        "a2a_discover" | "a2a_status" | "a2a_agents" | "nanda_status" | "nanda_consensus"
        | "nanda_quorum" | "job_status" | "job_list" | "jobs" | "job_results" | "results"
        | "finetune_status" | "finetune_progress" | "finetune_list" | "list_finetunes"
        | "kg_query" | "query_kg" | "kg_entities" | "entities" | "kg_relations" | "relations"
        | "rlm_stats" => {
            Some(Effect::ReadLocal)
        }
        // ── stated-pure audit 4: in-process state that was left Pure.
        //
        // approve(token) writes the approval store and governor_reset() clears the
        // resource-governor counters. Both are process memory, as a2a_* is. An
        // agent's approve is refused in its body, where the mode is known, so the
        // class does not gate it: WriteLocal decides Allow and is not centrally
        // enforced, so guard_dispatch returns before any approval is consulted.
        //
        // The a2ui_* names push events onto the A2UI channel's queue. The prompt
        // family (a2ui_prompt, a2ui_confirm, a2ui_select) pushes a prompt and then
        // waits on the response table; the class follows the write, and the wait
        // is not an effect a rollback or a policy can reach.
        "approve"
        | "governor_reset"
        | "a2ui_notify"
        | "a2ui_prompt"
        | "a2ui_confirm"
        | "a2ui_select"
        | "a2ui_progress"
        | "a2ui_progress_complete"
        | "a2ui_render"
        | "a2ui_render_table"
        | "a2ui_render_code"
        | "a2ui_toast"
        | "a2ui_status"
        | "a2ui_clear"
        | "a2ui_agent_started"
        | "a2ui_agent_completed"
        | "a2ui_agent_thinking"
        // The unprefixed spellings of the same slots: they share one implementation,
        // so they share its class (tests/effect_alias_agreement.rs).
        | "notify_user"
        | "prompt_user"
        | "confirm_user"
        | "select_user"
        | "progress_update"
        | "progress_done"
        | "render_content"
        | "render_table"
        | "render_code"
        | "toast"
        | "status_bar"
        | "ui_clear"
        | "agent_started"
        | "agent_completed"
        | "agent_thinking" => Some(Effect::WriteLocal),
        _ => None,
    }
}

// ════════════════════════════════════════════════════════════════════════
// Mode & policy (§7.1)
// ════════════════════════════════════════════════════════════════════════

/// Execution surface, which selects policy defaults.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Human at a REPL / running scripts — default-allow.
    Human,
    /// LLM agent over the API / agent syntax — default-deny for dangerous ops.
    Agent,
}

/// The project's one spelling of "is this switch on?". Public so builtins that
/// gate on an operator-set variable (rather than on caller-supplied data) share
/// exactly these accepted spellings instead of each inventing their own.
/// Matching is case-insensitive and ignores surrounding whitespace.
pub fn truthy_env(name: &str) -> bool {
    // `var_os`: no UTF-8 check, no `String` -- this and `current_mode` run on
    // every builtin call, and `getenv` was 8% of a call-heavy profile.
    let raw = std::env::var_os(name);
    let Some(v) = raw.as_deref().and_then(|v| v.to_str()) else {
        return false;
    };
    let v = v.trim();
    ["1", "true", "yes", "on"]
        .iter()
        .any(|on| v.eq_ignore_ascii_case(on))
}

#[cfg(test)]
lazy_static! {
    /// Serializes any test that mutates the process-global environment this
    /// module reads (`IRONSHELL_MODE`, `IRONSHELL_AGENT`, `IRONSHELL_WORKSPACE`, …).
    ///
    /// Crate-visible on purpose. `security::validate_safe_path` consults
    /// [`current_mode`], so `security`'s tests are affected by an
    /// `IRONSHELL_MODE=agent` set by a concurrently-running `safety` test — a
    /// `.` path that is fine in human mode gets jailed in agent mode. Every
    /// test on either side of that coupling must take *this* lock, not a
    /// module-private one.
    pub(crate) static ref ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
}

/// Refuse an interactive desktop dialog when nobody is there to dismiss it.
///
/// `gui_dialog_*` and `gui_color_picker` shell out to zenity, osascript or a
/// WinForms MessageBox and then *block on `.output()`* until a human clicks
/// something. In agent mode there is no human, so the call never returns:
/// `benches/agentic/uncoded.mjs` had `gui_dialog_file_save` killed at the
/// ten-second timeout, and a call that hangs is worse for an agent than any
/// error, because a failure can be branched on and a hang cannot.
///
/// Same resolution as `a2ui_confirm`, which waited 300 seconds and then
/// fabricated a decline: say `E_NO_UI` immediately, before spawning anything.
pub fn refuse_if_headless(builtin: &str) -> anyhow::Result<()> {
    if current_mode() == Mode::Agent {
        return Err(no_ui(builtin));
    }
    Ok(())
}

/// In agent mode a listener may bind only loopback, unless the operator sets
/// `IRONSHELL_ALLOW_REMOTE_BIND` to `1` or `true`: the same opt-in `ish mcp
/// serve` requires. An agent that binds `0.0.0.0` exposes the listener to every
/// peer that can route to the host, and the agent never sees that exposure.
pub fn refuse_remote_bind(builtin: &str, ip: std::net::IpAddr) -> anyhow::Result<()> {
    if ip.is_loopback() || current_mode() != Mode::Agent {
        return Ok(());
    }
    if matches!(
        std::env::var("IRONSHELL_ALLOW_REMOTE_BIND").as_deref(),
        Ok("1") | Ok("true")
    ) {
        return Ok(());
    }
    Err(policy_deny(
        builtin,
        format!(
            "{builtin}: refusing to listen on {ip} in agent mode; a listener beyond loopback accepts peers from the network"
        ),
        "bind 127.0.0.1, or set IRONSHELL_ALLOW_REMOTE_BIND=true if this exposure is intended",
    ))
}

/// The active execution mode, derived from the environment.
/// `IRONSHELL_MODE=agent` matching is case-insensitive and ignores surrounding
/// whitespace, as is `IRONSHELL_AGENT` (see [`truthy_env`]).
pub fn current_mode() -> Mode {
    if std::env::var_os("IRONSHELL_MODE")
        .as_deref()
        .and_then(|v| v.to_str())
        .is_some_and(|v| v.trim().eq_ignore_ascii_case("agent"))
        || truthy_env("IRONSHELL_AGENT")
    {
        Mode::Agent
    } else {
        Mode::Human
    }
}

/// Whether the policy has been globally relaxed to permissive (agent mode
/// behaves like human mode). `IRONSHELL_POLICY=permissive`, matched
/// case-insensitively and ignoring surrounding whitespace.
fn policy_permissive() -> bool {
    std::env::var("IRONSHELL_POLICY").is_ok_and(|v| v.trim().eq_ignore_ascii_case("permissive"))
}

/// The decision the policy engine reaches for a given effect under a mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
    /// Run the operation.
    Allow,
    /// Refuse outright (no approval path).
    Deny,
    /// Refuse unless a matching approval token is present.
    Approve,
}

/// The default policy table (§7.1). `permissive` short-circuits to allow-all.
///
/// This is the table's answer and nothing more. For `Network` in agent mode it
/// is `Allow`, and that is not what a call gets: [`effective_decision`] adds the
/// egress rule, which `guard` applies. Ask `effective_decision` what will happen.
pub fn decide(effect: Effect, mode: Mode) -> Decision {
    if policy_permissive() {
        return Decision::Allow;
    }
    match mode {
        Mode::Human => Decision::Allow,
        Mode::Agent => match effect {
            Effect::Pure | Effect::ReadLocal | Effect::WriteLocal | Effect::Network => {
                Decision::Allow
            }
            Effect::Process | Effect::Destructive | Effect::Exec => Decision::Approve,
            Effect::Privileged => Decision::Deny,
        },
    }
}

/// The decision `guard` applies: [`decide`], plus the egress rule.
///
/// `decide` allows `Network` in agent mode, but reaching a host is a grant, not a
/// default. With no `IRONSHELL_NET_ALLOW` allowlist, agent mode asks for approval
/// first, so `http_get`, `web_fetch`, `git_fetch` and `ai` return
/// `E_NEEDS_APPROVAL` until the operator names hosts or approves the call. Under
/// an allowlist, `Allow` stands and `egress_permitted` judges the destination.
/// Permissive policy allows everything.
pub fn effective_decision(effect: Effect, mode: Mode) -> Decision {
    let decision = decide(effect, mode);
    if decision == Decision::Allow
        && effect == Effect::Network
        && mode == Mode::Agent
        && !policy_permissive()
        && net_allowlist().is_none()
    {
        return Decision::Approve;
    }
    decision
}

// ════════════════════════════════════════════════════════════════════════
// Structured errors (§5.2, §7.3)
// ════════════════════════════════════════════════════════════════════════

/// Stable, machine-branchable error/refusal codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorCode {
    PolicyDeny,
    NeedsApproval,
    OutsideWorkspace,
    /// A builtin was called with a missing or wrong-typed argument.
    BadArg,
    /// A well-formed argument whose value makes the operation undefined, such as
    /// a zero divisor. It reports the wire code `E_BAD_ARG` like `BadArg`, so an
    /// agent branches on one code for bad arguments, but it is not retryable:
    /// the same value fails the same way, and only the caller's data can change
    /// that. `BadArg` stays retryable because a corrected call can succeed.
    BadValue,
    /// An Int operation whose result does not fit in 64 bits: `+`, `-`, `*`,
    /// `%`, `**` and unary minus. It used to wrap, or panic in a debug build,
    /// and the wrapped number flowed on as an answer. Reported as `E_BAD_VALUE`,
    /// which is documented next to `E_BAD_ARG` (the same call with the same
    /// operands overflows again, so it is not retryable).
    Overflow,
    /// An error the script raised itself with `error(message[, extra])`. The
    /// message is the script's own, and the script can add fields to the record.
    /// Not retryable: the script decided this call fails, and a retry runs the
    /// same script into the same decision.
    User,
    /// A condition the script asserted with `assert(condition[, message])` was
    /// false. Reported as `E_ASSERT`; not retryable for the same reason as `User`.
    Assert,
    /// A resource governor (op count, files, processes, or wall-clock) was hit.
    BudgetExceeded,
    /// A builtin was called by a name that does not exist. Carries
    /// `did_you_mean` candidates; the same name fails again, so it is not
    /// retryable as the same call.
    UnknownBuiltin,
    /// A record field (which is how module functions like `file.read` resolve)
    /// does not exist. Like `UnknownBuiltin`, carries `did_you_mean`.
    UnknownField,
    /// A bare name that nothing binds: not a variable, not a builtin, not a
    /// module. It used to evaluate to null, so a typo ran on and failed later,
    /// or never failed at all. Carries `did_you_mean` drawn from the bound
    /// variables and the builtins. Retryable by naming something that exists.
    UnknownName,
    /// An external tool the builtin shells out to is not installed.
    ///
    /// Distinct from every other code here because the fix is neither a
    /// corrected call nor an approval: it is installing something. Reported as
    /// `Unknown` until now, which told an agent the fault was unidentifiable
    /// when it is one of the most identifiable failures the shell has --
    /// `benches/agentic/uncoded.mjs` found 57 builtins in that state, and
    /// counting them alongside genuine type errors inflated a claim about the
    /// shell with a fact about the machine it ran on.
    ToolMissing,
    /// An interactive prompt was made with no UI attached to answer it.
    ///
    /// `A2UIChannel` is a buffer: `send` queues an event and nothing tracks
    /// whether a UI ever drains it, so `wait_for_response` waited its full
    /// 300-second timeout and then returned `Cancelled` -- which
    /// `prompt_confirm` maps to `Ok(false)`. An agent asking `a2ui_confirm`
    /// with no UI stalled five minutes and received a value indistinguishable
    /// from the user having declined. The fabricated answer is a *decision*,
    /// which is the worst thing to invent.
    ///
    /// Distinct from `NeedsApproval`, which means a human must decide and
    /// *can* be asked. This means nobody is reachable, so retrying is futile
    /// until a UI is attached.
    NoUi,
    /// The builtin exists and the call was well-formed, but IronShell does
    /// not implement the operation and never will by this route.
    ///
    /// `crypto.sign` is the case that named it: it returned prose beginning
    /// `E_UNIMPLEMENTED:` -- a code that did not exist -- so the boundary
    /// stamped it `Unknown` and the real message said `NOTHING WAS VERIFIED`.
    /// An agent told a signature check is *unidentifiably broken* may retry or
    /// route around it; one told the shell does not do signatures must go
    /// elsewhere. The distinction is the whole point of the taxonomy.
    Unimplemented,
    /// A precondition on *session state* was not met: no transaction is open,
    /// SSO was never initialised, no connection has been made.
    ///
    /// Retryable, unlike every other refusal here, but not by correcting the
    /// call -- by making the call that establishes the state first. The hint
    /// names that prerequisite, so this is the one code whose repair is
    /// *another builtin*.
    BadState,
    /// A named thing -- a job, a key, a record -- does not exist.
    ///
    /// Distinct from `UnknownBuiltin` (the *name of a builtin* is wrong) and
    /// from `BadArg` (the argument is the wrong shape). Here the call is
    /// well-formed and the shell understood it; the thing it names is absent.
    NotFound,
    /// An external tool was found and ran, and exited non-zero.
    ///
    /// The opposite end of `ToolMissing`, and the commonest shell-out failure
    /// there is. `docker_ps` named it: on a host where the docker CLI is
    /// installed but the daemon is not running, the builtin reported
    /// `docker ps --format {{json .}} failed: ` -- the tool's stderr was empty,
    /// so the message ended in a colon and said nothing at all, under the code
    /// that means unidentifiable. The status is now carried, and an empty
    /// stderr is stated rather than rendered as silence.
    ToolFailed,
    /// A filesystem operation failed for a reason that is neither
    /// absence nor a refusal: the disk is full, the handle is bad, the
    /// device is gone.
    ///
    /// Absence is `NotFound` and the OS's refusal is `OsDenied`; this is the
    /// rest of `io::ErrorKind`, which is identified even when it is not
    /// actionable. `Unknown` would say the shell has no idea what
    /// happened, and it does.
    Io,
    /// The operating system refused: a file's permissions, another user's
    /// process, a protected one. Not the shell's policy, which is `PolicyDeny`.
    ///
    /// These two used to share `PolicyDeny`, so a count of the shell's own
    /// refusals (the safety benchmarks, an audit review) included every
    /// read-only file it met, and an agent could not tell "the shell will not"
    /// from "this user cannot". Both exit 77, EX_NOPERM, and neither is
    /// retryable unchanged; the hint says what the OS wanted.
    OsDenied,
    /// `crypto_decrypt` could not produce plaintext: the ciphertext is malformed,
    /// the password is wrong, the ciphertext was modified, the plaintext is not
    /// text, or the legacy openssl child refused it.
    ///
    /// Not retryable as the same call: the same ciphertext and password fail the
    /// same way. A different password or an unmodified ciphertext may succeed,
    /// and the hint says which. Reported as `Unknown` until now, which hid the
    /// one failure a decryption caller most needs to recognise.
    DecryptFailed,
    /// FIPS mode refused a hash algorithm that is not on the approved list
    /// (`md5`, `sha1`). Its code is documented in `docs/security/CRYPTO_AND_FIPS.md`
    /// as `E_FIPS_DISALLOWED`, so it keeps that name rather than collapsing into
    /// `PolicyDeny`: operators grep for it. Not retryable; the hint names the
    /// approved algorithms.
    FipsDisallowed,
    /// An in-process cryptographic operation failed: key derivation, cipher
    /// setup, or sealing. Distinct from `DecryptFailed`, which is the caller's
    /// input being wrong; this is the library refusing to produce output for a
    /// valid request. Deterministic for the same input, so not retryable.
    CryptoFailed,
    /// A remote service could not be reached, or answered with a server error:
    /// the marketplace or registry is down, or the connection failed.
    ///
    /// Distinct from `NotFound`, which is only a real 404 or an entry the index
    /// does not list, and from `Io`, which is this machine's disk or input. A
    /// plugin install that could not reach a marketplace used to report
    /// `NotFound`, which sent the caller to search for a name that may exist.
    /// Retryable: the same call may succeed once the remote answers again.
    Network,
    /// A failure that reached the boundary without a specific code. The message
    /// is whatever the builtin produced; treat it as opaque and **not**
    /// retryable — an agent that cannot identify the fault should stop rather
    /// than re-run the same call. Every uncoded failure lands here rather than
    /// escaping as bare prose, so *every* failure is branchable on `.code`.
    Unknown,
}

impl ErrorCode {
    pub fn as_str(&self) -> &'static str {
        match self {
            ErrorCode::PolicyDeny => "E_POLICY_DENY",
            ErrorCode::NeedsApproval => "E_NEEDS_APPROVAL",
            ErrorCode::OutsideWorkspace => "E_OUTSIDE_WORKSPACE",
            ErrorCode::BadArg | ErrorCode::BadValue => "E_BAD_ARG",
            ErrorCode::Overflow => "E_BAD_VALUE",
            ErrorCode::User => "E_USER",
            ErrorCode::Assert => "E_ASSERT",
            ErrorCode::BudgetExceeded => "E_BUDGET_EXCEEDED",
            ErrorCode::UnknownBuiltin => "E_UNKNOWN_BUILTIN",
            ErrorCode::UnknownField => "E_UNKNOWN_FIELD",
            ErrorCode::UnknownName => "E_UNKNOWN_NAME",
            ErrorCode::ToolMissing => "E_TOOL_MISSING",
            ErrorCode::NoUi => "E_NO_UI",
            ErrorCode::Unimplemented => "E_UNIMPLEMENTED",
            ErrorCode::BadState => "E_BAD_STATE",
            ErrorCode::NotFound => "E_NOT_FOUND",
            ErrorCode::ToolFailed => "E_TOOL_FAILED",
            ErrorCode::Io => "E_IO",
            ErrorCode::OsDenied => "E_OS_DENIED",
            ErrorCode::DecryptFailed => "E_DECRYPT_FAILED",
            ErrorCode::FipsDisallowed => "E_FIPS_DISALLOWED",
            ErrorCode::CryptoFailed => "E_CRYPTO_FAILED",
            ErrorCode::Network => "E_NETWORK",
            ErrorCode::Unknown => "E_UNKNOWN",
        }
    }

    /// Whether re-running the call *with a correction* can plausibly succeed.
    ///
    /// This is the field a self-healing loop branches on, so it is deliberately
    /// conservative: a refusal (`PolicyDeny`), an exhausted envelope
    /// (`BudgetExceeded`), and an unidentified fault (`Unknown`) all report
    /// `false`, because retrying them burns budget without changing the outcome.
    ///
    /// The rule: `true` when the same call, retried later or with its arguments
    /// corrected as the hint says, can succeed (bad arguments, an unknown name
    /// with a suggestion, not found, needs approval); `false` when it can never
    /// succeed as asked. It is decided here, by code, and nowhere else.
    pub fn retryable(&self) -> bool {
        match self {
            ErrorCode::BadArg | ErrorCode::UnknownField => true,
            // Retryable by naming a variable or builtin that exists.
            ErrorCode::UnknownName => true,
            // Retryable by naming something that exists...
            ErrorCode::NotFound => true,
            // ...and this one by running the prerequisite the hint names, not
            // by changing anything about this call.
            ErrorCode::BadState => true,
            ErrorCode::NeedsApproval => true,
            // Not retryable: the same value is undefined on every attempt.
            ErrorCode::BadValue => false,
            // The same operands overflow again; only different operands can fit.
            ErrorCode::Overflow => false,
            // Retryable by naming a real builtin, which is what did_you_mean
            // carries. `SafetyError::is_retryable` narrows this to the calls
            // that have a candidate: with none, the same name fails again.
            ErrorCode::UnknownBuiltin => true,
            // Not retryable: the same path is outside the same workspace. The
            // fix is a path inside it, which is a different call, or the
            // operator widening the workspace, which no retry can do.
            ErrorCode::OutsideWorkspace => false,
            // Not retryable: the same call fails identically until someone
            // installs the tool, which is an action outside this process.
            ErrorCode::ToolMissing => false,
            // Nor this one: no correction to the call attaches a UI.
            ErrorCode::NoUi => false,
            // Nor this one: the operation is absent from the shell, so there
            // is no call that would have worked.
            ErrorCode::Unimplemented => false,
            // The tool ran and rejected the work. Conservative, per this
            // method's contract: an agent that wants to retry after fixing
            // the environment can, but nothing here promises it will help.
            ErrorCode::ToolFailed => false,
            // The disk does not get less full because the call was made
            // twice.
            ErrorCode::Io => false,
            // The same user asking again is refused again; another user, or
            // other permissions, is an action outside this call.
            ErrorCode::OsDenied => false,
            // The same ciphertext and password fail identically on a second
            // call; only a different input can change the outcome.
            ErrorCode::DecryptFailed => false,
            ErrorCode::FipsDisallowed => false,
            ErrorCode::CryptoFailed => false,
            // The remote may answer the same call next time; nothing local
            // about the call needs to change.
            ErrorCode::Network => true,
            ErrorCode::PolicyDeny | ErrorCode::BudgetExceeded | ErrorCode::Unknown => false,
            ErrorCode::User | ErrorCode::Assert => false,
        }
    }

    /// The process exit status this failure leaves behind.
    ///
    /// Measured against bash, PowerShell and nushell on ten induced failures
    /// (`benches/agentic/errors.mjs`), IronShell scored 0 of 10 on
    /// exit-status granularity: every failure exited 1. bash scored 5 of 10 and
    /// was the only shell to offer anything here. That is free signal — a
    /// caller, a `set -e` wrapper or a CI step can branch on it without reading
    /// stderr at all — and we were discarding it.
    ///
    /// Two of these deliberately borrow bash's conventions rather than invent
    /// better ones, because an agent that already knows shell gets them for
    /// free: **127** for a name that does not resolve, **2** for a syntax
    /// error. The rest follow `sysexits.h`, which is the closest thing to a
    /// convention for the others.
    ///
    /// `Unknown` stays 1: an unidentified fault should look like the generic
    /// failure it is, not claim a precision the shell does not have.
    pub fn exit_code(&self) -> i32 {
        match self {
            // bash: "command not found". A missing external tool is the same
            // condition one level out, and an agent that knows shell reads 127
            // without being told.
            ErrorCode::UnknownBuiltin | ErrorCode::UnknownName | ErrorCode::ToolMissing => 127,
            // EX_USAGE — the call was malformed.
            ErrorCode::BadArg
            | ErrorCode::BadValue
            | ErrorCode::Overflow
            | ErrorCode::UnknownField => 64,
            // EX_NOPERM — refused, and retrying unchanged will refuse again.
            ErrorCode::PolicyDeny | ErrorCode::OutsideWorkspace => 77,
            // EX_TEMPFAIL — the same call may succeed once approved.
            ErrorCode::NeedsApproval => 75,
            // EX_UNAVAILABLE — the envelope is spent, or the UI that would
            // have answered is not there.
            ErrorCode::BudgetExceeded | ErrorCode::NoUi | ErrorCode::ToolFailed => 69,
            // EX_UNAVAILABLE -- the remote service could not be reached.
            ErrorCode::Network => 69,
            // EX_SOFTWARE -- the fault is in what the shell offers, not in
            // the call or the environment.
            ErrorCode::Unimplemented => 70,
            // EX_NOINPUT -- the thing named could not be opened.
            ErrorCode::NotFound => 66,
            // EX_PROTOCOL -- issued out of sequence.
            ErrorCode::BadState => 76,
            // EX_IOERR.
            ErrorCode::Io => 74,
            // EX_NOPERM -- the operating system refused, as PolicyDeny's 77
            // is the shell refusing.
            ErrorCode::OsDenied => 77,
            // EX_DATAERR -- the input data was incorrect: the ciphertext, the
            // password, or what they decode to.
            ErrorCode::DecryptFailed => 65,
            // EX_NOPERM -- refused by policy, like PolicyDeny.
            ErrorCode::FipsDisallowed => 77,
            // EX_SOFTWARE -- the library failed on a valid request.
            ErrorCode::CryptoFailed => 70,
            // The script's own failure: the generic failure status, as Unknown's.
            ErrorCode::User | ErrorCode::Assert => 1,
            ErrorCode::Unknown => 1,
        }
    }

    /// [`ErrorCode::exit_code`] for a code as it appears on the wire (a response's
    /// `code`): `E_PARSE` is 2 as a syntax error is, an unlisted code is 1.
    pub fn exit_code_for_wire(code: &str) -> i32 {
        const ALL: &[ErrorCode] = &[
            ErrorCode::PolicyDeny,
            ErrorCode::NeedsApproval,
            ErrorCode::OutsideWorkspace,
            ErrorCode::BadArg,
            ErrorCode::Overflow,
            ErrorCode::User,
            ErrorCode::Assert,
            ErrorCode::BudgetExceeded,
            ErrorCode::UnknownBuiltin,
            ErrorCode::UnknownField,
            ErrorCode::UnknownName,
            ErrorCode::ToolMissing,
            ErrorCode::NoUi,
            ErrorCode::Unimplemented,
            ErrorCode::BadState,
            ErrorCode::NotFound,
            ErrorCode::ToolFailed,
            ErrorCode::Io,
            ErrorCode::OsDenied,
            ErrorCode::DecryptFailed,
            ErrorCode::FipsDisallowed,
            ErrorCode::CryptoFailed,
            ErrorCode::Network,
            ErrorCode::Unknown,
        ];
        if code == "E_PARSE" {
            return 2;
        }
        ALL.iter()
            .find(|c| c.as_str() == code)
            .map_or(1, |c| c.exit_code())
    }
}

/// Build a structured argument error (`E_BAD_ARG`). Threads through `anyhow`/`?`
/// like any error, and — because it is a [`SafetyError`] — is caught by the
/// evaluator's try/catch as a structured `{error: {code, message, hint, …}}`
/// record, so an agent can branch on `e.error.code` and read the expected
/// signature instead of parsing prose. `got` is the offending value's type name
/// (e.g. `value.type_name()`), or `"nothing"` when an argument is missing.
/// Build a structured "external tool is not installed" error
/// (`E_TOOL_MISSING`).
///
/// `tool` is the executable that could not be started, `builtin` the thing the
/// caller invoked, and `cause` the underlying OS error. The hint names the tool
/// rather than the builtin, because installing it is the only thing that helps.
/// Build a structured "no UI is attached" error (`E_NO_UI`).
///
/// For an interactive prompt made when nothing is listening. The alternative
/// was waiting five minutes and returning `false`, which an agent cannot tell
/// from the user declining.
pub fn no_ui(builtin: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::NoUi,
        message: format!("{builtin}: no UI is attached to answer this prompt"),
        builtin: builtin.to_string(),
        hint: "attach a UI (`ish tui`) or avoid interactive builtins in agent mode".to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "a UI listening for prompts".to_string(),
        got: "nothing attached".to_string(),
        extra: serde_json::Map::new(),
    })
}

pub fn tool_missing(builtin: &str, tool: &str, cause: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::ToolMissing,
        message: format!("{builtin}: `{tool}` is not installed ({cause})"),
        builtin: builtin.to_string(),
        hint: format!("install `{tool}` and run this again; no change to the call will help"),
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("`{tool}` on PATH"),
        got: "not installed".to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured "IronShell does not implement this" error
/// (`E_UNIMPLEMENTED`).
///
/// `what` states the operation *and any safety consequence*:
/// `crypto.verify_signature` must be able to say NOTHING WAS VERIFIED in the
/// message rather than bury it in a hint. `instead` names the route that does
/// work, which is the only useful thing to add, because no correction to the
/// call will help.
/// Callers that previously wrote `E_UNIMPLEMENTED:` into the message text
/// were describing a code the taxonomy did not have; the boundary stamped
/// those `E_UNKNOWN`, so the prose said one thing and the field said another.
pub fn unimplemented(builtin: &str, what: &str, instead: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::Unimplemented,
        message: format!("{builtin}: {what}"),
        builtin: builtin.to_string(),
        hint: format!("{instead}; no change to this call will make it work"),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "an operation IronShell implements".to_string(),
        got: "one it does not".to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured "the external tool ran and failed" error
/// (`E_TOOL_FAILED`).
///
/// Carries the tool's own exit status, which is the part an agent can act on
/// and which the old `"{prog} {args} failed: {stderr}"` prose discarded. When
/// stderr is empty the message says so: a message that trails off after a
/// colon reads as a truncation bug, and on the host that found this the
/// silence *was* the whole diagnosis -- the daemon was not running.
pub fn tool_failed(
    builtin: &str,
    command: &str,
    status: Option<i32>,
    stderr: &str,
) -> anyhow::Error {
    let status_text = match status {
        Some(c) => format!("exited {c}"),
        None => "was killed by a signal".to_string(),
    };
    tool_failed_text(builtin, command, status_text, stderr, None)
}

/// [`tool_failed`] whose hint is `hint` in place of the one that says the tool
/// is installed but rejected the work. For a failure whose cause the tool's own
/// stderr names, such as a SQL statement that does not parse.
pub fn tool_failed_hinted(
    builtin: &str,
    command: &str,
    status: Option<i32>,
    stderr: &str,
    hint: &str,
) -> anyhow::Error {
    let status_text = match status {
        Some(c) => format!("exited {c}"),
        None => "was killed by a signal".to_string(),
    };
    tool_failed_text(builtin, command, status_text, stderr, Some(hint))
}

/// [`tool_failed`] for an exit code that is an HRESULT-style value, such as a
/// winget `APPINSTALLER_CLI_ERROR_*` code. It is shown in hex (`0x8A150001`),
/// because the decimal form of those codes is unrecognisable.
pub fn tool_failed_code(builtin: &str, command: &str, code: u32, stderr: &str) -> anyhow::Error {
    tool_failed_text(
        builtin,
        command,
        format!("exited 0x{code:08X}"),
        stderr,
        None,
    )
}

/// The hint for a tool that ran and failed. "Check that its service is
/// running" is only true of a client for a daemon; a program that crashed (a
/// signal, or a status such as -1073741819) or that rejected its arguments gets
/// a hint that says what happened.
fn tool_failed_default_hint(command: &str, status_text: &str) -> String {
    const SERVICE_CLIENTS: &[&str] = &[
        "docker",
        "podman",
        "kubectl",
        "helm",
        "systemctl",
        "launchctl",
        "service",
        "sc",
        "nerdctl",
        "colima",
    ];
    let program = command
        .split_whitespace()
        .next()
        .unwrap_or(command)
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(command)
        .trim_end_matches(".exe")
        .to_ascii_lowercase();
    if status_text == "was killed by a signal" {
        return format!(
            "`{command}` was killed by a signal before it finished; run it by hand to see why"
        );
    }
    let code = status_text
        .strip_prefix("exited ")
        .and_then(|c| c.parse::<i64>().ok());
    if let Some(c) = code {
        if !(0..=255).contains(&c) {
            return format!("the program crashed (status {c}); run `{command}` by hand to see why");
        }
    }
    if SERVICE_CLIENTS.contains(&program.as_str()) {
        format!(
            "`{command}` is installed but rejected this work; check that its \
             service is running and that the arguments are valid for this host"
        )
    } else {
        format!(
            "`{command}` is installed but rejected this work; check that the \
             arguments are valid for this host"
        )
    }
}

fn tool_failed_text(
    builtin: &str,
    command: &str,
    status_text: String,
    stderr: &str,
    hint: Option<&str>,
) -> anyhow::Error {
    let stderr = stderr.trim();
    let said = if stderr.is_empty() {
        "and printed nothing to stderr".to_string()
    } else {
        format!("saying: {stderr}")
    };
    anyhow::Error::new(SafetyError {
        code: ErrorCode::ToolFailed,
        message: format!("{builtin}: `{command}` {status_text} {said}"),
        builtin: builtin.to_string(),
        hint: match hint {
            Some(hint) => hint.to_string(),
            None => tool_failed_default_hint(command, &status_text),
        },
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("`{command}` to exit 0"),
        got: status_text,
        extra: serde_json::Map::new(),
    })
}

/// Build a structured "precondition not met" error (`E_BAD_STATE`).
///
/// `needs` names the call that establishes the state, so a self-healing loop
/// has somewhere to go: this is the one retryable code whose repair is a
/// *different builtin* rather than a corrected argument.
pub fn bad_state(builtin: &str, state: &str, needs: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadState,
        message: format!("{builtin}: {state}"),
        builtin: builtin.to_string(),
        hint: format!("call `{needs}` first, then retry this unchanged"),
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("the state left by `{needs}`"),
        got: state.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured "precondition not met" error (`E_BAD_STATE`) whose hint
/// is the caller's own sentence, for a state no other builtin establishes
/// (`bad_state`'s "call X first" would send the caller to the wrong place).
pub fn bad_state_with_hint(builtin: &str, state: &str, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadState,
        message: format!("{builtin}: {state}"),
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "the precondition named in the message".to_string(),
        got: state.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build an `E_IO` error for a fault in the environment the call depends on,
/// such as the system clock or an attached client, rather than in the call.
pub fn io_fault(builtin: &str, what: &str, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::Io,
        message: format!("{builtin}: {what}"),
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "a working environment".to_string(),
        got: what.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build the error for a lock that an earlier call left poisoned (`E_BAD_STATE`).
///
/// A poisoned lock means an earlier call in this process panicked while it
/// held the lock, so the state behind it may be half-written. No other builtin
/// clears that, so the fix is a restart, not a different call. That is why
/// this does not reuse [`bad_state`]: its hint ("call X first") would send a
/// caller to a builtin that cannot clear the poison.
pub fn lock_poisoned(builtin: &str, what: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadState,
        message: format!(
            "{builtin}: {what} is unusable: an earlier call panicked while holding its lock"
        ),
        builtin: builtin.to_string(),
        hint:
            "restart the shell; this process's copy of that state cannot be trusted after the panic"
                .to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "a lock no earlier call left poisoned".to_string(),
        got: "a poisoned lock".to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured "no such thing" error (`E_NOT_FOUND`).
///
/// `kind` is what was being looked up ("job", "key"), `name` the identifier
/// that missed. Retryable, because a different identifier may well exist.
/// The hint for a path with a tab, newline or carriage return in it. In a
/// double-quoted string a backslash starts an escape, so `"C:\temp\new"` is not
/// the path that was written: `\t` is a tab and `\n` a newline. `None` for any
/// other path.
pub fn control_char_path_hint(path: &str) -> Option<&'static str> {
    path.chars().any(|c| matches!(c, '\t' | '\n' | '\r')).then_some(
        "the path contains a tab, newline or carriage return: in a double-quoted string a backslash starts an escape (\\t, \\n, \\r); write forward slashes (C:/temp/new) or double the backslashes",
    )
}

pub fn not_found(builtin: &str, kind: &str, name: &str) -> anyhow::Error {
    // A path is not an identifier. For a file or directory the useful facts are
    // where a relative path was resolved and how to look, not a list to choose
    // an identifier from.
    let is_path = matches!(kind, "source" | "destination" | "path");
    let hint = if is_path || matches!(kind, "file" | "directory" | "archive") {
        let here = std::env::current_dir()
            .map(|d| d.display().to_string())
            .unwrap_or_else(|_| "the current directory".to_string());
        control_char_path_hint(name)
            .map(str::to_string)
            .unwrap_or_else(|| {
                let what = if is_path { "file or directory" } else { kind };
                format!(
                    "no {what} at this path; a relative path is resolved against {here}, so \
                     check the spelling and that directory, or list it with ls() first"
                )
            })
    } else {
        format!(
            "list the available {kind}{} and use an identifier from it",
            // "processes", not "processs".
            if kind.ends_with('s') || kind.ends_with("sh") || kind.ends_with("ch") {
                "es"
            } else {
                "s"
            }
        )
    };
    anyhow::Error::new(SafetyError {
        code: ErrorCode::NotFound,
        message: if is_path {
            format!("{builtin}: no file or directory at `{name}`")
        } else {
            format!("{builtin}: no {kind} named '{name}'")
        },
        builtin: builtin.to_string(),
        hint,
        approval: None,
        did_you_mean: Vec::new(),
        expected: if is_path {
            "an existing file or directory".to_string()
        } else {
            format!("an existing {kind}")
        },
        got: name.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// `E_NOT_FOUND` for a journal step id that no step has. The journal's own
/// word is "step": an id names a step, and "entry" is the file-edit term.
pub fn journal_step_not_found(builtin: &str, id: usize) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::NotFound,
        message: format!("{builtin}: no journal step with id {id}"),
        builtin: builtin.to_string(),
        hint: "list the available journal steps with journal() and use an id from them".to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "an existing journal step".to_string(),
        got: id.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// A file edit whose target does not exist: E_NOT_FOUND, checked before any
/// pattern is looked for, so a missing file is not reported as a missing
/// pattern.
pub fn no_file_at(builtin: &str, path: &str) -> anyhow::Error {
    if let Some(parent) = missing_parent_of(path) {
        return parent_missing(builtin, path, &parent);
    }
    let here = std::env::current_dir()
        .map(|d| d.display().to_string())
        .unwrap_or_else(|_| "the current directory".to_string());
    anyhow::Error::new(SafetyError {
        code: ErrorCode::NotFound,
        message: format!("{builtin}: no file at {path}"),
        builtin: builtin.to_string(),
        hint: control_char_path_hint(path)
            .map(str::to_string)
            .unwrap_or_else(|| {
                format!(
                    "no file at this path; a relative path is resolved against {here}, so check \
                 the spelling and that directory, or create the file with file.write first"
                )
            }),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "an existing file".to_string(),
        got: path.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// The directory `path` would be created in, when that directory does not exist.
/// `None` when the path has no directory part, when the directory is there, when
/// it cannot be told (only a missing directory is an answer), and for a remote
/// share, which is not probed: asking Windows about one opens a session.
pub fn missing_parent_of(path: &str) -> Option<String> {
    if names_a_remote_share(path) {
        return None;
    }
    let parent = std::path::Path::new(path).parent()?;
    if parent.as_os_str().is_empty() {
        return None;
    }
    match std::fs::metadata(parent) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            Some(strip_verbatim_prefix(parent).display().to_string())
        }
        _ => None,
    }
}

/// A write to a file whose directory does not exist. Writing the file cannot
/// create its directory, so the hint names the directory and says to create it.
pub fn parent_missing(builtin: &str, path: &str, parent: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::NotFound,
        message: format!(
            "{builtin}: the folder '{parent}' does not exist; create it with mkdir(\"{parent}\")"
        ),
        builtin: builtin.to_string(),
        hint: format!(
            "mkdir creates the folder and mkdirp also creates missing parents; then run the call again for '{path}'"
        ),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "an existing directory".to_string(),
        got: parent.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// The `IRONSHELL_*` settings that bound a shell. A descendant keeps them: any
/// child may start `ish`, directly or through a script, and that `ish` must be
/// held by the same workspace, policy and limits as this one. None of them is a
/// credential, and each one only applies to a shell.
const CONFINING_ENV: &[&str] = &[
    "IRONSHELL_MODE",
    "IRONSHELL_AGENT",
    "IRONSHELL_POLICY",
    "IRONSHELL_WORKSPACE",
    PINNED_ROOT_ENV,
    "IRONSHELL_MAX_NET",
    "IRONSHELL_MAX_FILES",
    "IRONSHELL_MAX_OPS",
    "IRONSHELL_MAX_PROCS",
    "IRONSHELL_TIMEOUT_MS",
    "IRONSHELL_TOKEN_BUDGET",
    "IRONSHELL_NET_ALLOW",
    "IRONSHELL_FIPS",
    "IRONSHELL_DETERMINISTIC",
    "IRONSHELL_RBAC_CONFIG",
    "IRONSHELL_PRINCIPAL",
    "IRONSHELL_AUDIT_LOG",
    "IRONSHELL_AUDIT_REQUIRED",
    // An operator's refusal of reads through hard links; a child keeps it.
    "IRONSHELL_REFUSE_LINKED_READS",
    // The script nesting depth (posix.rs). Kept, so a child `ish` started by a
    // program rather than by a script still counts its depth from the parent.
    "IRONSHELL_SCRIPT_DEPTH",
];

/// Remove the shell's own `IRONSHELL_*` settings from a child's environment.
///
/// A child inherits whatever environment the shell holds, so a credential such
/// as `IRONSHELL_API_KEY` would reach any program the shell starts. Everything
/// is removed but [`CONFINING_ENV`]. The opt-outs go too (`IRONSHELL_APPROVE`,
/// `IRONSHELL_REDACT=off`), so a descendant shell is never looser than this one.
/// A variable the caller set on `cmd` with [`std::process::Command::env`] is the
/// caller's named choice, and it is kept.
///
/// In agent mode a credential is removed too: any variable [`is_secret_name`]
/// matches (`*TOKEN*`, `*_API_KEY`, `*SECRET*`, `*PASSWORD*`, `*CREDENTIAL*`, and
/// the like, which covers `AWS_SECRET_ACCESS_KEY`, `GITHUB_TOKEN`, `GH_TOKEN`,
/// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`), unless the operator names it in
/// `IRONSHELL_CHILD_ENV_KEEP` (comma-separated exact names, e.g. `GH_TOKEN` for
/// `gh`). Human mode is unchanged: a person running a program gets their own
/// environment. A child that a builtin needs a token for and does not get it
/// fails with its own error, as it would with no token set.
///
/// Agent mode can be set by other means than the variable, so every child gets
/// `IRONSHELL_MODE=agent` then. Any program may start `ish`, and without the
/// variable that `ish` would be in human mode, which is ungated.
pub(crate) fn strip_ironshell_env(cmd: &mut std::process::Command) {
    let explicit: Vec<std::ffi::OsString> = cmd
        .get_envs()
        .filter(|(_, value)| value.is_some())
        .map(|(name, _)| name.to_os_string())
        .collect();
    let agent = current_mode() == Mode::Agent;
    let keep = if agent { child_env_keep() } else { Vec::new() };
    for (name, _) in std::env::vars_os() {
        let shell_var = name
            .to_str()
            .is_some_and(|n| n.to_ascii_uppercase().starts_with("IRONSHELL_"));
        let confining = CONFINING_ENV.iter().any(|c| name.eq_ignore_ascii_case(c));
        let credential = agent
            && is_secret_name(&name.to_string_lossy())
            && !keep
                .iter()
                .any(|k| k.eq_ignore_ascii_case(&name.to_string_lossy()));
        let named = explicit.iter().any(|e| e.eq_ignore_ascii_case(&name));
        if ((shell_var && !confining) || credential) && !named {
            cmd.env_remove(&name);
        }
    }
    if agent {
        cmd.env("IRONSHELL_MODE", "agent");
    }
}

/// A `Command` for a program the shell starts, with the shell's own settings
/// already stripped (see [`strip_ironshell_env`]). Every spawn in `src/` goes
/// through here, so none inherits a credential or an opt-out by accident.
/// `tests/child_spawn_ratchet.rs` keeps a raw constructor call out of `src/`.
pub fn child_command(program: impl AsRef<std::ffi::OsStr>) -> std::process::Command {
    let mut cmd = std::process::Command::new(program);
    strip_ironshell_env(&mut cmd);
    cmd
}

/// The variable that names credentials a child keeps in agent mode, as
/// comma-separated exact names. Read by [`strip_ironshell_env`].
pub const CHILD_ENV_KEEP: &str = "IRONSHELL_CHILD_ENV_KEEP";

/// The names in [`CHILD_ENV_KEEP`], trimmed, with empty entries dropped.
fn child_env_keep() -> Vec<String> {
    std::env::var(CHILD_ENV_KEEP)
        .unwrap_or_default()
        .split(',')
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(str::to_string)
        .collect()
}

/// Run a command and give up on it after `secs`.
///
/// `Command::output()` waits forever. For an interactive shell that is
/// correct; for a builtin an agent calls, a hang is worse than any error,
/// because a failure can be branched on and a hang cannot -- it burns the
/// whole turn and returns nothing to reason about.
///
/// Two were found by sweeping rather than by reading: `gui_dialog_file_save`
/// blocked on a desktop dialog nobody was there to dismiss, and
/// `syslog_search` blocked in `journalctl` on a host with no running
/// journal. Both looked like success to a harness without a timeout, which
/// is how they survived.
///
/// stdout and stderr are drained on their own threads. Polling `try_wait`
/// while the child writes to a pipe nobody reads deadlocks once the pipe
/// buffer fills, which would turn a timeout guard into a new way to hang.
pub fn output_with_timeout(
    cmd: std::process::Command,
    secs: u64,
) -> std::io::Result<std::process::Output> {
    use crate::builtins::{Keep, TreeError};

    // Output past this is refused, not cut short: a report that stops partway
    // would look whole to the caller.
    const OUTPUT_LIMIT: usize = 64 * 1024 * 1024;
    let program = cmd.get_program().to_string_lossy().into_owned();
    let run = crate::builtins::run_tree_cmd(
        cmd,
        None,
        std::time::Duration::from_secs(secs),
        Keep::Head(OUTPUT_LIMIT),
        Keep::Head(OUTPUT_LIMIT),
    )
    .map_err(|e| match e {
        TreeError::Spawn(e) | TreeError::Wait(e) => e,
    })?;
    let status = match run.status {
        Some(status) if !run.timed_out => status,
        _ => {
            return Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                format!("no response after {secs}s"),
            ))
        }
    };
    if run.stdout_truncated || run.stderr_truncated {
        return Err(std::io::Error::other(budget_error(
            &program,
            format!("printed more than {OUTPUT_LIMIT} bytes"),
            "the output was not used; the call was refused rather than cut short",
        )));
    }
    Ok(std::process::Output {
        status,
        stdout: run.stdout,
        stderr: run.stderr,
    })
}

/// The coded budget error an [`output_with_timeout`] refusal carries, if `e`
/// is one. Callers that map io errors pass it through unchanged.
pub fn io_budget_error(e: &std::io::Error) -> Option<anyhow::Error> {
    let se = e
        .get_ref()
        .and_then(|inner| inner.downcast_ref::<SafetyError>())?;
    Some(anyhow::Error::new(se.clone()))
}

/// Classify a failure to *start* an external process.
///
/// `Command::new(prog).output()?` propagates a bare `io::Error`, and what
/// reaches an agent is `No such file or directory (os error 2)` -- no code, no
/// builtin, not even the name of the program that was missing. Thirteen
/// builtins were still answering exactly that after `E_TOOL_MISSING` existed,
/// because the code was added at the sites that *named* their tool and these
/// never did.
///
/// `NotFound` is the overwhelmingly common case and is what `ToolMissing` is
/// for. Anything else -- a permission denial, a broken interpreter line -- is
/// the tool being unusable rather than absent, and saying "install it" there
/// would be advice that cannot work.
pub fn spawn_error(builtin: &str, tool: &str, e: &std::io::Error) -> anyhow::Error {
    // A coded error an io-returning runner already made (a refused output) is
    // the answer, not a failure to start.
    if let Some(coded) = io_budget_error(e) {
        return coded;
    }
    // `output_with_timeout` reports its deadline as `TimedOut`: the tool ran
    // and was stopped, which is a budget, not a failure to start.
    if e.kind() == std::io::ErrorKind::TimedOut {
        return budget_exceeded(
            builtin,
            format!("`{tool}` did not finish in time and was stopped: {e}"),
            "a stopped tool can leave work half done; check the state before retrying",
        );
    }
    if e.kind() == std::io::ErrorKind::NotFound {
        return tool_missing(builtin, tool, &e.to_string());
    }
    // execvp answers EACCES, not ENOENT, for a name found nowhere when one
    // PATH directory could not be searched; the tool is absent, not unrunnable.
    #[cfg(unix)]
    if e.kind() == std::io::ErrorKind::PermissionDenied
        && !tool.contains('/')
        && !std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
            .any(|dir| dir.join(tool).is_file())
    {
        return tool_missing(
            builtin,
            tool,
            &format!("{e}, from a PATH directory that could not be searched"),
        );
    }
    anyhow::Error::new(SafetyError {
        code: ErrorCode::ToolFailed,
        message: format!("{builtin}: could not start `{tool}`: {e}"),
        builtin: builtin.to_string(),
        hint: format!(
            "`{tool}` exists but could not be run; check its permissions and \
             that it is executable on this host"
        ),
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("`{tool}` to start"),
        got: e.kind().to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured decryption failure (`E_DECRYPT_FAILED`).
///
/// `message` states what failed and must not repeat the code name; `hint` says
/// what the caller can change. Not retryable as the same call.
pub fn decrypt_failed(
    builtin: &str,
    message: impl Into<String>,
    hint: impl Into<String>,
) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::DecryptFailed,
        message: message.into(),
        builtin: builtin.to_string(),
        hint: hint.into(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// The structured error for a hash, MAC or random-number call that IronCrypto
/// refused. The refusal comes from its self-test or an error state; the same
/// call fails the same way, so the hint says not to retry it unchanged.
pub fn ic_refusal(builtin: &str, e: ironcrypto::core_types::Error) -> SafetyError {
    SafetyError {
        code: ErrorCode::CryptoFailed,
        message: format!("IronCrypto refused the operation ({e})"),
        builtin: builtin.to_string(),
        hint: "nothing was computed; do not retry this call unchanged, because the cryptographic module refused it".to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    }
}

/// [`ic_refusal`] as an `anyhow` error, for the builtins that return one.
pub fn ic_failed(builtin: &str, e: ironcrypto::core_types::Error) -> anyhow::Error {
    anyhow::Error::new(ic_refusal(builtin, e))
}

/// Fill `out` with bytes from IronCrypto's HMAC-DRBG, seeded from the operating
/// system. Every secret in IronShell (salts, nonces, tokens, keys) is drawn
/// through here; `rand::thread_rng` is not used for them.
pub fn ic_fill_random(builtin: &str, out: &mut [u8]) -> anyhow::Result<()> {
    let mut rng = ironcrypto::drbg::Rng::from_os().map_err(|e| ic_failed(builtin, e))?;
    rng.fill(out).map_err(|e| ic_failed(builtin, e))
}

/// Build a structured in-process cryptography failure (`E_CRYPTO_FAILED`).
///
/// `message` states what failed and must not repeat the code name; `hint` says
/// what the caller can change. Not retryable as the same call.
pub fn crypto_failed(
    builtin: &str,
    message: impl Into<String>,
    hint: impl Into<String>,
) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::CryptoFailed,
        message: message.into(),
        builtin: builtin.to_string(),
        hint: hint.into(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured "that path is outside the workspace" error
/// (`E_OUTSIDE_WORKSPACE`).
///
/// The code existed from the start and had no constructor, so the one place
/// that actually detects the condition -- `security::validate_safe_path` --
/// reported it as bare prose and it arrived as `E_UNKNOWN`. The containment
/// boundary is the single most important thing for an agent to be able to
/// branch on, and it was the least legible.
pub fn outside_workspace(builtin: &str, path: &str) -> anyhow::Error {
    outside_workspace_shown(builtin, path, path)
}

/// [`outside_workspace`] for a path shown in a shortened form. `raw` is the path
/// as the caller wrote it: its control characters, which the shortened form may
/// have dropped, decide the hint.
pub fn outside_workspace_shown(builtin: &str, shown: &str, raw: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::OutsideWorkspace,
        message: format!("{builtin}: `{shown}` is outside the workspace"),
        builtin: builtin.to_string(),
        hint: control_char_path_hint(raw)
            .map(str::to_string)
            .unwrap_or_else(outside_workspace_hint),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "a path inside the workspace".to_string(),
        got: shown.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// The hint for `E_OUTSIDE_WORKSPACE`. It names the root and tells the caller to
/// use a path inside it. It does not tell the caller how to widen the workspace:
/// that decision belongs to the operator, and an agent that is told how to widen
/// its own jail will do it.
pub fn outside_workspace_hint() -> String {
    format!(
        "use a path inside the workspace root {}; only the operator can widen the workspace",
        workspace_root().display()
    )
}

/// Classify a filesystem failure.
///
/// The counterpart to [`spawn_error`], and found the same way: the
/// catalogue sweep probes each builtin once, so it never reaches a second
/// failure path. A second sweep -- every builtin handed a well-formed path
/// that does not exist -- found 54 builtins answering `E_UNKNOWN`, nine of
/// them with nothing but `No such file or directory (os error 2)`.
///
/// A missing file is the commonest failure any shell has, and it was the
/// one code an agent is told not to reason about.
/// `path` is `impl AsRef<Path>` because call sites hold a `String`, a
/// `PathBuf` or a `&str` depending on whether the path has been through
/// `validate_read_path` yet, and a uniform signature beats 36 conversions.
pub fn fs_error(
    builtin: &str,
    path: impl AsRef<std::path::Path>,
    e: &std::io::Error,
) -> anyhow::Error {
    fs_error_as(builtin, path, e, false)
}

/// [`fs_error`] for a failed write: the message says `cannot write`, and the
/// expectation is a writable path. A write that fails on a name the filesystem
/// refuses (such as an NTFS alternate stream) read as a read failure before.
pub fn fs_write_error(
    builtin: &str,
    path: impl AsRef<std::path::Path>,
    e: &std::io::Error,
) -> anyhow::Error {
    fs_error_as(builtin, path, e, true)
}

/// Whether an OS error says a directory is not empty: `ERROR_DIR_NOT_EMPTY`
/// (145) on Windows, `ENOTEMPTY` (39 on Linux, 66 elsewhere on Unix).
pub fn dir_not_empty(e: &std::io::Error) -> bool {
    if e.kind() == std::io::ErrorKind::DirectoryNotEmpty {
        return true;
    }
    let code = e.raw_os_error();
    if cfg!(windows) {
        code == Some(145)
    } else if cfg!(target_os = "linux") {
        code == Some(39)
    } else if cfg!(unix) {
        code == Some(66)
    } else {
        false
    }
}

fn fs_error_as(
    builtin: &str,
    path: impl AsRef<std::path::Path>,
    e: &std::io::Error,
    writing: bool,
) -> anyhow::Error {
    let (verb, expected_access) = if writing {
        ("write", "writable")
    } else {
        ("read", "readable")
    };
    // A canonicalised path carries the `\\?\` verbatim prefix on Windows. The
    // message shows the ordinary form, as the other builtins' paths do.
    let path = strip_verbatim_prefix(path.as_ref()).display().to_string();
    let path = path.as_str();
    // The name the caller typed: file_mkdir is spelled `mkdir`.
    let shown = if builtin == "file_mkdir" {
        "mkdir"
    } else {
        builtin
    };
    match e.kind() {
        std::io::ErrorKind::NotFound => match writing.then(|| missing_parent_of(path)).flatten() {
            Some(parent) => parent_missing(builtin, path, &parent),
            None => not_found(builtin, "file", path),
        },
        // Windows refuses a read or write that opens a directory with access
        // denied. The caller named a directory where a file belongs, which is
        // not a permission problem; a remote-share name is not probed (see
        // names_a_remote_share).
        std::io::ErrorKind::PermissionDenied
            if !names_a_remote_share(path) && std::path::Path::new(path).is_dir() =>
        {
            bad_value_in(
                builtin,
                format!("{builtin}: `{path}` is a directory, not a file"),
                &format!(
                    "pass a file; to act on a directory's files, name them with a glob such as '{path}/**/*'"
                ),
            )
        }
        // The OS refused, not our policy.
        std::io::ErrorKind::PermissionDenied => os_denied(
            builtin,
            format!("{builtin}: the operating system denied access to `{path}`"),
            "check the file's permissions and owner; the shell did not refuse this",
        ),
        // A directory with something in it is not removed by rmdir without
        // `recursive`. The OS says so; the caller needs the fix, not the code.
        _ if dir_not_empty(e) => bad_state_with_hint(
            shown,
            &format!("`{path}` is not empty"),
            &if builtin == "rmdir" {
                format!("rmdir(\"{path}\", true) removes it and its contents")
            } else {
                "a directory is removed only when it is empty; empty it first".to_string()
            },
        ),
        // The name is taken. For mkdir that is a file (or a directory it
        // would have made), and the caller must choose another path.
        _ if e.kind() == std::io::ErrorKind::AlreadyExists
            || (cfg!(windows) && e.raw_os_error() == Some(183)) =>
        {
            if std::path::Path::new(path).is_file() {
                bad_state_with_hint(
                    shown,
                    &format!("`{path}` exists and is a file"),
                    "choose another path, or remove that file first",
                )
            } else {
                bad_state_with_hint(
                    shown,
                    &format!("`{path}` already exists"),
                    "choose another path; the existing one is left as it is",
                )
            }
        }
        // ERROR_PRIVILEGE_NOT_HELD: a symbolic link without the privilege or
        // Developer Mode. std does not count it as PermissionDenied, but it is
        // the operating system refusing all the same.
        _ if cfg!(windows) && e.raw_os_error() == Some(1314) => os_denied(
            builtin,
            format!("{builtin}: the operating system denied `{path}`: a required privilege is not held ({e})"),
            "enable Developer Mode, or run with the symbolic-link privilege; the shell did not refuse this",
        ),
        _ => anyhow::Error::new(SafetyError {
            code: ErrorCode::Io,
            message: format!("{builtin}: cannot {verb} `{path}`: {e}"),
            builtin: builtin.to_string(),
            // Windows refuses a control character in a name with an invalid-name
            // error, not "not found"; the escape is the likely cause, so say so.
            hint: control_char_path_hint(path)
                .map(str::to_string)
                .unwrap_or_else(|| {
                    "a filesystem failure that is neither absence nor a \
                     permission refusal; the message names the condition"
                        .to_string()
                }),
            approval: None,
            did_you_mean: Vec::new(),
            expected: format!("`{path}` to be {expected_access}"),
            got: e.kind().to_string(),
            extra: serde_json::Map::new(),
        }),
    }
}

pub fn bad_arg(builtin: &str, expected: &str, got: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadArg,
        message: format!("{}: expected {}, got {}", builtin, expected, got),
        builtin: builtin.to_string(),
        hint: format!("pass an argument matching: {}", expected),
        approval: None,
        did_you_mean: Vec::new(),
        expected: expected.to_string(),
        got: got.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// [`bad_arg`] with a hint that says what the caller should do instead, in
/// place of the generic "pass an argument matching: ...". For the cases where
/// the generic hint is correct but leaves the actual fix unsaid.
pub fn bad_arg_with_hint(builtin: &str, expected: &str, got: &str, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadArg,
        message: format!("{}: expected {}, got {}", builtin, expected, got),
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: expected.to_string(),
        got: got.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured policy refusal (`E_POLICY_DENY`) for a gate that is not
/// the central effect governor.
///
/// A handful of refusals are decided before `guard` ever sees the call — the
/// `sh()` gate is the important one. They used to return a bare `anyhow!`, so
/// `ensure_structured` filed them under `E_UNKNOWN` with the hint "failed
/// without a specific error code; inspect the message rather than retrying the
/// same call". That is exactly backwards for the most security-relevant
/// refusal the shell makes: the cause is known precisely, and `E_UNKNOWN` is
/// the one code an agent is told *not* to reason about.
pub fn policy_deny(
    builtin: &str,
    message: impl Into<String>,
    hint: impl Into<String>,
) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::PolicyDeny,
        message: message.into(),
        builtin: builtin.to_string(),
        hint: hint.into(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured operating-system refusal (`E_OS_DENIED`): permissions,
/// ownership, or a protected process. The shell's own refusals are
/// [`policy_deny`].
pub fn os_denied(
    builtin: &str,
    message: impl Into<String>,
    hint: impl Into<String>,
) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::OsDenied,
        message: message.into(),
        builtin: builtin.to_string(),
        hint: hint.into(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: "permission denied".to_string(),
        extra: serde_json::Map::new(),
    })
}

/// The keys of the standard error record. A script's `error(message, extra)`
/// field with one of these names would never reach the caller, so `error`
/// refuses it. `hint`, `expected` and `got` are not here: a script may set them,
/// and they reach the caller (`hint` replaces the default hint). Keep in step
/// with the keys [`SafetyError::to_json`] emits.
pub const ERROR_RESERVED_KEYS: &[&str] = &[
    "code",
    "message",
    "retryable",
    "builtin",
    "error",
    "did_you_mean",
    "approval",
];

/// The error a script raises with `error(message[, extra])` (`E_USER`). `extra`
/// is merged into the caught record by [`SafetyError::to_json`]. A `hint` the
/// script gives replaces the default one.
pub fn user_error(
    message: String,
    extra: serde_json::Map<String, serde_json::Value>,
    hint: Option<String>,
) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::User,
        message,
        builtin: "error".to_string(),
        hint: hint.unwrap_or_else(|| {
            "raised by error() in the script; catch it with try { } catch e { ... }, \
             or fix the step that raised it"
                .to_string()
        }),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra,
    })
}

/// The error a failed `assert(condition[, message])` raises (`E_ASSERT`). It is
/// raised like `error()`, so `try { } catch e { e.code }` and `e.message` work.
pub fn assertion_failed(message: String) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::Assert,
        message,
        builtin: "assert".to_string(),
        hint: "raised by assert() in the script; catch it with try { } catch e { ... }, \
             or fix the condition that failed"
            .to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// The refusal for an Int result that does not fit in 64 bits (`E_BAD_VALUE`).
/// `operator` names the operation, such as `Add` or `Pow`.
pub fn integer_overflow(operator: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::Overflow,
        message: format!("integer overflow in operator {operator}"),
        builtin: format!("operator {operator}"),
        hint: "the result does not fit in a 64-bit Int; write one operand as a Float (2.0, \
               not 2) to get a Float result, or split the computation"
            .to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// A missing folder or other thing that needs its own message and hint, as
/// `E_NOT_FOUND`. For a case where [`not_found`]'s "no file named" would name
/// the wrong thing, such as a destination folder that is the one missing.
pub fn not_found_with(builtin: &str, message: String, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::NotFound,
        message,
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "the destination folder to exist".to_string(),
        got: "no such folder".to_string(),
        extra: serde_json::Map::new(),
    })
}

/// An edit whose pattern or anchor is not in the file (`E_NOT_FOUND`). Nothing
/// was written, so the caller can fix the pattern and run the edit again. An
/// edit that finds nothing is a failure, not a success with a flag in it.
pub fn edit_not_found(builtin: &str, message: String, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::NotFound,
        message,
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "the pattern to occur in the file".to_string(),
        got: "not in the file".to_string(),
        extra: serde_json::Map::new(),
    })
}

/// A conversion's operand that has no value of the target type, such as
/// `int("1.5")` or `int(NaN)`. The operand has the right type; its value cannot
/// be represented. It is `E_BAD_VALUE`, which is the wire name `ErrorCode::Overflow`
/// carries (`BadValue` writes `E_BAD_ARG`), and it is not retryable.
pub fn value_not_representable(builtin: &str, message: String, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::Overflow,
        message,
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// [`bad_arg`] with a free-form message and a hint, for an operation whose
/// operands have the wrong types together: `operator Add: cannot combine String
/// and Int`. `builtin` names the operation, so the error says where it came from.
pub fn bad_arg_in(builtin: &str, message: impl Into<String>, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadArg,
        message: message.into(),
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// [`bad_value`] that names the operation it refused in `builtin`, such as
/// `operator Div`, so the error's `builtin` field says where it came from.
pub fn bad_value_in(builtin: &str, message: impl Into<String>, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadValue,
        message: message.into(),
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured value error (`E_BAD_ARG`, not retryable): the argument is
/// well-formed but its value makes the operation undefined. The hint says what
/// to change, which for these is the caller's data.
pub fn bad_value(message: impl Into<String>, hint: &str) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadValue,
        message: message.into(),
        builtin: String::new(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// The `E_BAD_ARG` (not retryable) for an index past either end of an Array or
/// String. The hint names the length, so the caller can pick a valid index
/// without a second call. `from_args` says the Array is the script's `args()`,
/// which is empty when the script was run with no arguments.
pub fn index_out_of_range(kind: &str, index: i64, len: usize, from_args: bool) -> anyhow::Error {
    let hint = if len == 0 && from_args && crate::builtins::run_under_c() {
        "-c takes no script arguments; put the code in a .ish file and run ish file.ish <arg>"
            .to_string()
    } else if len == 0 && from_args {
        "the script was run with no arguments: ish script.ish <arg>".to_string()
    } else if len == 0 {
        format!("the {kind} is empty; check len(x) > 0 first")
    } else {
        format!(
            "the {kind} has length {len}: valid indices are 0 to {} (or -1 to -{len} from the end)",
            len - 1
        )
    };
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadValue,
        message: format!("index {index} is out of range: the {kind} has length {len}"),
        builtin: String::new(),
        hint,
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("an index from -{len} to {}", len.saturating_sub(1)),
        got: index.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured unknown-builtin error (`E_UNKNOWN_BUILTIN`) carrying the
/// nearest real names. `candidates` must already have been filtered against the
/// live builtin table — this constructor does not invent names.
pub fn unknown_builtin(name: &str, candidates: Vec<String>) -> anyhow::Error {
    unknown_builtin_hinted(name, candidates, None)
}

/// [`unknown_builtin`] whose hint is `specific` when given, in place of the
/// candidate list: for a name a loaded module defines without `pub`.
pub fn unknown_builtin_hinted(
    name: &str,
    candidates: Vec<String>,
    specific: Option<String>,
) -> anyhow::Error {
    let hint = if let Some(specific) = specific {
        specific
    } else if candidates.is_empty() {
        "no builtin has a similar name; call ontology_manifest() to list the \
         available categories"
            .to_string()
    } else {
        format!("did you mean: {}", candidates.join(", "))
    };
    anyhow::Error::new(SafetyError {
        code: ErrorCode::UnknownBuiltin,
        message: format!("unknown builtin: {}", name),
        builtin: name.to_string(),
        hint,
        approval: None,
        did_you_mean: candidates,
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// Build the unknown-name error for `name.member` where `name` is neither a
/// bound value nor a module. It carries the same code `nope()` gets
/// (`E_UNKNOWN_BUILTIN`), and names the module, not a field: the reader wrote a
/// module that does not exist, and "expected a Record" sent them looking at a
/// value they never had.
pub fn unknown_module(name: &str, candidates: Vec<String>) -> anyhow::Error {
    let hint = if candidates.is_empty() {
        "no module has a similar name; call ontology_manifest() to list the available categories"
            .to_string()
    } else {
        format!("did you mean: {}", candidates.join(", "))
    };
    anyhow::Error::new(SafetyError {
        code: ErrorCode::UnknownBuiltin,
        message: format!("unknown module: {}", name),
        builtin: name.to_string(),
        hint,
        approval: None,
        did_you_mean: candidates,
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// Build the error for `module.member` where `module` is a known module that has
/// no such member (`E_UNKNOWN_BUILTIN`). The member is a builtin that does not
/// exist, so it is named as one; `candidates` are the nearest real names.
pub fn unknown_module_member(module: &str, member: &str, candidates: Vec<String>) -> anyhow::Error {
    unknown_module_member_hinted(module, member, candidates, None)
}

/// [`unknown_module_member`] whose hint is `specific` when given, in place of
/// the candidate list.
pub fn unknown_module_member_hinted(
    module: &str,
    member: &str,
    candidates: Vec<String>,
    specific: Option<String>,
) -> anyhow::Error {
    let hint = if let Some(specific) = specific {
        specific
    } else if candidates.is_empty() {
        "no member of this module has a similar name; call ontology_manifest() to list the available builtins"
            .to_string()
    } else {
        format!("did you mean: {}", candidates.join(", "))
    };
    anyhow::Error::new(SafetyError {
        code: ErrorCode::UnknownBuiltin,
        message: format!("module `{module}` has no member `{member}`"),
        builtin: format!("{module}.{member}"),
        hint,
        approval: None,
        did_you_mean: candidates,
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// Build the error for a bare name that nothing binds (`E_UNKNOWN_NAME`). The
/// candidates are the nearest bound variables and builtins; `candidates` must
/// come from those tables, as with the other `unknown_*` constructors.
pub fn unknown_name(name: &str, candidates: Vec<String>) -> anyhow::Error {
    let hint = if candidates.is_empty() {
        format!(
            "`{name}` is not a variable, builtin or module; bind it with `{name} = ...`, \
             or call a builtin as `{name}(...)`"
        )
    } else {
        format!("did you mean: {}", candidates.join(", "))
    };
    anyhow::Error::new(SafetyError {
        code: ErrorCode::UnknownName,
        message: format!("unknown name `{name}`"),
        builtin: String::new(),
        hint,
        approval: None,
        did_you_mean: candidates,
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// Build a structured unknown-field error (`E_UNKNOWN_FIELD`) carrying the
/// nearest real field names.
///
/// Module functions are record fields, so this is the code an agent sees for
/// `file.raed(…)` — the shape most agent typos actually take, since a model
/// writes dotted module paths far more often than bare builtin names.
/// `candidates` must come from the record's own keys.
pub fn unknown_field(field: &str, candidates: Vec<String>) -> anyhow::Error {
    unknown_field_hinted(field, candidates, None)
}

/// [`unknown_field`] whose hint is `specific` when given, in place of the
/// candidate list.
pub fn unknown_field_hinted(
    field: &str,
    candidates: Vec<String>,
    specific: Option<String>,
) -> anyhow::Error {
    let hint = if let Some(specific) = specific {
        specific
    } else if candidates.is_empty() {
        format!("no field named '{}' in this record", field)
    } else {
        format!("did you mean: {}", candidates.join(", "))
    };
    anyhow::Error::new(SafetyError {
        code: ErrorCode::UnknownField,
        message: format!("field '{}' not found in record", field),
        builtin: String::new(),
        hint,
        approval: None,
        did_you_mean: candidates,
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// The hint for a missing record field when no key is close enough to suggest:
/// the record's actual keys, sorted, at most twelve of them, then "…". An agent
/// that misspelt or guessed a key gets the real ones back in one reply.
pub fn record_keys_hint<'a>(keys: impl Iterator<Item = &'a str>) -> String {
    let mut keys: Vec<&str> = keys.collect();
    if keys.is_empty() {
        return "the record has no fields".to_string();
    }
    keys.sort_unstable();
    let mut listed = keys.iter().take(12).copied().collect::<Vec<_>>().join(", ");
    if keys.len() > 12 {
        listed.push_str(", …");
    }
    format!("the record has: {listed}")
}

/// The hint for a record that lacks `field` when no key is close enough to
/// suggest: it says the field is absent and names `get` for an optional one,
/// then lists the record's keys ([`record_keys_hint`]).
pub fn missing_field_hint<'a>(field: &str, keys: impl Iterator<Item = &'a str>) -> String {
    format!(
        "this record has no field `{field}`; use get(r, \"{field}\") for an optional field (Null when missing). {}",
        record_keys_hint(keys)
    )
}

/// A code for an uncoded error whose cause is an I/O or HTTP error: one passed
/// up with a bare `?` or `.context()`, which no call site coded. The cause
/// says whose fault it is as well as a call site would: a missing file is
/// `E_NOT_FOUND`, the operating system refusing is `E_OS_DENIED`, any other
/// I/O or HTTP failure is `E_IO`. `None` leaves the error `E_UNKNOWN`.
fn classify_uncoded(e: &anyhow::Error) -> Option<(ErrorCode, &'static str)> {
    for cause in e.chain() {
        if let Some(io) = cause.downcast_ref::<std::io::Error>() {
            return Some(match io.kind() {
                std::io::ErrorKind::NotFound => (
                    ErrorCode::NotFound,
                    "a file or directory the call needs does not exist; the message names it",
                ),
                std::io::ErrorKind::PermissionDenied => (
                    ErrorCode::OsDenied,
                    "the operating system denied access; the shell did not refuse this",
                ),
                _ => (
                    ErrorCode::Io,
                    "an I/O failure that is neither absence nor a permission refusal; the message names the condition",
                ),
            });
        }
        #[cfg(not(target_arch = "wasm32"))]
        if cause.downcast_ref::<reqwest::Error>().is_some() {
            return Some((
                ErrorCode::Io,
                "an HTTP request failed; check the address and the network, then retry",
            ));
        }
    }
    None
}

/// The code an error that reached a boundary carries, without consuming it.
///
/// A [`SafetyError`] answers with its own code. Anything else gets the same
/// classification [`ensure_structured`] applies (absence, permission, I/O), and
/// `E_UNKNOWN` when that finds nothing. Used by [`crate::record`], which must
/// read the code of an error it is about to pass on unchanged.
/// Add `note` to an error where its reader will see it. Agents get a coded error
/// as its JSON, which `.context()` never reaches, so the note goes in the message.
pub fn with_note(e: anyhow::Error, note: &str) -> anyhow::Error {
    if let Some(se) = e.downcast_ref::<SafetyError>() {
        let mut noted = se.clone();
        noted.message = format!("{}; {note}", noted.message);
        return anyhow::Error::new(noted);
    }
    let message = format!("{e:#}; {note}");
    e.context(message)
}

pub fn code_of(e: &anyhow::Error) -> ErrorCode {
    if let Some(se) = e.downcast_ref::<SafetyError>() {
        return se.code;
    }
    classify_uncoded(e).map_or(ErrorCode::Unknown, |(code, _)| code)
}

/// Name an error's builtin as the caller wrote it. A module member such as
/// `file.read` runs the builtin `cat`, and its errors named `cat`. The error's
/// `builtin` field and the leading `from:` of its message become `to`; the code
/// and everything else are unchanged. An error of another builtin, or one that
/// is not structured, is returned as it is.
pub fn rename_builtin(e: anyhow::Error, from: &str, to: &str) -> anyhow::Error {
    match e.downcast_ref::<SafetyError>() {
        Some(se) if se.builtin == from => {
            let mut renamed = se.clone();
            renamed.builtin = to.to_string();
            if let Some(rest) = renamed.message.strip_prefix(&format!("{from}:")) {
                renamed.message = format!("{to}:{rest}");
            }
            anyhow::Error::new(renamed)
        }
        _ => e,
    }
}

/// Give an otherwise-uncoded failure a stable code (`E_UNKNOWN`).
///
/// This is the boundary net that makes "every failure is branchable" true
/// rather than aspirational: an error that is *already* a [`SafetyError`] is
/// returned untouched (its specific code is strictly better information), and
/// anything else is wrapped with its original message preserved verbatim.
pub fn ensure_structured(builtin: &str, e: anyhow::Error) -> anyhow::Error {
    if let Some(se) = e.downcast_ref::<SafetyError>() {
        // `arg_err` — by far the most-used structured helper — takes only a
        // message, so its `builtin` field is empty. The boundary is the one
        // place that knows the name being called, so fill it in here rather
        // than editing hundreds of call sites. Without this, `diagnose` cannot
        // look up the signature for the majority of E_BAD_ARG failures.
        // The same boundary replaces the generic `arg_err` hint with what the
        // builtin's declaration says it takes.
        let generic = matches!(se.code, ErrorCode::BadArg) && se.hint == ARG_ERR_HINT;
        if !builtin.is_empty() && (se.builtin.is_empty() || generic) {
            let mut filled = se.clone();
            if filled.builtin.is_empty() {
                filled.builtin = builtin.to_string();
                // A refusal built with no name leads with the empty name:
                // ": `x` is outside the workspace". Name it here, where the
                // name becomes known.
                if let Some(rest) = filled.message.strip_prefix(": ") {
                    filled.message = format!("{builtin}: {rest}");
                }
            }
            if generic {
                if let Some(sig) = crate::signature::signature_of(builtin) {
                    filled.hint = signature_arg_hint(builtin, sig);
                }
            }
            return anyhow::Error::new(filled);
        }
        return e;
    }
    let message = e.to_string();
    if let Some((code, hint)) = classify_uncoded(&e) {
        return anyhow::Error::new(SafetyError {
            code,
            message: format!("{e:#}"),
            builtin: builtin.to_string(),
            hint: hint.to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: String::new(),
            got: String::new(),
            extra: serde_json::Map::new(),
        });
    }
    anyhow::Error::new(SafetyError {
        code: ErrorCode::Unknown,
        message,
        builtin: builtin.to_string(),
        hint: format!(
            "{} failed without a specific error code; inspect the message rather \
             than retrying the same call",
            builtin
        ),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// The hint [`arg_err`] carries when the caller has nothing more specific. At the
/// dispatch boundary ([`ensure_structured`]) it is replaced by the parameter
/// types from the builtin's declared signature, when it has one.
pub const ARG_ERR_HINT: &str = "check this builtin's required argument count and types";

/// The hint for a bad argument to `name`, from its declared signature: the
/// types its subject and parameters take. A builtin whose declaration gives no
/// type (every one is `Any`) is described by its own doc line instead.
fn signature_arg_hint(name: &str, sig: &crate::signature::Signature) -> String {
    use crate::signature::Ty;
    // Each type once, in declaration order: `slice(start, end)` takes Int, not
    // "Int or Int".
    let mut types: Vec<&str> = Vec::new();
    let subject = sig.subject.filter(|t| *t != Ty::Any);
    let parameters = sig
        .params
        .iter()
        .filter(|p| p.ty != Ty::Any)
        .map(|p| p.ty.as_str());
    for t in subject.into_iter().map(Ty::as_str).chain(parameters) {
        if !types.contains(&t) {
            types.push(t);
        }
    }
    match types.split_last() {
        None => format!("{name}: {}", sig.doc),
        Some((last, [])) => format!("{name} takes {last}"),
        Some((last, init)) => format!("{name} takes {} or {last}", init.join(", ")),
    }
}

/// Build a structured argument error (`E_BAD_ARG`) from a free-form arity/usage
/// message that already names the builtin and what it needs (e.g.
/// `"map requires a lambda"`). The missing/extra-argument counterpart to
/// [`bad_arg`] for the many call sites whose message doesn't split cleanly into
/// `expected`/`got`. Like [`bad_arg`] it is a [`SafetyError`], so try/catch binds
/// it as a structured `{error:{code:"E_BAD_ARG", message, hint, retryable}}`
/// record and the human REPL renders it as legible prose.
pub fn arg_err(message: impl Into<String>) -> anyhow::Error {
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadArg,
        message: message.into(),
        builtin: String::new(),
        hint: ARG_ERR_HINT.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// The arity error for calling a lambda with the wrong number of arguments. It
/// names the callee (`f`, or `lambda` when the value has no variable name), lists
/// the parameters, and says what a lambda does about a missing argument: nothing,
/// since its parameters take no defaults.
pub fn lambda_arity(name: Option<&str>, params: &[String], got: usize) -> anyhow::Error {
    let label = name.unwrap_or("lambda");
    let plural = |k: usize| if k == 1 { "argument" } else { "arguments" };
    let want = format!("{} {}", params.len(), plural(params.len()));
    let received = format!("{got} {}", plural(got));
    anyhow::Error::new(SafetyError {
        code: ErrorCode::BadArg,
        message: format!("{label} takes {want} ({}), got {got}", params.join(", ")),
        builtin: String::new(),
        hint: format!(
            "a lambda takes exactly the parameters it was written with and has no \
             defaults: call it with {want}, or pass null for a value you do not have \
             and check for null in the body"
        ),
        approval: None,
        did_you_mean: Vec::new(),
        expected: want,
        got: received,
        extra: serde_json::Map::new(),
    })
}

/// A describable action an agent may be asked to approve (§7.2). The `token`
/// is cryptographically bound to the action's content, so it cannot be replayed
/// to approve a different action.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ApprovalDescriptor {
    pub what: String,
    pub builtin: String,
    pub targets: Vec<String>,
    pub blast_radius: Json,
    pub reversible: bool,
    pub token: String,
}

impl ApprovalDescriptor {
    fn new(
        what: &str,
        builtin: &str,
        targets: Vec<String>,
        blast_radius: Json,
        reversible: bool,
    ) -> Result<Self, ironcrypto::core_types::Error> {
        // token = apv_<first 16 hex of sha256 over the action content>
        let content = json!({
            "what": what,
            "builtin": builtin,
            "targets": targets,
            "blast_radius": blast_radius,
            "reversible": reversible,
        });
        let mut hasher = Sha256::new();
        hasher.update(content.to_string().as_bytes());
        let digest = hasher.finalize()?;
        let token = format!("apv_{}", &hex(&digest)[..16]);
        Ok(Self {
            what: what.to_string(),
            builtin: builtin.to_string(),
            targets,
            blast_radius,
            reversible,
            token,
        })
    }
}

/// A safety refusal/failure carrying a stable code and an actionable hint.
/// Implements [`std::error::Error`] so it threads through `anyhow`/`?`.
#[derive(Debug, Clone)]
pub struct SafetyError {
    pub code: ErrorCode,
    pub message: String,
    pub builtin: String,
    pub hint: String,
    pub approval: Option<ApprovalDescriptor>,
    /// Nearest existing builtin names for a misspelled call. Emitted **only**
    /// when non-empty, and only ever containing names that really exist — an
    /// empty list is the honest answer when nothing is close, which costs an
    /// agent fewer tokens than a confident wrong guess costs it retries.
    pub did_you_mean: Vec<String>,
    /// What the call wanted, as a bare type/shape name, and what it received.
    /// The same facts `message` states in prose, but machine-readable: an agent
    /// repairing a `E_BAD_ARG` should not have to parse English to learn that an
    /// `Int` was wanted where a `Str` arrived. Both empty when not applicable.
    pub expected: String,
    pub got: String,
    /// Fields a script added to its own error (`error(message, {field: ...})`),
    /// merged into the structured record after the standard ones, which they
    /// cannot replace. Empty for every error the shell raises itself.
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl SafetyError {
    /// Whether `try` must let this refusal through. In agent mode the policy
    /// refusals (`E_NEEDS_APPROVAL`, `E_OUTSIDE_WORKSPACE`, `E_POLICY_DENY`) are
    /// not catchable: a script that swallowed one would report success for work
    /// the policy stopped. Human mode keeps them catchable.
    pub fn is_uncatchable_in_agent_mode(&self) -> bool {
        current_mode() == Mode::Agent
            && matches!(
                self.code,
                ErrorCode::NeedsApproval | ErrorCode::OutsideWorkspace | ErrorCode::PolicyDeny
            )
    }

    /// Whether this failure, as reported, is worth re-running with a correction.
    ///
    /// The class answers for most codes. An unknown builtin is the exception
    /// that depends on the call: a misspelling with a real candidate is retried
    /// under that candidate, but a name with nothing close fails the same way
    /// every time.
    pub fn is_retryable(&self) -> bool {
        match self.code {
            ErrorCode::UnknownBuiltin => !self.did_you_mean.is_empty(),
            code => code.retryable(),
        }
    }

    /// The structured JSON form an agent reads programmatically.
    ///
    /// The prose fields name paths and echo the arguments of the failed call, so
    /// a secret-shaped name (`AWS_SECRET_ACCESS_KEY=AKIA….txt`) reaches them
    /// verbatim. They get the same redaction as the output of a successful call,
    /// when redaction is on.
    pub fn to_json(&self) -> Json {
        let scrub = |s: &str| {
            if redaction_enabled() {
                redact_str(s).0
            } else {
                s.to_string()
            }
        };
        let mut err = json!({
            "code": self.code.as_str(),
            "message": scrub(&self.message),
            "builtin": self.builtin,
            "hint": scrub(&self.hint),
            "retryable": self.is_retryable(),
        });
        if let Some(a) = &self.approval {
            err["approval"] = serde_json::to_value(a).unwrap_or(Json::Null);
        }
        if !self.did_you_mean.is_empty() {
            err["did_you_mean"] = serde_json::to_value(&self.did_you_mean).unwrap_or(Json::Null);
        }
        // Emitted only as a pair, and only when populated — a lone `expected` tells
        // an agent nothing it cannot already read in `hint`, and costs tokens.
        if !self.expected.is_empty() && !self.got.is_empty() {
            err["expected"] = Json::String(scrub(&self.expected));
            err["got"] = Json::String(scrub(&self.got));
        }
        // A script's own fields go in after the standard ones and never replace
        // them. `error` refuses such a field before it gets here (E_BAD_ARG), so
        // this guard only holds for an extra built some other way.
        if let Some(object) = err.as_object_mut() {
            for (key, value) in &self.extra {
                if object.contains_key(key) {
                    continue;
                }
                let value = match value {
                    Json::String(s) => Json::String(scrub(s)),
                    other => other.clone(),
                };
                object.insert(key.clone(), value);
            }
        }
        json!({ "error": err })
    }
}

impl std::fmt::Display for SafetyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Deterministic single-line rendering; the JSON form is authoritative.
        write!(f, "{}", self.to_json())
    }
}

impl std::error::Error for SafetyError {}

// ════════════════════════════════════════════════════════════════════════
// Workspace jail (§7.4)
// ════════════════════════════════════════════════════════════════════════

/// The workspace root. `IRONSHELL_WORKSPACE` if set, else the current directory.
///
/// The fallback is the *live* working directory, so in an unpinned process a
/// `cd` moves the jail and the audit log with it. [`pin_workspace_root`] stops
/// that by setting the variable once, at startup, in agent mode.
pub fn workspace_root() -> PathBuf {
    if let Ok(w) = std::env::var("IRONSHELL_WORKSPACE") {
        // Always absolute. A relative root (`--workspace proj`) made
        // `resolve_path_str` return a relative path that the jail then joined to
        // the root a second time: `../x` was judged as `proj/x` and written as
        // `x`, outside the workspace.
        let w = PathBuf::from(w);
        if w.is_absolute() {
            w
        } else {
            std::path::absolute(&w).unwrap_or(w)
        }
    } else if let Ok(pinned) = std::env::var(PINNED_ROOT_ENV) {
        PathBuf::from(pinned)
    } else {
        std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
    }
}

/// Where [`pin_workspace_root`] records the root. It is separate from
/// `IRONSHELL_WORKSPACE` because that variable also makes a relative path resolve
/// against the workspace, and a pin must not: after `cd sub`, `echo x > f` still
/// means `sub/f`.
const PINNED_ROOT_ENV: &str = "IRONSHELL_PINNED_ROOT";

/// Fix the workspace root for this process: in agent mode, with
/// `IRONSHELL_WORKSPACE` unset, record the canonical current directory.
///
/// Called once by the binary after the mode is decided and before any work
/// starts. After it, a `cd` moves the working directory but not the jail or
/// the audit log, and a relative path still follows the working directory. A
/// child `ish` inherits the variable (it is in `CONFINING_ENV`), so it shares
/// the same root. A variable the operator set, including `--workspace`, is
/// left as it is. Human mode is unchanged. Library callers that never call
/// this are covered by the audit log's path-change marker instead.
pub fn pin_workspace_root() {
    if current_mode() != Mode::Agent
        || std::env::var_os("IRONSHELL_WORKSPACE").is_some()
        || std::env::var_os(PINNED_ROOT_ENV).is_some()
    {
        return;
    }
    let Ok(cwd) = std::env::current_dir() else {
        return;
    };
    let canon = cwd.canonicalize().unwrap_or(cwd);
    std::env::set_var(PINNED_ROOT_ENV, strip_verbatim_prefix(&canon));
}

/// `canonicalize` on Windows returns the `\\?\C:\...` form. Strip it for the
/// variable, so the root reads and passes to children as an ordinary path.
/// Verbatim UNC (`\\?\UNC\...`) keeps its prefix, since there is no plain form.
pub(crate) fn strip_verbatim_prefix(p: &Path) -> PathBuf {
    let s = p.to_string_lossy();
    match s.strip_prefix(r"\\?\") {
        Some(rest) if !rest.starts_with("UNC\\") && rest.as_bytes().get(1) == Some(&b':') => {
            PathBuf::from(rest)
        }
        _ => p.to_path_buf(),
    }
}

/// Whether `path` names the active audit log or the directory holding it.
///
/// Compared lexically after normalising separators, because the target may not
/// exist yet — a truncating write to a path that is about to *become* the log is
/// the same attack as editing the one that is there.
///
/// Compared again after resolving symlinks, and by file identity too.
/// The lexical test alone let an alias through: a symlink in the workspace
/// whose target is the log passed the jail (the link is inside it) and passed
/// this test (the link's name is not the log's), and `file.write`,
/// `file.append`, `fs.chmod` and others then followed the link and changed the
/// log. A hard link is the same alias with no link to resolve, so it is
/// matched by file identity: device and inode on Unix, volume serial and file
/// index on Windows (see [`same_existing_file`]).
pub fn is_audit_artifact(path: &str) -> bool {
    let p = path.replace('\\', "/");
    if p.trim_end_matches('/').is_empty() {
        return false;
    }
    // The append-only sink is evidence too. It is normally outside the
    // workspace — that is the point of it — but nothing forces that, and a
    // sink placed inside the jail would otherwise be an ordinary writable
    // file that any `file.write` could clobber.
    let sink = std::env::var_os("IRONSHELL_AUDIT_SINK")
        .map(PathBuf::from)
        .filter(|s| !s.as_os_str().is_empty());
    let log = audit_path();
    if sink.is_none() && log.is_none() {
        return false;
    }
    // Judged where the path resolves, not as it is spelled: `.ironshell/../x`
    // is the workspace, and matching its prefix refused it (a false refusal
    // that failed closed). A path that will not resolve is refused, because
    // nothing can then say where it lands.
    let Some(candidates) = judged_forms(path) else {
        return true;
    };
    let hit = |target: &Path| {
        let forms = audit_forms(target);
        candidates.iter().any(|c| forms.contains(c)) || same_existing_file(Path::new(path), target)
    };
    if let Some(sink) = &sink {
        if hit(sink) {
            return true;
        }
    }

    match log {
        Some(log) => {
            if hit(&log) {
                return true;
            }
            // The containing directory too, so `rm -r .ironshell` is caught — but
            // **only when that directory is ours**. The first version
            // protected the parent unconditionally, which meant an
            // `IRONSHELL_AUDIT_LOG` pointing at `/tmp/x.log` made the whole of
            // `/tmp` unwritable. A guard that swallows a shared directory
            // because a file was placed in it is a denial of service, not a
            // control.
            match log.parent() {
                Some(dir) if dir.file_name().is_some_and(|n| n == ".ironshell") => {
                    let dirs = audit_forms(dir);
                    candidates.iter().any(|c| {
                        dirs.iter()
                            .any(|d| !d.is_empty() && (c == d || c.starts_with(&format!("{d}/"))))
                    })
                }
                _ => false,
            }
        }
        None => false,
    }
}

/// Where `path` lands, as strings comparable with [`audit_forms`]: lowercased,
/// `/` separators, symlinks and `..` resolved. That is the reading the jail
/// judges ([`resolve_for_jail`]). On Windows the Win32 reading is judged too,
/// since it removes `..` as text before the file system sees the path, so a
/// path must stay clear of the audit directory under both. `None` when either
/// reading cannot be resolved; the callers then refuse.
fn judged_forms(path: &str) -> Option<Vec<String>> {
    let norm = |p: PathBuf| {
        p.to_string_lossy()
            .replace('\\', "/")
            .trim_end_matches('/')
            .to_ascii_lowercase()
    };
    let jail = norm(resolve_for_jail(path)?);
    #[cfg(windows)]
    let forms = vec![jail, norm(resolve_walked(win32_path(path))?)];
    #[cfg(not(windows))]
    let forms = vec![jail];
    Some(forms)
}

/// The spellings of `path` that [`is_audit_artifact`] compares: the lexical
/// form, and the form with symlinks resolved (through the nearest existing
/// ancestor, so a path that does not exist yet still resolves its directory).
/// Lowercased with `/` separators, since Windows paths compare that way.
fn audit_forms(path: &Path) -> Vec<String> {
    let norm = |s: &str| {
        s.replace('\\', "/")
            .trim_end_matches('/')
            .to_ascii_lowercase()
    };
    let mut forms = vec![norm(&path.to_string_lossy())];
    if let Some(real) = resolve_existing_prefix(path) {
        let real = norm(&real.to_string_lossy());
        if !forms.contains(&real) {
            forms.push(real);
        }
    }
    forms
}

/// `path` with symlinks resolved: canonicalised outright when it exists, else
/// its nearest existing ancestor canonicalised and the missing tail re-joined.
fn resolve_existing_prefix(path: &Path) -> Option<PathBuf> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir().ok()?.join(path)
    };
    let mut tail = Vec::new();
    let mut cursor = absolute.as_path();
    loop {
        if let Ok(real) = std::fs::canonicalize(cursor) {
            let mut out = real;
            for part in tail.iter().rev() {
                out.push(part);
            }
            return Some(out);
        }
        tail.push(cursor.file_name()?.to_os_string());
        cursor = cursor.parent()?;
    }
}

/// Whether `path` names a file that configures the gate itself: the RBAC
/// config (`IRONSHELL_RBAC_CONFIG`, else `<workspace>/.ironshell/rbac.toml` whether or
/// not it exists yet) or the audit chain key (`IRONSHELL_AUDIT_KEY_FILE`).
///
/// Both are read when a process starts, and the Python SDK starts one per
/// call, so a jailed write to either would govern the next call: an agent
/// could grant itself roles, or choose the key its log is chained with. The
/// default config's `.ironshell` directory is covered too, so it cannot be renamed
/// away or replaced by a link. Matched the way [`is_audit_artifact`] matches,
/// aliases included.
pub fn is_governance_file(path: &str) -> bool {
    if path.replace('\\', "/").trim_end_matches('/').is_empty() {
        return false;
    }
    // Judged where it resolves, and refused when it will not resolve (see
    // `is_audit_artifact`).
    let Some(candidates) = judged_forms(path) else {
        return true;
    };
    let names = |target: &Path| {
        let forms = audit_forms(target);
        candidates.iter().any(|c| forms.contains(c)) || same_existing_file(Path::new(path), target)
    };
    let mut files = Vec::new();
    match std::env::var_os("IRONSHELL_RBAC_CONFIG") {
        Some(config) if !config.is_empty() => files.push(PathBuf::from(config)),
        _ => {
            let dir = workspace_root().join(".ironshell");
            let dirs = audit_forms(&dir);
            if candidates.iter().any(|c| {
                dirs.iter()
                    .any(|d| !d.is_empty() && (c == d || c.starts_with(&format!("{d}/"))))
            }) {
                return true;
            }
            files.push(dir.join("rbac.toml"));
        }
    }
    if let Some(key) = std::env::var_os("IRONSHELL_AUDIT_KEY_FILE") {
        if !key.is_empty() {
            files.push(PathBuf::from(key));
        }
    }
    files.iter().any(|f| names(f))
}

/// Why a write to `path` is refused when it is one `guard` protects, for a
/// builtin whose writes `guard` never sees: `apply` writes the paths its plan
/// names, and an archive extraction writes paths only the archive names. None
/// outside the jail, as in `guard`.
pub fn protected_write_refusal(path: &str) -> Option<&'static str> {
    let mode = current_mode();
    if !jail_enforced(mode) {
        return None;
    }
    if is_audit_artifact(path) {
        Some("the audit log or its directory")
    } else if is_governance_file(path) {
        Some("a file that configures this shell's access control or audit key")
    } else if mode == Mode::Agent && is_git_control_path(path) {
        Some("inside a .git directory, whose config and hooks git runs")
    } else {
        None
    }
}

/// Whether `path` is a `.git` entry or lies under one, symlinks resolved.
///
/// Git runs commands named in a repository's own files: `core.fsmonitor` in
/// `.git/config` runs on `git status` and `git diff`, and `.git/hooks/*` run on
/// checkout, commit and merge. Those git builtins are ReadLocal or approved by
/// their git verb, so an agent that could write `.git/config` and then call
/// `git_status` would run a program nobody approved. A `.git` *file* is covered
/// too, since its `gitdir:` line chooses which config is read.
pub fn is_git_control_path(path: &str) -> bool {
    audit_forms(Path::new(path))
        .iter()
        .any(|form| form.split('/').any(|part| part == ".git"))
}

/// Whether two existing paths are the same file, hard links included.
///
/// On Unix this compares device and inode. On Windows it compares the volume
/// serial number and the 64-bit file index, which NTFS assigns per file however
/// many names link to it. A path that cannot be opened answers false.
#[cfg(unix)]
fn same_existing_file(a: &Path, b: &Path) -> bool {
    use std::os::unix::fs::MetadataExt;
    match (std::fs::metadata(a), std::fs::metadata(b)) {
        (Ok(x), Ok(y)) => x.dev() == y.dev() && x.ino() == y.ino(),
        _ => false,
    }
}

#[cfg(windows)]
fn same_existing_file(a: &Path, b: &Path) -> bool {
    match (windows_file_id(a), windows_file_id(b)) {
        (Some(x), Some(y)) => x == y,
        _ => false,
    }
}

#[cfg(not(any(unix, windows)))]
fn same_existing_file(_a: &Path, _b: &Path) -> bool {
    false
}

/// `(volume serial number, file index)` of `path`, from
/// `GetFileInformationByHandle`. Std does not expose these on stable Rust, so
/// the call is declared here rather than adding a crate for one function.
#[cfg(windows)]
fn windows_file_id(path: &Path) -> Option<(u32, u64)> {
    let info = by_handle_information(path)?;
    let index = (u64::from(info.file_index_high) << 32) | u64::from(info.file_index_low);
    Some((info.volume_serial_number, index))
}

/// `BY_HANDLE_FILE_INFORMATION` from the Windows SDK, laid out to match.
/// Every field is part of the layout; only some of them are read.
#[cfg(windows)]
#[repr(C)]
#[derive(Default)]
#[allow(dead_code)]
struct ByHandleFileInformation {
    file_attributes: u32,
    creation_time: [u32; 2],
    last_access_time: [u32; 2],
    last_write_time: [u32; 2],
    volume_serial_number: u32,
    file_size_high: u32,
    file_size_low: u32,
    number_of_links: u32,
    file_index_high: u32,
    file_index_low: u32,
}

#[cfg(windows)]
#[link(name = "kernel32")]
extern "system" {
    fn GetFileInformationByHandle(
        h: *mut std::ffi::c_void,
        info: *mut ByHandleFileInformation,
    ) -> i32;
}

/// The `BY_HANDLE_FILE_INFORMATION` of `path`, following links. Std does not
/// expose these on stable Rust, so the call is declared here rather than adding
/// a crate for one function. Shared by [`windows_file_id`] and
/// [`hard_link_count`].
#[cfg(windows)]
fn by_handle_information(path: &Path) -> Option<ByHandleFileInformation> {
    use std::os::windows::fs::OpenOptionsExt;

    // Access 0 asks for metadata only, so a locked or read-only file still
    // opens. Sharing read, write and delete does not block its owner. The
    // backup-semantics flag lets a directory open as well as a file.
    const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
    let file = std::fs::OpenOptions::new()
        .access_mode(0)
        .share_mode(0x7)
        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
        .open(path)
        .ok()?;
    handle_information(&file)
}

/// The `BY_HANDLE_FILE_INFORMATION` of an open handle, or `None` when the call
/// fails.
#[cfg(windows)]
fn handle_information(file: &std::fs::File) -> Option<ByHandleFileInformation> {
    use std::os::windows::io::AsRawHandle;

    let mut info = ByHandleFileInformation::default();
    // SAFETY: `file` holds a valid open handle for the whole call, and `info`
    // is a writable value whose layout matches BY_HANDLE_FILE_INFORMATION.
    let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) };
    if ok == 0 {
        return None;
    }
    Some(info)
}

/// The number of hard links to `path` when it is an existing regular file, else
/// `None`. Links are followed, so a symbolic link reports its target's count.
#[cfg(unix)]
pub(crate) fn hard_link_count(path: &Path) -> Option<u64> {
    use std::os::unix::fs::MetadataExt;
    let meta = std::fs::metadata(path).ok()?;
    meta.is_file().then(|| meta.nlink())
}

/// The number of hard links to `path` when it is an existing regular file, else
/// `None`, from the file's `GetFileInformationByHandle` record.
#[cfg(windows)]
pub(crate) fn hard_link_count(path: &Path) -> Option<u64> {
    if !std::fs::metadata(path).ok()?.is_file() {
        return None;
    }
    by_handle_information(path).map(|info| u64::from(info.number_of_links))
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn hard_link_count(_path: &Path) -> Option<u64> {
    None
}

/// The refusal for an in-place write to a file with `links` hard links.
/// The operator setting that refuses reads through a hard link under the jail.
pub(crate) const REFUSE_LINKED_READS_ENV: &str = "IRONSHELL_REFUSE_LINKED_READS";

/// Refuse a read of a file with more than one hard link, when the jail is
/// enforced and the operator set `IRONSHELL_REFUSE_LINKED_READS=1`.
///
/// Off by default. A hard link inside the workspace to a file outside it lets a
/// read see that file, and the jail cannot tell where a file's other names are
/// (Unix keeps no list of them). But package stores such as pnpm's hard-link
/// `node_modules` into a store outside the project, so refusing every linked
/// read would break ordinary installs. An operator whose workspace holds no
/// such store, or who must not let a planted link leak a file, turns it on.
pub(crate) fn refuse_hard_linked_read(builtin: &str, path: &str) -> anyhow::Result<()> {
    if std::env::var(REFUSE_LINKED_READS_ENV).as_deref() != Ok("1")
        || !jail_enforced(current_mode())
    {
        return Ok(());
    }
    let resolved = resolve_path_str(path);
    for candidate in [path.to_string(), resolved] {
        if let Some(links) = hard_link_count(Path::new(&candidate)).filter(|n| *n > 1) {
            return Err(policy_deny(
                builtin,
                format!(
                    "'{path}' has {links} hard links, and {REFUSE_LINKED_READS_ENV} refuses reads through a hard link"
                ),
                "read a copy that is not linked, or ask the operator to unset the setting",
            ));
        }
    }
    Ok(())
}

fn hard_link_refusal(builtin: &str, path: &str, links: u64) -> anyhow::Error {
    policy_deny(
        builtin,
        format!(
            "'{path}' has {links} hard links, so writing it in place could change a file outside the workspace"
        ),
        "remove the link or write a new file",
    )
}

/// The number of hard links of an open regular file, or `None` for anything else.
#[cfg(unix)]
fn handle_link_count(file: &std::fs::File) -> Option<u64> {
    use std::os::unix::fs::MetadataExt;
    let meta = file.metadata().ok()?;
    meta.is_file().then(|| meta.nlink())
}

/// The number of hard links of an open regular file, from its handle.
#[cfg(windows)]
fn handle_link_count(file: &std::fs::File) -> Option<u64> {
    if !file.metadata().ok()?.is_file() {
        return None;
    }
    handle_information(file).map(|info| u64::from(info.number_of_links))
}

#[cfg(not(any(unix, windows)))]
fn handle_link_count(_file: &std::fs::File) -> Option<u64> {
    None
}

/// Refuse an in-place write to a file with more than one hard link, when the
/// jail is enforced. The other names of such a file may lie outside the
/// workspace, and writing through one changes all of them. An atomic replace
/// (write a temporary file, rename it over the target) breaks the link instead,
/// so only in-place writers need this: a redirection, `tee`, `touch`, and the
/// builtins that open an existing file for append or truncate.
///
/// The path is judged as given and as the workspace resolves it, since a builtin
/// may open either form. Reads are not refused: a package store such as pnpm's
/// hard-links node_modules into its store, and reading through a link changes
/// nothing. This check is the fast early refusal by path. The in-place writers
/// also judge the handle they write through, in [`open_in_place`], which catches
/// a link planted after this check.
pub(crate) fn refuse_hard_linked_write(builtin: &str, path: &str) -> anyhow::Result<()> {
    if !jail_enforced(current_mode()) {
        return Ok(());
    }
    let resolved = resolve_path_str(path);
    let mut candidates = vec![path.to_string()];
    if resolved != path {
        candidates.push(resolved);
    }
    for candidate in &candidates {
        if let Some(links) = hard_link_count(Path::new(candidate)).filter(|n| *n > 1) {
            return Err(hard_link_refusal(builtin, path, links));
        }
    }
    Ok(())
}

/// Open `path` for an in-place write, judging the link count of the open handle.
///
/// The file is opened without truncation, and created when missing, so a refused
/// open leaves its contents alone. When the jail is enforced, a regular file with
/// more than one hard link is refused as [`refuse_hard_linked_write`] refuses it.
/// Only then is the file truncated (`append` false) or positioned at its end
/// (`append` true). The check and the truncation share one handle, so a link
/// planted after the path check cannot be missed. An I/O failure comes back as
/// an `io::Error` inside the `anyhow::Error`; [`in_place_error`] names it.
pub(crate) fn open_in_place(
    builtin: &str,
    path: &Path,
    append: bool,
) -> anyhow::Result<std::fs::File> {
    use std::io::{Seek, SeekFrom};
    let mut file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)?;
    if jail_enforced(current_mode()) {
        if let Some(links) = handle_link_count(&file).filter(|n| *n > 1) {
            return Err(hard_link_refusal(
                builtin,
                &path.display().to_string(),
                links,
            ));
        }
    }
    if append {
        file.seek(SeekFrom::End(0))?;
    } else if file.metadata()?.is_file() {
        // Only a regular file is truncated: a device such as /dev/null refuses it.
        file.set_len(0)?;
    }
    Ok(file)
}

/// Name the I/O failure inside an [`open_in_place`] error as a write error for
/// `path`. A refusal passes through unchanged.
pub(crate) fn in_place_error(builtin: &str, path: &str, e: anyhow::Error) -> anyhow::Error {
    match e.downcast::<std::io::Error>() {
        Ok(io) => fs_write_error(builtin, path, &io),
        Err(other) => other,
    }
}

/// Whether the jail is enforced. Enforced in agent mode, or whenever the
/// workspace root is set explicitly (humans opting into reproducible jails).
pub(crate) fn jail_enforced(mode: Mode) -> bool {
    mode == Mode::Agent || std::env::var("IRONSHELL_WORKSPACE").is_ok()
}

/// Why the workspace jail would refuse a guarded write to `path`, judged as
/// [`guard`] judges a filesystem target: the same checks, in the same order, but
/// nothing is audited and nothing is written. `None` when the jail lets it
/// through. `path` is the path the write would go to, as
/// [`resolve_path_str`] gives it.
pub fn write_jail_refusal(path: &str) -> Option<String> {
    let mode = current_mode();
    if !jail_enforced(mode) {
        return None;
    }
    if !within_workspace(path) {
        return Some(format!("'{path}' is outside the workspace root"));
    }
    if is_audit_artifact(path) {
        return Some(format!(
            "'{path}' is the audit log or its directory, which is protected and cannot be written by a guarded builtin"
        ));
    }
    if is_governance_file(path) {
        return Some(format!(
            "'{path}' configures this shell's access control or audit key and cannot be written by a guarded builtin"
        ));
    }
    if mode == Mode::Agent && is_git_control_path(path) {
        return Some(format!(
            "'{path}' is inside a .git directory and cannot be written by an agent"
        ));
    }
    None
}

/// Resolve a user-supplied path the way an effecting builtin should operate on it.
///
/// Absolute paths are returned unchanged. In a **jailed** context (agent mode, or
/// an explicit `IRONSHELL_WORKSPACE`) a relative path is resolved against the
/// workspace root, so writes/deletes land inside the jail and agree with both the
/// `within_workspace` check and the transaction journal — closing the gap where a
/// relative path was resolved against the process CWD (escaping the workspace when
/// CWD ≠ workspace). In plain human mode the path is left as-is, so the OS resolves
/// it against the current directory like any normal shell.
pub fn resolve_path_str(path: &str) -> String {
    let p = std::path::Path::new(path);
    if p.is_absolute() || !jail_enforced(current_mode()) {
        path.to_string()
    } else if std::env::var_os("IRONSHELL_WORKSPACE").is_some() {
        join_native(workspace_root(), path)
    } else {
        // No workspace was named, so a relative path means what it means to any
        // program: the working directory. The jail still judges the result
        // against the pinned root.
        join_native(
            std::env::current_dir().unwrap_or_else(|_| workspace_root()),
            path,
        )
    }
}

/// `base` joined with the relative `path` one component at a time, so the
/// result uses the platform's separator throughout (`proj\src\a.py` on
/// Windows, not `proj\src/a.py`) for the journal, the audit log and messages.
/// `.` components are dropped; `..` is kept for the jail to judge. A trailing
/// separator is kept, since it can say the path names a directory.
fn join_native(mut base: std::path::PathBuf, path: &str) -> String {
    for part in std::path::Path::new(path).components() {
        if part != std::path::Component::CurDir {
            base.push(part.as_os_str());
        }
    }
    let mut text = base.to_string_lossy().into_owned();
    if (path.ends_with('/') || path.ends_with('\\')) && !text.ends_with(std::path::MAIN_SEPARATOR) {
        text.push(std::path::MAIN_SEPARATOR);
    }
    text
}

/// Test whether a (possibly non-existent) path is contained in the workspace
/// root. Both sides are resolved to the same canonical form so the comparison
/// is correct across platforms (Windows verbatim `\\?\` prefixes, POSIX symlink
/// targets) and cannot be escaped by `..` traversal.
pub fn within_workspace(path: &str) -> bool {
    within_root(path, &workspace_root())
}

/// [`within_workspace`] for an arbitrary root: whether `path` resolves inside it.
pub fn within_root(path: &str, base: &Path) -> bool {
    let root = match base.canonicalize() {
        Ok(r) => r,
        Err(_) => return false,
    };
    // On Windows the two readings of `..` can differ, so both must stay inside.
    #[cfg(windows)]
    if !matches!(resolve_walked(win32_path(path)), Some(r) if r.starts_with(&root)) {
        return false;
    }
    match resolve_for_jail(path) {
        Some(resolved) => resolved.starts_with(&root),
        None => false,
    }
}

/// Why a journalled path may not be rewritten by `undo` or `redo` here, if it
/// may not.
///
/// A journal entry's path passed the jail when it was recorded, but the journal
/// persists across processes, keyed by working directory: a step recorded in
/// human mode, where nothing is jailed, can be replayed by an agent-mode
/// session in the same directory. Rewinding rewrites or deletes that file, so
/// in a jailed context a path outside the workspace is left alone.
pub fn rewind_refused(path: &str) -> Option<String> {
    if path.is_empty() || !jail_enforced(current_mode()) || within_workspace(path) {
        return None;
    }
    Some(
        "outside the workspace jail, so left as it is; rewind it outside agent mode, \
         or with IRONSHELL_WORKSPACE covering it"
            .to_string(),
    )
}

/// The most symbolic links one jail check follows (Linux `SYMLOOP_MAX`). A chain
/// longer than this, or a loop, makes the path count as outside the workspace.
const MAX_LINK_HOPS: usize = 40;

/// One component of a path that [`physical_path`] is walking.
enum WalkSeg {
    Prefix(std::ffi::OsString),
    Root,
    Parent,
    Normal(std::ffi::OsString),
}

/// The components of `path`, keeping `..` (which `Path::components` does not
/// remove) and dropping only `.`.
fn walk_segments(path: &Path) -> Vec<WalkSeg> {
    use std::path::Component;
    path.components()
        .filter_map(|comp| match comp {
            Component::Prefix(p) => Some(WalkSeg::Prefix(p.as_os_str().to_os_string())),
            Component::RootDir => Some(WalkSeg::Root),
            Component::CurDir => None,
            Component::ParentDir => Some(WalkSeg::Parent),
            Component::Normal(name) => Some(WalkSeg::Normal(name.to_os_string())),
        })
        .collect()
}

/// The absolute form of a user-supplied path, without any lexical cleaning: a
/// relative path is joined to the workspace root, itself made absolute.
fn absolute_form(path: &str) -> PathBuf {
    let given = Path::new(path);
    if given.is_absolute() {
        return given.to_path_buf();
    }
    let root = workspace_root();
    let root = if root.is_absolute() {
        root
    } else {
        std::env::current_dir().unwrap_or_default().join(root)
    };
    root.join(given)
}

/// The place the OS would reach for `path`, with every symbolic link resolved in
/// the order the OS resolves them.
///
/// The walk runs left to right from the absolute form. A normal component is
/// appended, and if it is a link its target replaces it: a relative target is
/// taken against the directory the walk has reached, and the walk restarts on
/// the target followed by the rest of the path. A `..` pops what the walk has
/// already resolved, so after `lnk/..` it is the parent of the link's target,
/// as it is for the OS. The result holds no link in any component that exists.
///
/// A component that does not exist is appended as it is. A later `..` pops it,
/// which matches what creating it would have done. Any other error reading a
/// component, or more than [`MAX_LINK_HOPS`] links, gives `None`: the caller
/// treats the path as outside the workspace.
fn physical_path(path: &str) -> Option<PathBuf> {
    let mut pending: std::collections::VecDeque<WalkSeg> =
        walk_segments(&absolute_form(path)).into();
    let mut out = PathBuf::new();
    let mut hops = 0usize;
    while let Some(seg) = pending.pop_front() {
        match seg {
            WalkSeg::Prefix(prefix) => out = PathBuf::from(prefix),
            WalkSeg::Root => out.push(std::path::Component::RootDir.as_os_str()),
            WalkSeg::Parent => {
                out.pop();
            }
            WalkSeg::Normal(name) => {
                let next = out.join(&name);
                match std::fs::symlink_metadata(&next) {
                    Ok(meta) if meta.file_type().is_symlink() => {
                        hops += 1;
                        if hops > MAX_LINK_HOPS {
                            return None;
                        }
                        let target = std::fs::read_link(&next).ok()?;
                        let target = if target.is_absolute() {
                            target
                        } else {
                            out.join(target)
                        };
                        let mut restart: std::collections::VecDeque<WalkSeg> =
                            walk_segments(&target).into();
                        restart.append(&mut pending);
                        pending = restart;
                        out = PathBuf::new();
                    }
                    Ok(_) => out = next,
                    Err(e)
                        if matches!(
                            e.kind(),
                            std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                        ) =>
                    {
                        out = next
                    }
                    Err(_) => return None,
                }
            }
        }
    }
    Some(out)
}

/// Resolve a path for jail comparison: walk it with [`physical_path`], then
/// canonicalize its deepest existing ancestor (resolving symlinks and the
/// Windows spellings: 8.3 names, trailing dots, verbatim prefixes) and re-append
/// the remainder, which holds no `..` and no link. This yields a path in the same
/// canonical namespace as a canonicalized workspace root, even when the leaf does
/// not yet exist. `None` when the path is outside the jail by construction (see
/// [`physical_path`]).
fn resolve_for_jail(path: &str) -> Option<PathBuf> {
    resolve_walked(physical_path(path)?)
}

/// The path with `..` removed by text, as Win32 does before the file system sees
/// it. On Windows the bytes land here, not where [`physical_path`] says: observed
/// on a Windows runner, `lnk/../f` with `lnk` pointing at `a/b` wrote `f`, not
/// `a/f`.
#[cfg(windows)]
fn win32_path(path: &str) -> PathBuf {
    let mut out = PathBuf::new();
    for seg in walk_segments(&absolute_form(path)) {
        match seg {
            WalkSeg::Prefix(prefix) => out = PathBuf::from(prefix),
            WalkSeg::Root => out.push(std::path::Component::RootDir.as_os_str()),
            WalkSeg::Parent => {
                out.pop();
            }
            WalkSeg::Normal(name) => out.push(name),
        }
    }
    out
}

fn resolve_walked(walked: PathBuf) -> Option<PathBuf> {
    for anc in walked.ancestors() {
        if let Ok(canon) = anc.canonicalize() {
            return Some(match walked.strip_prefix(anc) {
                Ok(rest) => canon.join(rest),
                Err(_) => canon,
            });
        }
    }
    Some(walked)
}

// ════════════════════════════════════════════════════════════════════════
// Approval registry (§7.2)
// ════════════════════════════════════════════════════════════════════════

lazy_static! {
    static ref GRANTED: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}

/// Grant an approval token in-process (e.g. after an interactive confirmation
/// or an A2UI prompt). The token must equal the descriptor's bound token.
pub fn grant_approval(token: &str) {
    if let Ok(mut g) = GRANTED.lock() {
        g.insert(token.to_string());
    }
}

/// Revoke a previously granted token.
pub fn revoke_approval(token: &str) {
    if let Ok(mut g) = GRANTED.lock() {
        g.remove(token);
    }
}

/// Whether `token` has been approved (via `IRONSHELL_APPROVE_ALL`, the
/// `IRONSHELL_APPROVE` list, or an in-process `grant_approval`). Public so batch
/// executors (plan/apply) can gate a whole plan on a single approval token.
pub fn is_approved(token: &str) -> bool {
    is_token_approved(token)
}

/// Whether `IRONSHELL_APPROVE` names at least one token. Only used after a call
/// has failed to match, so a set value means its tokens were tried and missed.
fn approve_env_is_set() -> bool {
    std::env::var("IRONSHELL_APPROVE")
        .is_ok_and(|list| list.split(',').any(|t| !t.trim().is_empty()))
}

/// How a refused call says its approval token is granted. In agent mode
/// `approve()` is refused for the agent's own calls (AS-2026-01), so naming it
/// would offer a dead end: the grant comes from whoever launched the agent,
/// through `IRONSHELL_APPROVE`. Outside agent mode `approve()` is the in-process
/// route and is named too.
pub fn approval_instruction(token: &str) -> String {
    if current_mode() == Mode::Agent {
        format!(
            "a human approves this token out of band: re-run with IRONSHELL_APPROVE={token} set by the operator"
        )
    } else {
        format!("re-run with IRONSHELL_APPROVE={token} (or call approve(\"{token}\"))")
    }
}

/// The full hint for a refused call that needs `token`. `network` adds the
/// operator's allowlist route, which is the only other way a `Network` call
/// is admitted.
fn approval_refusal_hint(token: &str, network: bool) -> String {
    let mut hint = approval_instruction(token);
    if network {
        hint.push_str(
            ", or have the operator allow the destination with IRONSHELL_NET_ALLOW=<host>",
        );
    }
    // This call was not approved, so every token in a set IRONSHELL_APPROVE
    // failed to match it. Without saying so, the variable looks ignored, and a
    // retry with the same value fails the same way.
    if approve_env_is_set() {
        hint.push_str(
            "; IRONSHELL_APPROVE was set but none of its tokens approve this call; tokens are bound to the exact action and target",
        );
    }
    hint
}

/// The `E_NEEDS_APPROVAL` refusal for a batch gated on one plan token (`apl_`).
/// It has the shape the central gate gives a single call, so an agent reads one
/// error for every gated call, and `approval.token` is the plan's token.
pub fn plan_needs_approval(
    builtin: &str,
    token: &str,
    targets: Vec<String>,
    operations: usize,
) -> SafetyError {
    let what = "apply plan";
    SafetyError {
        code: ErrorCode::NeedsApproval,
        message: format!("{builtin}: requires approval ({what})"),
        builtin: builtin.to_string(),
        hint: approval_refusal_hint(token, false),
        approval: Some(ApprovalDescriptor {
            what: what.to_string(),
            builtin: builtin.to_string(),
            targets,
            blast_radius: json!({ "operations": operations }),
            // A plan is not claimed reversible as a whole: a `mkdir` is not
            // restored, and a file over the journal's capture limit is recorded
            // as irreversible.
            reversible: false,
            token: token.to_string(),
        }),
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    }
}

fn is_token_approved(token: &str) -> bool {
    if truthy_env("IRONSHELL_APPROVE_ALL") {
        return true;
    }
    // IRONSHELL_APPROVE may carry a comma-separated list of approved tokens.
    if let Ok(list) = std::env::var("IRONSHELL_APPROVE") {
        if list.split(',').map(str::trim).any(|t| t == token) {
            return true;
        }
    }
    GRANTED.lock().map(|g| g.contains(token)).unwrap_or(false)
}

// ════════════════════════════════════════════════════════════════════════
// RBAC principal authorization (§7.1) — an authenticated principal with the
// right permission bypasses the per-action approval requirement.
// ════════════════════════════════════════════════════════════════════════

lazy_static! {
    /// The RBAC manager backing principal authorization (None = RBAC disabled).
    static ref RBAC: Mutex<Option<std::sync::Arc<crate::auth::RbacManager>>> = Mutex::new(None);
    /// The current acting principal's user id (None = anonymous).
    static ref PRINCIPAL: Mutex<Option<String>> = Mutex::new(None);
}

/// Install the RBAC manager used to authorize principals against effect classes.
pub fn set_rbac_manager(mgr: std::sync::Arc<crate::auth::RbacManager>) {
    if let Ok(mut g) = RBAC.lock() {
        *g = Some(mgr);
    }
}

/// Disable RBAC authorization (revert to plain policy + approval).
pub fn clear_rbac_manager() {
    if let Ok(mut g) = RBAC.lock() {
        *g = None;
    }
}

/// Set the current acting principal (user id) for authorization decisions.
pub fn set_principal(user_id: Option<String>) {
    if let Ok(mut g) = PRINCIPAL.lock() {
        *g = user_id;
    }
}

/// The current acting principal's user id, if any.
pub fn current_principal() -> Option<String> {
    PRINCIPAL.lock().ok().and_then(|g| g.clone())
}

/// Load and install an RBAC manager from config at startup, if configured, and
/// set the acting principal. Sources, in order:
///
/// - `IRONSHELL_PRINCIPAL=<id>` sets the acting principal (independent of a config).
/// - `IRONSHELL_RBAC_CONFIG=<path>` (or `<workspace>/.ironshell/rbac.toml` if it exists)
///   is parsed as a TOML [`crate::auth::RbacConfig`], installed as the manager,
///   and its `principal` is used if `IRONSHELL_PRINCIPAL` didn't already set one.
///
/// No-op when nothing is configured, so default runs are unaffected. Parse/read
/// failures warn (security_audit) and leave RBAC disabled rather than aborting.
pub fn init_rbac_from_env() {
    if let Ok(p) = std::env::var("IRONSHELL_PRINCIPAL") {
        if !p.is_empty() {
            set_principal(Some(p));
        }
    }
    let path = match std::env::var("IRONSHELL_RBAC_CONFIG") {
        Ok(p) => PathBuf::from(p),
        Err(_) => {
            let default = workspace_root().join(".ironshell").join("rbac.toml");
            if !default.exists() {
                return;
            }
            default
        }
    };
    let text = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(e) => {
            tracing::warn!(target: "security_audit", "rbac config read {}: {}", path.display(), e);
            return;
        }
    };
    match crate::auth::RbacManager::from_config_str(&text) {
        Ok((mgr, principal)) => {
            set_rbac_manager(std::sync::Arc::new(mgr));
            if current_principal().is_none() {
                if let Some(p) = principal {
                    set_principal(Some(p));
                }
            }
        }
        Err(e) => {
            tracing::warn!(target: "security_audit", "rbac config parse {}: {}", path.display(), e);
        }
    }
}

/// Whether the current principal is RBAC-authorized for this effect. A grant
/// (`effect:<class>`, `effect:*`, `*:*`, or `builtin:<name>`) returns
/// `Some(true)`; the absence of a manager/principal or grant returns `None`
/// (defer to the default policy — RBAC here is additive, never a hard deny).
fn rbac_authorized(effect: Effect, builtin: &str) -> Option<bool> {
    let mgr = RBAC.lock().ok()?.clone()?;
    let user = current_principal()?;
    let by_effect = format!("effect:{}", effect.as_str());
    let by_builtin = format!("builtin:{}", builtin);
    if mgr.check_permission(&user, &by_effect) || mgr.check_permission(&user, &by_builtin) {
        Some(true)
    } else {
        None
    }
}

// ════════════════════════════════════════════════════════════════════════
// Hash-chained audit log (§7.5)
// ════════════════════════════════════════════════════════════════════════

struct AuditState {
    seq: u64,
    last_hash: String,
    /// The log path the in-memory chain (`seq`/`last_hash`) belongs to. When the
    /// active path differs, the chain is reset and the new file's tail reloaded,
    /// so switching logs never continues a stale chain into a fresh file.
    path: Option<PathBuf>,
}

lazy_static! {
    static ref AUDIT: Mutex<AuditState> = Mutex::new(AuditState {
        seq: 0,
        last_hash: GENESIS_HASH.to_string(),
        path: None,
    });
}

/// The audit log path, or `None` if auditing is disabled for this run.
/// `IRONSHELL_AUDIT_LOG` overrides; in agent mode it defaults to
/// `<workspace>/.ironshell/audit.log`. Human mode without an explicit path = no audit
/// (so the default REPL has no side effects).
pub fn audit_path() -> Option<PathBuf> {
    if let Ok(p) = std::env::var("IRONSHELL_AUDIT_LOG") {
        return Some(PathBuf::from(p));
    }
    if current_mode() == Mode::Agent {
        return Some(workspace_root().join(".ironshell").join("audit.log"));
    }
    None
}

fn hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{:02x}", b));
    }
    s
}

fn sha256_hex(s: &str) -> Result<String, ironcrypto::core_types::Error> {
    Ok(hex(&Sha256::digest(s.as_bytes())?))
}

// ── Chain keying (AS-2026-02) ────────────────────────────────────────────
//
// An unkeyed SHA-256 chain is evidence against corruption, not against an
// author. Anyone who can write the file can truncate it and rewrite it
// end-to-end with a fresh, internally consistent chain that `verify_audit`
// accepts. Keying the chain with HMAC-SHA256 means a rewrite requires the key,
// so tampering by anyone who has only *write* access is detectable.
//
// What this does and does not defend against, stated plainly, because the
// difference decides where the key may live:
//
//   * An approved `Exec` -- a spawned `sh`, `tar`, `git` -- that writes to the
//     log: DETECTED. The child never sees the key (see `remove_var` below), so
//     it cannot produce a valid tag.
//   * Someone editing the file later, offline: DETECTED.
//   * Code running *inside this process*: NOT detected, and cannot be. Whatever
//     key this process can append with, it can forge with. No in-process scheme
//     fixes that; it needs an append-only sink the process cannot rewrite
//     (remote syslog, a WORM mount), which is a deployment decision.
//
// The key must therefore never reach a child process. `IRONSHELL_AUDIT_KEY` is
// read exactly once and then removed from this process's environment, so every
// later `Command::spawn` -- which inherits the parent environment by default --
// starts without it.

/// Minimum accepted key material. Each entry carries a `key_id` derived from
/// the key, so a short, guessable key would be a brute-force oracle; 32 bytes
/// makes that irrelevant rather than merely inconvenient.
const AUDIT_KEY_MIN_BYTES: usize = 32;

lazy_static! {
    /// Resolved once. `None` = unkeyed chain (the pre-10.0.0 behaviour, and
    /// still the default: keying is opt-in because it needs somewhere to put a
    /// key, which only the operator can decide).
    static ref AUDIT_KEY: Option<Vec<u8>> = load_audit_key();
}

/// The variable that supplied a chain key which was set but too short to use
/// (`IRONSHELL_AUDIT_KEY` or `IRONSHELL_AUDIT_KEY_FILE`), so `audit_verify` can
/// say the key was set and rejected rather than report a plain unkeyed chain.
static AUDIT_KEY_REJECTED: Mutex<Option<&'static str>> = Mutex::new(None);

/// The variable name of a rejected (set, but too short) chain key, if any.
pub fn audit_key_rejected() -> Option<&'static str> {
    AUDIT_KEY_REJECTED.lock().ok().and_then(|g| *g)
}

/// Read the chain key from `IRONSHELL_AUDIT_KEY` (hex or raw bytes) or from the
/// file named by `IRONSHELL_AUDIT_KEY_FILE`. A key that is set but too short
/// (fewer than 32 bytes) is not used: the chain is written unkeyed, one warning
/// goes to stderr, and `audit_verify` reports the rejected key.
fn load_audit_key() -> Option<Vec<u8>> {
    let from_env = std::env::var("IRONSHELL_AUDIT_KEY").ok();
    if from_env.is_some() {
        // Before anything else can spawn a child that would inherit it.
        std::env::remove_var("IRONSHELL_AUDIT_KEY");
    }
    let (raw, var) = match from_env {
        Some(v) => (v, "IRONSHELL_AUDIT_KEY"),
        None => match std::env::var("IRONSHELL_AUDIT_KEY_FILE") {
            Ok(path) => match std::fs::read_to_string(&path) {
                Ok(c) => (c.trim().to_string(), "IRONSHELL_AUDIT_KEY_FILE"),
                Err(e) => {
                    tracing::error!(
                        target: "security_audit",
                        "IRONSHELL_AUDIT_KEY_FILE={} could not be read ({}); the audit chain is \
                         UNKEYED and a rewrite by anyone with write access will verify clean",
                        path, e
                    );
                    return None;
                }
            },
            Err(_) => return None,
        },
    };

    // Hex is the documented form; raw bytes are accepted so an operator can
    // point the file at `head -c 32 /dev/urandom` output without encoding it.
    let bytes = match hex::decode(raw.trim()) {
        Ok(b) if b.len() >= AUDIT_KEY_MIN_BYTES => b,
        _ => raw.trim().as_bytes().to_vec(),
    };
    if bytes.len() < AUDIT_KEY_MIN_BYTES {
        if let Ok(mut g) = AUDIT_KEY_REJECTED.lock() {
            *g = Some(var);
        }
        tracing::error!(
            target: "security_audit",
            "audit chain key is {} bytes, below the {}-byte minimum; the chain is UNKEYED",
            bytes.len(), AUDIT_KEY_MIN_BYTES
        );
        let subject = if var == "IRONSHELL_AUDIT_KEY" {
            "IRONSHELL_AUDIT_KEY is set but"
        } else {
            "IRONSHELL_AUDIT_KEY_FILE contents are"
        };
        eprintln!(
            "{} shorter than {} characters, so the audit chain is not keyed",
            subject, AUDIT_KEY_MIN_BYTES
        );
        return None;
    }
    Some(bytes)
}

/// The active chain key, or `None` when the chain is unkeyed.
pub fn audit_key() -> Option<&'static [u8]> {
    AUDIT_KEY.as_deref()
}

/// A short, non-secret label for the key in use, so a verifier can tell "wrong
/// key" from "tampered" and so rotation shows up in the log rather than looking
/// like corruption. The label predates the IronShell rename and is kept, so
/// the key ids already written to audit logs still match.
fn audit_key_id(key: &[u8]) -> Result<String, ironcrypto::core_types::Error> {
    let mut h = Sha256::new();
    h.update(b"AetherShell-audit-key-id\x00");
    h.update(key);
    Ok(hex(&h.finalize()?)[..16].to_string())
}

/// The chain tag over an entry's canonical core: HMAC-SHA256 when a key is
/// configured, plain SHA-256 otherwise.
fn chain_tag(key: Option<&[u8]>, s: &str) -> Result<String, ironcrypto::core_types::Error> {
    match key {
        Some(k) => {
            use ironcrypto::core_types::traits::Mac as _;
            let tag = ironcrypto::mac::HmacSha256::mac(k, s.as_bytes())?;
            Ok(hex(&tag))
        }
        None => sha256_hex(s),
    }
}

/// Recover `seq`/`last_hash` from the tail of an existing log so the chain
/// continues across process restarts. Assumes the caller has already reset
/// `seq`/`last_hash` to genesis for a fresh file.
fn load_tail(path: &PathBuf, state: &mut AuditState) {
    if let Ok(content) = std::fs::read_to_string(path) {
        if let Some(last) = content.lines().rev().find(|l| !l.trim().is_empty()) {
            if let Ok(obj) = serde_json::from_str::<Json>(last) {
                if let Some(seq) = obj.get("seq").and_then(|v| v.as_u64()) {
                    state.seq = seq;
                }
                if let Some(h) = obj.get("entry_hash").and_then(|v| v.as_str()) {
                    state.last_hash = h.to_string();
                }
            }
        }
    }
}

/// Read the last non-empty line of a file without reading the whole file. The
/// audit log is append-only and grows without bound, so the tail check below
/// runs on every guarded operation and must not be O(size).
fn read_last_line(path: &PathBuf) -> Option<String> {
    use std::io::{Read, Seek, SeekFrom};
    const WINDOW: u64 = 64 * 1024;

    let mut f = std::fs::File::open(path).ok()?;
    let len = f.metadata().ok()?.len();
    if len == 0 {
        return None;
    }
    let start = len.saturating_sub(WINDOW);
    f.seek(SeekFrom::Start(start)).ok()?;
    let mut buf = Vec::with_capacity((len - start) as usize);
    f.read_to_end(&mut buf).ok()?;
    let text = String::from_utf8_lossy(&buf);
    // With a partial window the first line may be a fragment.
    //
    // The last one can be too. This used to say it never is, and that was
    // wrong: another process appending while this one reads can be observed
    // mid-write, and the reader then sees a truncated final line. Measured at
    // ~15% of runs with two concurrent writers under load.
    //
    // A caller that needs a *usable* tail should ask for the last line that
    // parses, not the last line; see `read_last_entry_line`.
    text.lines()
        .rev()
        .find(|l| !l.trim().is_empty())
        .map(|s| s.to_string())
}

/// The last line of the log that is a complete JSON entry.
///
/// Trailing garbage is skipped rather than read as evidence. A line that does
/// not parse is far more often another process's append caught in flight than
/// it is an attack, and the two were indistinguishable to
/// [`detect_tail_divergence`], which reported the torn read as
/// `tamper-detected`. An alarm that fires because two agents wrote at once is
/// the alarm nobody reads -- the same failure the per-process writer id was
/// added to fix, arriving by a different route.
///
/// Returns the parsed entry with its line, or `None` if the window holds no
/// complete entry at all. That case is genuinely suspicious and the caller
/// still treats it as such.
fn read_last_entry_line(path: &PathBuf) -> Option<Json> {
    use std::io::{Read, Seek, SeekFrom};
    const WINDOW: u64 = 64 * 1024;

    let mut f = std::fs::File::open(path).ok()?;
    let len = f.metadata().ok()?.len();
    if len == 0 {
        return None;
    }
    let start = len.saturating_sub(WINDOW);
    f.seek(SeekFrom::Start(start)).ok()?;
    let mut buf = Vec::with_capacity((len - start) as usize);
    f.read_to_end(&mut buf).ok()?;
    let text = String::from_utf8_lossy(&buf);

    text.lines()
        .rev()
        .filter(|l| !l.trim().is_empty())
        .find_map(|l| serde_json::from_str::<Json>(l).ok())
}

/// Has the log been rewritten underneath us since our last append?
///
/// The in-memory chain (`state.last_hash`) is the honest record of what this
/// process wrote. If the file's tail no longer matches it, something outside
/// this process's audit path changed the file -- a truncation, an overwrite, a
/// hand-edit. That is exactly the residual hole in AS-2026-02: an *approved*
/// `Exec` runs arbitrary code, and no jail rule can stop `sh -c '> audit.log'`.
///
/// Keying makes such a rewrite fail an offline verify. This makes it visible at
/// the next append instead of at the next audit, which is the difference
/// between catching it in minutes and catching it in months.
/// A random identifier for this process's audit writer.
///
/// The chain is per-process state — `seq` and `last_hash` live in memory — so
/// two processes appending to one log both start at `seq: 1` from genesis and
/// interleave two chains into one file. That is not exotic: in agent mode the
/// log defaults to `<workspace>/.ironshell/audit.log`, so two agents in one workspace
/// share it by default.
///
/// Recording who wrote each entry does not make the interleaving valid. What it
/// does is let the reader say so accurately — "this log has entries from 2
/// writers" rather than "broken chain link", which reads as tampering — and let
/// the tail check tell a concurrent writer apart from someone rewriting the
/// file. A tamper alarm that fires whenever two agents run is a control that
/// stops being read.
fn writer_id() -> &'static str {
    static ID: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    ID.get_or_init(|| {
        let n: u64 = rand::random();
        format!("{:016x}", n)
    })
}

fn detect_tail_divergence(path: &PathBuf, state: &AuditState) -> Option<String> {
    // Nothing written yet in this process: the tail is whatever we loaded, and
    // `load_tail` already trusted it. Nothing to compare against.
    if state.seq == 0 {
        return None;
    }
    // The last *complete* entry, not the last line. A partially written line at
    // the end of the file is another process appending, not an attacker.
    match read_last_entry_line(path) {
        None => {
            // No complete entry anywhere in the window. An empty or missing
            // file, or one whose tail is entirely unreadable -- both are worth
            // reporting, and neither is produced by ordinary concurrency.
            if read_last_line(path).is_none() {
                Some("the audit log is missing or empty".to_string())
            } else {
                Some("the audit log tail holds no complete entry".to_string())
            }
        }
        Some(entry) => {
            // Another process appending to the same log is a different thing
            // from someone rewriting it, and calling both "tamper-detected"
            // makes the alarm useless in the configuration agent mode ships
            // with. If the tail carries a different writer id, this is
            // concurrency; the log is still not a single verifiable chain, and
            // `verify_audit` says so, but it is not evidence of an attacker.
            if let Some(w) = entry.get("writer").and_then(|v| v.as_str()) {
                if w != writer_id() {
                    return None;
                }
            }
            let observed = entry
                .get("entry_hash")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            if observed == state.last_hash {
                None
            } else {
                Some(format!(
                    "the audit log tail is {} but this process last wrote {}",
                    if observed.is_empty() {
                        "an entry with no hash".to_string()
                    } else {
                        format!("entry {}", &observed[..observed.len().min(12)])
                    },
                    &state.last_hash[..state.last_hash.len().min(12)]
                ))
            }
        }
    }
}

/// Build one chained entry: the serialized line, plus the `(seq, entry_hash)`
/// the caller should commit to `AuditState` once the line is safely on disk.
/// Kept separate from the write so the tamper marker and an ordinary entry are
/// produced by exactly the same code -- a marker that chained differently from
/// a normal entry would fail verification and look like the tampering it
/// reports.
fn build_entry(
    state: &AuditState,
    builtin: &str,
    effect: Effect,
    decision: &str,
    resource: &str,
    detail: Json,
) -> Result<(u64, String, String), String> {
    let seq = state.seq + 1;
    let ts = chrono::Utc::now().to_rfc3339();
    let principal = std::env::var("USER")
        .or_else(|_| std::env::var("USERNAME"))
        .ok();

    // Scrub secret shapes out of the resource string and detail metadata before
    // they are hashed and persisted — the audit log is a durable artifact, so a
    // leaked credential there would outlive the run (§7.6).
    let (resource, detail) = if redaction_enabled() {
        let (r, _) = redact_str(resource);
        let mut d = detail;
        redact_json(&mut d);
        (r, d)
    } else {
        (resource.to_string(), detail)
    };

    // Canonical core (everything but entry_hash); prev_hash chains entries.
    let key = audit_key();
    let mut core = json!({
        "seq": seq,
        "ts": ts,
        "principal": principal,
        "builtin": builtin,
        "effect": effect.as_str(),
        "decision": decision,
        "resource": resource,
        "detail": detail,
        "prev_hash": state.last_hash,
        "writer": writer_id(),
    });
    // The algorithm label lives *inside* the tagged core, so an attacker cannot
    // relabel a keyed entry as unkeyed and recompute it with a plain SHA-256
    // (AS-2026-02). `verify_audit` rejects that downgrade from the other side
    // too, by requiring a tag on every entry once a key is configured.
    if let Some(k) = key {
        core["mac"] = json!("hmac-sha256");
        core["key_id"] = json!(audit_key_id(k).map_err(|e| format!("audit chain: {e}"))?);
    }
    let entry_hash =
        chain_tag(key, &core.to_string()).map_err(|e| format!("audit chain tag refused: {e}"))?;

    let mut full = core;
    full["entry_hash"] = json!(entry_hash);
    Ok((seq, entry_hash, full.to_string()))
}

/// Append one already-built line to the log, creating the directory if needed.
fn append_line(path: &PathBuf, line: &str) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    write_record(&mut f, line)
}

/// Write one record — content *and* newline — in a single call.
///
/// `writeln!` emits the content and the newline as separate writes, and an
/// `O_APPEND` handle only guarantees atomicity per write. Two processes
/// appending to one log could therefore interleave *within a line*, producing
/// output that is not valid JSON at all:
///
/// ```text
/// json.decoder.JSONDecodeError: Extra data: line 1 column 401
/// ```
///
/// An audit log that cannot be parsed is worse than one that fails to verify:
/// verification at least tells you something happened. Building the record with
/// its terminator and issuing one write keeps each line intact, which is what
/// makes a shared log analysable even when it is not a single chain.
fn write_record(f: &mut std::fs::File, line: &str) -> std::io::Result<()> {
    let record = format!("{}\n", line);
    f.write_all(record.as_bytes())
}

/// Mirror one entry to the append-only sink named by `IRONSHELL_AUDIT_SINK`.
///
/// Keying the chain (AS-2026-02) stops anyone who can only *write* the log
/// from forging it, but not code running inside this process: whatever key the
/// shell appends with, it can also forge with. No in-process scheme fixes
/// that. What does fix it is a sink the shell cannot rewrite, and this is the
/// hook for one — point it at a FIFO drained by a collector, a WORM mount, or
/// a file on a filesystem where the shell's user has append but not write.
///
/// Being explicit about the limit: this call opens the path in append mode and
/// writes a line. If you point it at an ordinary file the process can rewrite,
/// it buys nothing. The integrity comes from what is behind the path, not from
/// here.
fn mirror_to_sink(line: &str) -> std::io::Result<()> {
    let sink = match std::env::var_os("IRONSHELL_AUDIT_SINK") {
        Some(p) if !p.is_empty() => PathBuf::from(p),
        _ => return Ok(()),
    };
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&sink)?;
    write_record(&mut f, line)
}

/// Poison the audit lock, as a panic while holding it would.
/// Not part of the public API.
#[doc(hidden)]
pub fn __test_poison_audit_lock() {
    let _ = std::thread::spawn(|| {
        let _held = AUDIT.lock();
        panic!("poisoning the audit lock for a test");
    })
    .join();
}

/// Append a tamper-evident audit entry. Best-effort: a write failure logs a
/// warning but never blocks the guarded operation, unless
/// `IRONSHELL_AUDIT_REQUIRED=1`, in which case the error is returned.
pub fn audit(
    builtin: &str,
    effect: Effect,
    decision: &str,
    resource: &str,
    detail: Json,
) -> Result<(), String> {
    let path = match audit_path() {
        Some(p) => p,
        None => return Ok(()),
    };

    // The chain state behind a poisoned lock cannot be trusted, so nothing is
    // written. That was silent even when the entry was required: audit_log said
    // "logged" and apply said "applied" with no record made.
    let mut state = match AUDIT.lock() {
        Ok(s) => s,
        Err(_) => {
            let reason =
                "the audit log is unusable: an earlier call panicked while holding its lock";
            if truthy_env("IRONSHELL_AUDIT_REQUIRED") {
                return Err(reason.to_string());
            }
            tracing::error!(target: "security_audit", "audit entry dropped: {}", reason);
            return Ok(());
        }
    };
    // If the active log path changed (multi-workspace use, tests), reset the
    // chain and reload the new file's tail rather than continuing a stale chain.
    if state.path.as_deref() != Some(path.as_path()) {
        let previous = state.path.take();
        state.seq = 0;
        state.last_hash = GENESIS_HASH.to_string();
        state.path = Some(path.clone());
        load_tail(&path, &mut state);

        // A library caller that never pinned the workspace can still move the
        // log by moving the working directory. The new chain must not start
        // silently: say, in the new log, which log this process was writing.
        // The marker chains like any entry, so `verify_audit` accepts it.
        if let (Some(old), Mode::Agent) = (previous, current_mode()) {
            let reason = format!(
                "the audit log path changed within one process, from {} to {}; this log starts a new chain here",
                old.display(),
                path.display()
            );
            if let Ok((mseq, mhash, mline)) = build_entry(
                &state,
                "audit_chain",
                Effect::Privileged,
                "log-path-changed",
                &reason,
                json!({ "previous_log": old.display().to_string() }),
            ) {
                if append_line(&path, &mline).is_ok() {
                    state.seq = mseq;
                    state.last_hash = mhash;
                }
            }
        }
    }

    // If the file no longer ends where we left it, say so *in the log itself*,
    // as its own chained entry, before appending the entry we were called for.
    // A rewrite that removed entries then leaves a permanent, chained marker at
    // the point of discovery instead of a clean-looking file.
    if let Some(reason) = detect_tail_divergence(&path, &state) {
        tracing::error!(
            target: "security_audit",
            "audit log integrity: {} — the log was modified outside the audit path", reason
        );
        let broken_from = state.last_hash.clone();
        let broken_seq = state.seq;
        // Re-anchor to what is actually on disk, so the marker chains onto the
        // file as it now stands; the marker itself records what the chain was.
        state.seq = 0;
        state.last_hash = GENESIS_HASH.to_string();
        load_tail(&path, &mut state);

        let (mseq, mhash, mline) = build_entry(
            &state,
            "audit_chain",
            Effect::Privileged,
            "tamper-detected",
            &reason,
            json!({
                "expected_prev_hash": broken_from,
                "entries_written_by_this_process": broken_seq,
            }),
        )?;
        // Best-effort: if this write fails, the tracing::error above is still
        // the record, and the caller's own entry is attempted regardless.
        if append_line(&path, &mline).is_ok() {
            state.seq = mseq;
            state.last_hash = mhash;
        }
    }

    let (seq, entry_hash, line) = build_entry(&state, builtin, effect, decision, resource, detail)?;

    match append_line(&path, &line) {
        Ok(()) => {
            state.seq = seq;
            state.last_hash = entry_hash;
            // Mirror after the primary write succeeds, so the sink never holds
            // an entry the log itself does not.
            if let Err(e) = mirror_to_sink(&line) {
                if truthy_env("IRONSHELL_AUDIT_REQUIRED") {
                    return Err(format!("audit sink write failed: {}", e));
                }
                tracing::warn!(target: "security_audit", "audit sink write failed: {}", e);
            }
            Ok(())
        }
        Err(e) => {
            if truthy_env("IRONSHELL_AUDIT_REQUIRED") {
                Err(format!("audit write failed: {}", e))
            } else {
                tracing::warn!(target: "security_audit", "audit write failed: {}", e);
                Ok(())
            }
        }
    }
}

/// Read the most recent `n` audit entries (parsed JSON objects) from the active
/// log, oldest-to-newest. Returns empty if auditing is disabled or unreadable —
/// a read-only review of what was allowed / denied / approved.
pub fn read_audit_tail(n: usize) -> Vec<Json> {
    let path = match audit_path() {
        Some(p) => p,
        None => return Vec::new(),
    };
    let content = match std::fs::read_to_string(&path) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };
    let lines: Vec<&str> = content.lines().filter(|l| !l.trim().is_empty()).collect();
    let start = lines.len().saturating_sub(n);
    lines[start..]
        .iter()
        .filter_map(|l| serde_json::from_str::<Json>(l).ok())
        .collect()
}

/// Verify a hash-chained audit log. Returns the number of valid entries, or an
/// error describing the first inconsistency (broken hash, bad chain link, or
/// non-monotonic sequence).
pub fn verify_audit(path: &PathBuf) -> Result<u64, String> {
    verify_audit_with(path, audit_key())
}

/// `verify_audit` against an explicit chain key. Separated so a verifier can
/// check a log it did not produce -- an operator holding the key auditing an
/// agent's log offline is the whole point of keying the chain.
pub fn verify_audit_with(path: &PathBuf, key: Option<&[u8]>) -> Result<u64, String> {
    let content = std::fs::read_to_string(path).map_err(|e| format!("read: {}", e))?;
    let mut prev = GENESIS_HASH.to_string();
    let mut expected_seq = 1u64;
    let mut count = 0u64;
    let mut writers: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();

    for (lineno, line) in content.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let mut obj: Json =
            serde_json::from_str(line).map_err(|e| format!("line {}: parse: {}", lineno + 1, e))?;

        if let Some(w) = obj.get("writer").and_then(|v| v.as_str()) {
            writers.insert(w.to_string());
        }

        let stored = obj
            .get("entry_hash")
            .and_then(|v| v.as_str())
            .ok_or_else(|| format!("line {}: missing entry_hash", lineno + 1))?
            .to_string();

        // Recompute over the core (object minus entry_hash). Removing the key
        // yields the same sorted object that was hashed at append time.
        if let Json::Object(m) = &mut obj {
            m.remove("entry_hash");
        }
        // Downgrade check before the tag check, so the error names the real
        // problem. A keyed verifier must refuse an unkeyed entry: otherwise
        // truncating the log and rewriting it with plain SHA-256 -- which needs
        // no key at all -- would verify clean (AS-2026-02).
        let claims_mac = obj.get("mac").and_then(|v| v.as_str());
        match (key, claims_mac) {
            (Some(_), None) => {
                return Err(format!(
                    "line {}: entry is unkeyed but this log is verified with a key — a rewritten chain looks exactly like this",
                    lineno + 1
                ))
            }
            (Some(_), Some(alg)) if alg != "hmac-sha256" => {
                return Err(format!("line {}: unknown chain mac {:?}", lineno + 1, alg))
            }
            (None, Some(_)) => {
                return Err(format!(
                    "line {}: entry is keyed but no chain key is configured; set IRONSHELL_AUDIT_KEY or IRONSHELL_AUDIT_KEY_FILE to verify it",
                    lineno + 1
                ))
            }
            _ => {}
        }

        let recomputed = chain_tag(key, &obj.to_string())
            .map_err(|e| format!("line {}: chain tag refused: {e}", lineno + 1))?;
        if !ironcrypto::core_types::ct::verify(stored.as_bytes(), recomputed.as_bytes()) {
            // An unkeyed chain is plain SHA-256 that anyone can recompute, so
            // a mismatch there cannot be attributed to tampering.
            return Err(if key.is_some() {
                format!("line {}: entry_hash mismatch (tampered)", lineno + 1)
            } else {
                format!(
                    "line {}: entry_hash mismatch (the log was edited or corrupted; an unkeyed chain cannot tell which)",
                    lineno + 1
                )
            });
        }

        let prev_hash = obj.get("prev_hash").and_then(|v| v.as_str()).unwrap_or("");
        if prev_hash != prev {
            // Distinguish a shared log from a rewritten one. Two processes
            // appending to one file interleave two chains, each internally
            // sound; reporting that as "broken chain link" reads as tampering
            // and sends the reader looking for an attacker who is not there.
            if writers.len() > 1 {
                return Err(format!(
                    "line {}: this log interleaves entries from {} writers, so it is not a single chain; give each process its own IRONSHELL_AUDIT_LOG, or share one append-only sink via IRONSHELL_AUDIT_SINK",
                    lineno + 1,
                    writers.len()
                ));
            }
            return Err(format!("line {}: broken chain link", lineno + 1));
        }

        let seq = obj.get("seq").and_then(|v| v.as_u64()).unwrap_or(0);
        if seq != expected_seq {
            return Err(format!(
                "line {}: non-monotonic seq (expected {}, got {})",
                lineno + 1,
                expected_seq,
                seq
            ));
        }

        prev = stored;
        expected_seq += 1;
        count += 1;
    }
    Ok(count)
}

// ════════════════════════════════════════════════════════════════════════
// Resource governors (§7.6)
// ════════════════════════════════════════════════════════════════════════
//
// A per-run blast-radius envelope: an agent may perform at most a bounded number
// of effecting operations and run for a bounded wall-clock time. Enforced at the
// `guard()` chokepoint (so it covers every effecting builtin uniformly) and only
// in agent mode. All limits are opt-in via env — unset = unlimited — so existing
// runs are unaffected until a limit is configured. A breach returns the structured
// `E_BUDGET_EXCEEDED` so an agent stops rather than looping. Counters tally
// *attempts* at the guard boundary (an op that is then denied by jail/policy still
// counts — the envelope bounds what the agent may try, the strictly-safe reading).
//
// | Env var             | Bounds                                              |
// |---------------------|-----------------------------------------------------|
// | `IRONSHELL_MAX_OPS`    | total guarded operations                            |
// | `IRONSHELL_MAX_FILES`  | filesystem ops (WriteLocal + Destructive)           |
// | `IRONSHELL_MAX_PROCS`  | process/exec ops (Process + Exec)                   |
// | `IRONSHELL_MAX_NET`    | network ops (Network) — egress request count        |
// | `IRONSHELL_TIMEOUT_MS` | wall-clock ms since the first guarded op (or reset) |

#[derive(Default)]
struct GovernorState {
    start: Option<std::time::Instant>,
    total: u64,
    files: u64,
    procs: u64,
    net: u64,
}

lazy_static! {
    static ref GOVERNOR: Mutex<GovernorState> = Mutex::new(GovernorState::default());
}

fn env_u64(name: &str) -> Option<u64> {
    std::env::var(name)
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
}

/// `budget_error` as an `anyhow::Error`, for builtins that govern their own
/// work rather than going through the central op counter.
///
/// A walk that gives up partway has a partial answer, and returning that as
/// though it were the whole one is the silent-wrong-answer defect this
/// taxonomy exists to remove -- `project_loc` counting half a tree and
/// reporting an Int is indistinguishable from a small project.
pub fn budget_exceeded(builtin: &str, message: String, hint: &str) -> anyhow::Error {
    anyhow::Error::new(budget_error(builtin, message, hint))
}

fn budget_error(builtin: &str, message: String, hint: &str) -> SafetyError {
    SafetyError {
        code: ErrorCode::BudgetExceeded,
        message: format!("{}: {}", builtin, message),
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    }
}

/// Account for one guarded operation against the resource governors and return
/// `E_BUDGET_EXCEEDED` if a configured limit is exceeded. No-op outside agent
/// mode or when no limit is set. Counts the attempt (increments before checking)
/// so the envelope bounds total attempts, not just successes.
fn governor_admit(effect: Effect, builtin: &str) -> Result<(), SafetyError> {
    if current_mode() != Mode::Agent {
        return Ok(());
    }
    let mut g = match GOVERNOR.lock() {
        Ok(g) => g,
        Err(_) => return Ok(()),
    };

    // Wall-clock: start the envelope lazily on the first guarded op.
    let now = std::time::Instant::now();
    let start = *g.start.get_or_insert(now);
    if let Some(limit_ms) = env_u64("IRONSHELL_TIMEOUT_MS") {
        let elapsed = now.duration_since(start).as_millis() as u64;
        if elapsed > limit_ms {
            return Err(budget_error(
                builtin,
                format!("wall-clock budget exhausted ({}ms > {}ms)", elapsed, limit_ms),
                "the run exceeded IRONSHELL_TIMEOUT_MS; whoever launched the agent raises the limit, or a new process starts the clock",
            ));
        }
    }

    g.total += 1;
    if let Some(max) = env_u64("IRONSHELL_MAX_OPS") {
        if g.total > max {
            return Err(budget_error(
                builtin,
                format!("operation budget exhausted ({} > {})", g.total, max),
                "whoever launched the agent raises IRONSHELL_MAX_OPS before launch",
            ));
        }
    }
    match effect {
        Effect::WriteLocal | Effect::Destructive => {
            g.files += 1;
            if let Some(max) = env_u64("IRONSHELL_MAX_FILES") {
                if g.files > max {
                    return Err(budget_error(
                        builtin,
                        format!("file-operation budget exhausted ({} > {})", g.files, max),
                        "whoever launched the agent raises IRONSHELL_MAX_FILES before launch",
                    ));
                }
            }
        }
        Effect::Process | Effect::Exec => {
            g.procs += 1;
            if let Some(max) = env_u64("IRONSHELL_MAX_PROCS") {
                if g.procs > max {
                    return Err(budget_error(
                        builtin,
                        format!("process budget exhausted ({} > {})", g.procs, max),
                        "whoever launched the agent raises IRONSHELL_MAX_PROCS before launch",
                    ));
                }
            }
        }
        Effect::Network => {
            g.net += 1;
            if let Some(max) = env_u64("IRONSHELL_MAX_NET") {
                if g.net > max {
                    return Err(budget_error(
                        builtin,
                        format!("network-egress budget exhausted ({} > {})", g.net, max),
                        "whoever launched the agent raises IRONSHELL_MAX_NET before launch",
                    ));
                }
            }
        }
        _ => {}
    }
    Ok(())
}

/// Reset the resource-governor counters and wall-clock start (e.g. at a session
/// boundary or after a deliberate raise of the limits).
pub fn governor_reset() {
    if let Ok(mut g) = GOVERNOR.lock() {
        *g = GovernorState::default();
    }
}

/// Snapshot of the governors for introspection: current counts, the configured
/// limits (null = unlimited), and elapsed wall-clock ms. Lets an agent watch its
/// envelope burn down before it hits a wall.
pub fn governor_snapshot() -> Json {
    let g = match GOVERNOR.lock() {
        Ok(g) => g,
        Err(e) => e.into_inner(),
    };
    let elapsed_ms = g
        .start
        .map(|s| std::time::Instant::now().duration_since(s).as_millis() as u64)
        .unwrap_or(0);
    let lim = |n: &str| env_u64(n).map(|v| json!(v)).unwrap_or(Json::Null);
    json!({
        "active": current_mode() == Mode::Agent,
        "elapsed_ms": elapsed_ms,
        "used": { "ops": g.total, "files": g.files, "procs": g.procs, "net": g.net },
        "limits": {
            "max_ops": lim("IRONSHELL_MAX_OPS"),
            "max_files": lim("IRONSHELL_MAX_FILES"),
            "max_procs": lim("IRONSHELL_MAX_PROCS"),
            "max_net": lim("IRONSHELL_MAX_NET"),
            "timeout_ms": lim("IRONSHELL_TIMEOUT_MS"),
        }
    })
}

// ════════════════════════════════════════════════════════════════════════
// The guard (§7) — the one entry point effecting builtins call.
// ════════════════════════════════════════════════════════════════════════

/// Context describing a single effecting call.
pub struct GuardCtx<'a> {
    /// Builtin name, e.g. `"rm"`.
    pub builtin: &'a str,
    /// Effect class of this call.
    pub effect: Effect,
    /// Verb for the approval descriptor, e.g. `"delete"`, `"kill"`, `"exec"`.
    pub what: &'a str,
    /// Concrete targets (paths, pids, command) for jail + descriptor + audit.
    pub targets: Vec<String>,
    /// Estimated blast radius, e.g. `{"files": 412, "bytes": 1200000000}`.
    pub blast_radius: Json,
    /// Whether the action can be undone.
    pub reversible: bool,
    /// Whether `targets` are local filesystem paths subject to the workspace
    /// jail. True for `rm`/file ops; false for non-path targets like database
    /// rows, container names, or shell commands.
    pub fs_paths: bool,
}

impl<'a> GuardCtx<'a> {
    /// Convenience constructor for the common single-target case. `fs_paths`
    /// defaults to whether the effect is a filesystem effect.
    pub fn new(builtin: &'a str, effect: Effect, what: &'a str, target: impl Into<String>) -> Self {
        Self {
            builtin,
            effect,
            what,
            targets: vec![target.into()],
            blast_radius: Json::Null,
            reversible: false,
            fs_paths: effect.is_filesystem(),
        }
    }
}

/// Gate a builtin that runs a caller-supplied program or shell command.
///
/// Until 2026-08-04 `sh` was the only builtin that gated on [`Effect::Exec`],
/// which made the exec control a denylist of exactly one *name* rather than of
/// the *capability*. `timeout`, `xargs`, `proc.spawn`, `nohup`, `strace`,
/// `ltrace` and the `perf` builtins all hand a caller-controlled string to a
/// shell, so in agent mode — with `sh` disabled outright, the intended hardened
/// configuration — an agent could still run any command it liked, with no
/// approval prompt and no `exec`-classified audit entry.
///
/// Every builtin whose argument *is* a command must route through here, so that
/// adding another such builtin cannot silently reopen the hole.
pub fn guard_exec(builtin: &str, command: impl Into<String>) -> Result<(), SafetyError> {
    let command = command.into();
    guard(GuardCtx {
        builtin,
        effect: Effect::Exec,
        what: "exec",
        targets: vec![command.clone()],
        blast_radius: serde_json::json!({ "command": command }),
        reversible: false,
        // A command string is not a path, so it must not be jailed as one.
        fs_paths: false,
    })
}

/// Reject caller-supplied *positional* arguments that a tool would parse as
/// options (CWE-88).
///
/// Fixing the program name is not enough when the program can be told to run a
/// command by a flag. `tar -cvf out.tar <files>` with a "file" named
/// `--use-compress-program=sh -c '…'` executes it; Info-ZIP's `-TT` sets the
/// command used to test an archive. Both turn a file list into arbitrary
/// execution while the builtin still looks like a pure archiving call.
///
/// `--` would stop option parsing in `tar` and `zip`, and is passed as well
/// where those are invoked, but support is not universal and getting it wrong is
/// silent. Refusing the argument outright is the check that does not depend on
/// the tool's parser. A path that genuinely starts with `-` is reachable as
/// `./-name`, which the hint says.
pub fn reject_option_like(builtin: &str, values: &[String]) -> anyhow::Result<()> {
    for v in values {
        if v.starts_with('-') {
            return Err(anyhow::Error::new(SafetyError {
                code: ErrorCode::BadArg,
                message: format!(
                    "{}: refusing an option-like path argument: {:?}",
                    builtin, v
                ),
                builtin: builtin.to_string(),
                hint: "this position is a file path, and a leading '-' would be parsed as \
                       an option by the underlying tool — several of which can be made to \
                       run a command that way; pass './-name' if the file really is named \
                       that"
                    .to_string(),
                approval: None,
                did_you_mean: Vec::new(),
                expected: String::new(),
                got: String::new(),
                extra: serde_json::Map::new(),
            }));
        }
    }
    Ok(())
}

/// Reject a URL that a desktop launcher would treat as something other than a
/// web address.
///
/// This is the *second* layer under `web_open_url`, and it is worth being clear
/// about which layer does what, because the obvious defence here does not work.
///
/// The first layer is structural: the Windows branch used to run
/// `cmd /C start <url>`, and `cmd` splits its command line on `&`. A URL of
/// `http://example.com&echo.>marker.txt` therefore ran `echo` — demonstrated,
/// not theorised. The tempting fix is to refuse `&`, and it is the wrong one:
/// `&` is the query-string separator, so it is *legal data* in the very values
/// this builtin exists to accept. A blocklist that refuses it breaks
/// `?a=1&b=2`; one that allows it leaves the hole open. The only fix that can be
/// both correct and complete is to stop handing the value to a shell at all,
/// which is what the call site now does.
///
/// What is left for this function is the part a shell-free launcher does not
/// solve:
///
/// * **Scheme.** `ShellExecute` and `xdg-open` dispatch on the scheme, so
///   `ms-msdt:`, `search-ms:` and friends reach registered handlers that are not
///   browsers — the Follina shape. An allowlist is right here because the set of
///   things a *web*-opening builtin should reach is small and closed.
/// * **Control characters.** A newline is a command separator in every shell,
///   so it must not survive into any future call site that has one.
/// * **A leading `-`.** The macOS and Linux branches pass the value positionally
///   to `open` and `xdg-open`; `open -a <app>` launches an arbitrary
///   application. This is the same defect [`reject_option_like`] exists for, and
///   the scheme check would catch it too — it is stated separately so the error
///   message says which problem it is.
pub fn reject_unsafe_url(builtin: &str, url: &str) -> anyhow::Result<()> {
    /// Schemes a URL-opening builtin may hand to the desktop's handler.
    ///
    /// This list may only shrink. Every addition widens the set of registered
    /// protocol handlers an agent can reach with a caller-controlled argument.
    const ALLOWED_SCHEMES: &[&str] = &["http", "https"];

    let err = |message: String, hint: &str| {
        anyhow::Error::new(SafetyError {
            code: ErrorCode::BadArg,
            message,
            builtin: builtin.to_string(),
            hint: hint.to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: format!(
                "a URL with one of these schemes: {}",
                ALLOWED_SCHEMES.join(", ")
            ),
            got: url.to_string(),
            extra: serde_json::Map::new(),
        })
    };

    if let Some(c) = url.chars().find(|c| c.is_ascii_control()) {
        return Err(err(
            format!(
                "{builtin}: refusing a URL containing a control character ({:#04x})",
                c as u32
            ),
            "a newline or carriage return separates commands in every shell; a URL \
             cannot legitimately contain one",
        ));
    }
    if url.starts_with('-') {
        return Err(err(
            format!("{builtin}: refusing an option-like URL: {url:?}"),
            "this position is passed positionally to `open`/`xdg-open`, and a leading \
             '-' is parsed as an option — `open -a <app>` launches an arbitrary \
             application",
        ));
    }
    let scheme = match url.split_once(':') {
        Some((s, _)) if !s.is_empty() => s.to_ascii_lowercase(),
        _ => {
            return Err(err(
                format!("{builtin}: refusing a URL with no scheme: {url:?}"),
                "give an absolute URL such as 'https://example.com'; a bare path is \
                 dispatched by the desktop handler rather than opened as a web page",
            ))
        }
    };
    if !ALLOWED_SCHEMES.contains(&scheme.as_str()) {
        return Err(err(
            format!("{builtin}: refusing the URL scheme {scheme:?}"),
            "the desktop handler dispatches on the scheme, so a non-web scheme reaches \
             whatever program is registered for it rather than a browser",
        ));
    }
    Ok(())
}

/// Quote a value for interpolation into a **single-quoted** PowerShell string
/// literal (CWE-78).
///
/// Many Windows builtins build a command with `format!("Start-Service '{}'",
/// name)`. In a single-quoted PowerShell literal the only metacharacter is `'`
/// itself, so a value containing one closes the string and everything after it
/// is executed. Verified, not assumed: a service name of
/// `x'; New-Item -ItemType File -Path '…' -Force; '` created the file.
///
/// PowerShell escapes a quote inside a single-quoted string by doubling it, so
/// that is the whole transformation. The returned string **includes** the
/// surrounding quotes — callers interpolate it with `{}`, not `'{}'`, which
/// makes a missed call site visible as a syntax error rather than silently
/// unquoted.
///
/// This is for single-quoted context only. A double-quoted PowerShell string
/// also expands `$` and backtick, and must not use this.
pub fn ps_quote(value: &str) -> PsLiteral {
    // PowerShell ends a single-quoted string at any of five quote characters,
    // not only ASCII `'`: U+2018, U+2019, U+201A and U+201B close it too. With
    // only `'` doubled, a service name containing `’` closed the literal and
    // the rest ran as a command, under a ReadLocal builtin that asks for no
    // approval. Each is escaped the same way, by doubling.
    let mut out = String::with_capacity(value.len() + 2);
    out.push('\'');
    for c in value.chars() {
        if PS_SINGLE_QUOTES.contains(&c) {
            out.push(c);
        }
        out.push(c);
    }
    out.push('\'');
    PsLiteral(out)
}

/// The characters PowerShell accepts as a single-quote delimiter.
const PS_SINGLE_QUOTES: [char; 5] = ['\'', '\u{2018}', '\u{2019}', '\u{201A}', '\u{201B}'];

/// A PowerShell string literal, quoted and escaped, that only [`ps_quote`] can
/// build.
///
/// The point is that the *type* records that quoting happened. A `String` in a
/// command builder proves nothing — findings 10a, 10c and 10d were all raw
/// strings reaching a `format!` that looked fine on review, three times. A value
/// of this type cannot be constructed except by going through the escaper,
/// because the field is private to this module.
///
/// It renders through `Display`, so `format!("Start-Service {}", ps_quote(&n))`
/// works unchanged. It deliberately does **not** implement `Deref<Target=str>`
/// or `From<String>`: either would let an unescaped value be substituted for an
/// escaped one, which is the whole thing this prevents.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PsLiteral(String);

impl std::fmt::Display for PsLiteral {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// Build a PowerShell command string, accepting only already-escaped values.
///
/// `format!` is the hole the newtypes alone cannot close: it accepts anything
/// implementing `Display`, so `format!("Start-Service '{}'", name)` with a bare
/// `String` still compiles. That is the exact shape of findings 10a, 10c and
/// 10d, and it got past manual review three times.
///
/// This macro binds every argument to `&PsLiteral` before formatting, so a
/// `String` is a *compile* error rather than an injection:
///
/// ```
/// use iron_shell::{ps_script, safety::ps_quote};
/// let name = "my service";
/// assert_eq!(
///     ps_script!("Start-Service {}", ps_quote(name)),
///     "Start-Service 'my service'"
/// );
/// ```
///
/// Note the template uses `{}`, not `'{}'` — the literal carries its own
/// quotes, so adding more would nest them.
#[macro_export]
macro_rules! ps_script {
    ($fmt:literal $(, $arg:expr)* $(,)?) => {{
        // Type-check every argument. A `String` or a borrowed `&str` fails
        // here, naming the argument, before it can reach a shell.
        $($crate::safety::ps_arg(&$arg);)*
        format!($fmt $(, $arg)*)
    }};
}

/// Argument types [`ps_script!`] will accept.
///
/// Deliberately **not** implemented for `String` or for a non-`'static` `&str`:
/// those are how caller data arrives, and letting them through is the defect
/// this whole mechanism exists to prevent. To pass one, quote it with
/// [`ps_quote`] first.
///
/// The three things that *are* safe:
///
/// - [`PsLiteral`] — escaped by construction.
/// - Integers — no PowerShell metacharacter has a numeric representation.
/// - `&'static str` — a compile-time literal, so it cannot be caller data. This
///   covers the common `match algo { "sha256" => "SHA256", … }` shape, where the
///   value is one of a fixed set chosen in-tree. (`String::leak` could forge a
///   `&'static str`, but that is a deliberate act, not an accident.)
pub trait PsArg {}

impl PsArg for PsLiteral {}
impl PsArg for &'static str {}
macro_rules! impl_ps_arg_for_numbers {
    ($($t:ty),*) => { $(impl PsArg for $t {})* };
}
impl_ps_arg_for_numbers!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);

/// Type-check a [`ps_script!`] argument. Called by the macro; not useful alone.
#[doc(hidden)]
pub fn ps_arg<T: PsArg + ?Sized>(_: &T) {}

/// Validate a value that must be interpolated **unquoted** — a size or a port.
///
/// Some PowerShell parameters cannot take a quoted string: `-MemoryStartupBytes
/// '4GB'` is not the same as `-MemoryStartupBytes 4GB`, because `4GB` is a
/// numeric literal. So [`ps_quote`] is not available for them, and they were
/// interpolated bare — which the source lint cannot flag either, because it
/// looks for *quoted* placeholders.
///
/// Found by [`ps_script!`]'s type check, which is the one layer that sees an
/// unquoted interpolation: `vm.create(name, memory, disk)` and
/// `firewall.allow(port)` both put caller strings straight into a command.
/// (Both of those builtins were deleted in the 2026-08-26 dead-code pass — they
/// were never registered. The helper stays because the shape recurs, and the
/// history is kept so the next reader knows what it was written against.)
///
/// The check is a whitelist — digits, at most one decimal point, and an
/// optional size suffix — so nothing that could carry a metacharacter survives.
/// The returned [`PsLiteral`] carries no quotes; the type here means "checked
/// safe to interpolate", which for this shape is validation rather than quoting.
pub fn ps_bare_number(builtin: &str, value: &str) -> anyhow::Result<PsLiteral> {
    let v = value.trim();
    let (digits, suffix) = match v.find(|c: char| c.is_ascii_alphabetic()) {
        Some(i) => (&v[..i], &v[i..]),
        None => (v, ""),
    };

    let digits_ok = !digits.is_empty()
        && digits.chars().all(|c| c.is_ascii_digit() || c == '.')
        && digits.matches('.').count() <= 1;
    let suffix_ok = matches!(
        suffix.to_ascii_uppercase().as_str(),
        "" | "KB" | "MB" | "GB" | "TB" | "PB"
    );

    if digits_ok && suffix_ok {
        return Ok(PsLiteral(v.to_string()));
    }
    Err(anyhow::Error::new(SafetyError {
        code: ErrorCode::BadArg,
        message: format!("{}: expected a number or size, got {:?}", builtin, value),
        builtin: builtin.to_string(),
        hint: "this value is interpolated into a command unquoted, so it is \
               restricted to digits with an optional KB/MB/GB/TB/PB suffix"
            .to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    }))
}

/// Join already-escaped literals into one, for the `-Path a,b,c` shape.
///
/// Exists so that building a list does not require dropping to `String` and
/// thereby losing the type that says "this was escaped".
pub fn ps_join(values: impl IntoIterator<Item = PsLiteral>, sep: &str) -> PsLiteral {
    PsLiteral(
        values
            .into_iter()
            .map(|v| v.0)
            .collect::<Vec<_>>()
            .join(sep),
    )
}

/// Type-check an [`applescript!`] argument. Called by the macro.
#[doc(hidden)]
pub fn applescript_arg<T: AppleScriptArg + ?Sized>(_: &T) {}

/// Argument types [`applescript!`] accepts. See [`PsArg`].
pub trait AppleScriptArg {}
impl AppleScriptArg for AppleScriptLiteral {}
impl AppleScriptArg for &'static str {}

/// The AppleScript counterpart to [`ps_script!`].
#[macro_export]
macro_rules! applescript {
    ($fmt:literal $(, $arg:expr)* $(,)?) => {{
        $($crate::safety::applescript_arg(&$arg);)*
        format!($fmt $(, $arg)*)
    }};
}

/// An AppleScript string literal, quoted and escaped, that only
/// [`applescript_quote`] can build. See [`PsLiteral`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppleScriptLiteral(String);

impl std::fmt::Display for AppleScriptLiteral {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// Quote a value for interpolation into an AppleScript string literal
/// (CWE-78, macOS).
///
/// The `osascript` counterpart to [`ps_quote`]. AppleScript string literals are
/// double-quoted and escape with a backslash, so an unescaped `"` closes the
/// literal — after which `" & (do shell script "…") & "` runs a command.
///
/// Backslash is escaped first, or escaping the quote would itself be undone.
/// As with `ps_quote`, the surrounding quotes are included so a missed call site
/// is a syntax error rather than a silently unquoted value.
pub fn applescript_quote(value: &str) -> AppleScriptLiteral {
    AppleScriptLiteral(format!(
        "\"{}\"",
        value.replace('\\', "\\\\").replace('"', "\\\"")
    ))
}

/// Reject a sqlite3 CLI *dot-command* where SQL is expected (CWE-77).
///
/// `sqlite3 <db> "<sql>"` accepts the CLI's own dot-commands in the SQL
/// position, and two of them run programs: `.system` and `.shell`. Verified —
/// `sqlite3 db ".system cmd /c echo … > file"` created the file. That turns
/// `db.sqlite_query` from "run a query" into "run anything", with no
/// `Effect::Exec` gate in front of it.
///
/// Dot-commands are a feature of the `sqlite3` shell, not of SQL, so refusing
/// them costs a caller nothing that SQL can express. The check is on the first
/// non-whitespace character: SQL statements never begin with `.`.
/// Render a value as a SQL string literal, safe to interpolate.
///
/// The sqlite builtins shell out to the `sqlite3` CLI, so there is no bound
/// parameter to use -- the SQL is a string by the time it leaves this process.
/// That made every `format!("... WHERE key = '{}'", key)` an injection point,
/// and not theoretically:
///
/// ```text
/// db_kv_get(db, "x' OR '1'='1")            -> returned another key's value
/// db_kv_delete(db, "z'; DELETE FROM kv; --") -> emptied the table (2 rows -> 0)
/// ```
///
/// SQLite escapes a quote inside a literal by doubling it, so `'` becomes `''`
/// and the value can no longer terminate its own literal. An interior NUL is
/// refused rather than escaped: the CLI takes its SQL as a C string, so a NUL
/// truncates the statement, and silently storing a shortened key would be its
/// own bug.
pub fn sql_literal(builtin: &str, value: &str) -> anyhow::Result<String> {
    if value.contains('\0') {
        return Err(anyhow::Error::new(SafetyError {
            code: ErrorCode::BadArg,
            message: format!("{builtin}: NUL byte in a SQL value"),
            builtin: builtin.to_string(),
            hint: "sqlite3 reads its SQL as a C string, so a NUL would silently truncate the statement; remove it"
                .to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: String::new(),
            got: String::new(),
            extra: serde_json::Map::new(),
        }));
    }
    Ok(format!("'{}'", value.replace('\'', "''")))
}

/// Quote a table or column name for interpolation: `"name"` with any embedded
/// `"` doubled, which is how SQL writes an identifier that is a reserved word or
/// holds spaces and quotes, and which cannot close the statement. Any name that
/// is non-empty and has no control character (NUL and newline included) is
/// accepted; anything else is refused naming what is allowed. The result is
/// already quoted: do not wrap it again.
pub fn sql_identifier(builtin: &str, name: &str) -> anyhow::Result<String> {
    let ok = !name.is_empty() && !name.chars().any(|c| c.is_control());
    if !ok {
        return Err(anyhow::Error::new(SafetyError {
            code: ErrorCode::BadArg,
            message: format!("{builtin}: {name:?} is not a valid table or column name: a name must be non-empty and hold no control characters"),
            builtin: builtin.to_string(),
            hint: "identifiers are interpolated into SQL and cannot be quoted as values; use any non-empty name without control characters (NUL, newline, tab and the like)"
                .to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: "a non-empty name without control characters".to_string(),
            got: name.to_string(),
            extra: serde_json::Map::new(),
        }));
    }
    Ok(format!("\"{}\"", name.replace('"', "\"\"")))
}

/// Validate a column *type* clause for `CREATE TABLE` — the last unvalidated
/// interpolation in the SQL family.
///
/// [`sql_identifier`] covers the name half of `"<name> <type>"`. The type half
/// was left as written, with a note saying that constraining it "means inventing
/// a grammar for SQL type expressions, which is a deliberate decision rather
/// than a drive-by one". This is that decision, taken rather than carried
/// forward again.
///
/// The grammar is a token allowlist, not a parser, because the value being
/// described is small and closed: a type name, an optional size, and a handful
/// of column constraints. Each whitespace-separated token must be one of
///
/// * a type or constraint keyword from the lists below, optionally carrying a
///   `(N)` or `(N,M)` size — `VARCHAR(255)`, `DECIMAL(10,2)`;
/// * a numeric literal, for `DEFAULT 0`;
/// * a single-quoted literal containing no quote of its own, for `DEFAULT ''`.
///
/// Anything else is refused. That is deliberately narrower than SQLite accepts —
/// SQLite's type affinity rules will take almost any word — and it refuses
/// `CHECK(…)` and `REFERENCES t(c)` along with the injections, because both
/// carry a parenthesised expression this cannot judge. A caller who genuinely
/// needs those has the raw column-definition branch, which is SQL by contract
/// and says so.
///
/// **Why now, for a builtin nothing can reach.** `db_sqlite_create_table` is in
/// the 168 unregistered implementations (§5 item 3), so this fixes nothing
/// exploitable today. It removes a *precondition*: registering it was previously
/// blocked on a security decision nobody had made, which is the kind of debt
/// that gets paid by whoever is registering builtins in a hurry.
pub fn sql_column_type(builtin: &str, spec: &str) -> anyhow::Result<String> {
    /// Type names accepted before the optional size. Covers the SQLite affinity
    /// families and the common spellings borrowed from other dialects.
    const TYPES: &[&str] = &[
        "INT",
        "INTEGER",
        "TINYINT",
        "SMALLINT",
        "MEDIUMINT",
        "BIGINT",
        "UNSIGNED",
        "BIG",
        "INT2",
        "INT8",
        "CHARACTER",
        "VARCHAR",
        "VARYING",
        "NCHAR",
        "NATIVE",
        "NVARCHAR",
        "TEXT",
        "CLOB",
        "BLOB",
        "REAL",
        "DOUBLE",
        "PRECISION",
        "FLOAT",
        "NUMERIC",
        "DECIMAL",
        "BOOLEAN",
        "DATE",
        "DATETIME",
        "TIMESTAMP",
    ];
    /// Column constraints, and the bare words that may follow `DEFAULT` or
    /// `COLLATE`. This list may only shrink.
    const KEYWORDS: &[&str] = &[
        "NOT",
        "NULL",
        "PRIMARY",
        "KEY",
        "AUTOINCREMENT",
        "UNIQUE",
        "DEFAULT",
        "COLLATE",
        "NOCASE",
        "BINARY",
        "RTRIM",
        "ASC",
        "DESC",
        "CURRENT_TIMESTAMP",
        "CURRENT_DATE",
        "CURRENT_TIME",
        "TRUE",
        "FALSE",
    ];

    let reject = |token: &str| {
        anyhow::Error::new(SafetyError {
            code: ErrorCode::BadArg,
            message: format!("{builtin}: {token:?} is not a valid column type or constraint"),
            builtin: builtin.to_string(),
            hint: "this is interpolated into a CREATE TABLE statement, which sqlite3 \
                   executes as written — use a type name with an optional size and \
                   constraints such as 'NOT NULL' or 'PRIMARY KEY'; for a CHECK or \
                   REFERENCES clause, pass the whole column definition as a string \
                   instead of a record"
                .to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: "a column type such as 'TEXT', 'VARCHAR(255) NOT NULL'".to_string(),
            got: spec.to_string(),
            extra: serde_json::Map::new(),
        })
    };

    /// A token stripped of a trailing `(N)` or `(N,M)`, or `None` if the
    /// parentheses are anything other than that.
    fn without_size(token: &str) -> Option<&str> {
        let Some(open) = token.find('(') else {
            return Some(token);
        };
        let rest = &token[open + 1..];
        let inner = rest.strip_suffix(')')?;
        let digits_ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit());
        let sized = match inner.split_once(',') {
            Some((a, b)) => digits_ok(a.trim()) && digits_ok(b.trim()),
            None => digits_ok(inner.trim()),
        };
        sized.then(|| &token[..open])
    }

    fn is_number(token: &str) -> bool {
        let t = token.strip_prefix('-').unwrap_or(token);
        match t.split_once('.') {
            Some((a, b)) => {
                !a.is_empty()
                    && !b.is_empty()
                    && a.chars().all(|c| c.is_ascii_digit())
                    && b.chars().all(|c| c.is_ascii_digit())
            }
            None => !t.is_empty() && t.chars().all(|c| c.is_ascii_digit()),
        }
    }

    /// `'literal'` with no embedded quote, so it cannot end early and start
    /// something else.
    fn is_plain_string_literal(token: &str) -> bool {
        token.len() >= 2
            && token.starts_with('\'')
            && token.ends_with('\'')
            && !token[1..token.len() - 1].contains('\'')
    }

    let spec = spec.trim();
    if spec.is_empty() {
        return Err(reject(""));
    }

    // Whitespace inside a size is not a token boundary. `DECIMAL(10, 2)` is
    // ordinary SQL and the first version of this split it into `DECIMAL(10,` and
    // `2)`, refusing both — the check has to accept what people actually write
    // or it is a ban wearing a validator's coat. Collapsing spaces *inside*
    // parentheses is safe because the parenthesised part is separately required
    // to be digits and at most one comma.
    let mut flattened = String::with_capacity(spec.len());
    let mut depth = 0i32;
    for c in spec.chars() {
        match c {
            '(' => depth += 1,
            ')' => depth -= 1,
            _ => {}
        }
        if depth > 0 && c.is_whitespace() {
            continue;
        }
        flattened.push(c);
    }

    for token in flattened.split_whitespace() {
        if is_number(token) || is_plain_string_literal(token) {
            continue;
        }
        let Some(word) = without_size(token) else {
            return Err(reject(token));
        };
        let upper = word.to_ascii_uppercase();
        if TYPES.contains(&upper.as_str()) || KEYWORDS.contains(&upper.as_str()) {
            continue;
        }
        return Err(reject(token));
    }
    Ok(spec.to_string())
}

pub fn reject_sqlite_dot_command(builtin: &str, sql: &str) -> anyhow::Result<()> {
    if sql.trim_start().starts_with('.') {
        return Err(anyhow::Error::new(SafetyError {
            code: ErrorCode::BadArg,
            message: format!(
                "{}: refusing a sqlite3 dot-command where SQL is expected",
                builtin
            ),
            builtin: builtin.to_string(),
            hint: "`.system` and `.shell` run programs, so dot-commands are not \
                   accepted here; pass a SQL statement"
                .to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: String::new(),
            got: String::new(),
            extra: serde_json::Map::new(),
        }));
    }
    Ok(())
}

/// Refuse a `;` that would end a statement, in a fragment the caller wrote and
/// that is spliced into a statement of the builtin's own: a WHERE clause, or the
/// raw text of a column definition. sqlite3 runs every `;`-separated statement
/// it is handed, so a fragment carrying one can run another.
///
/// A `;` inside a string literal, a quoted identifier or a comment cannot end a
/// statement, and is accepted. The scanner follows SQLite's lexical rules:
/// `'...'` and `"..."` with a doubled quote as the escape (the close and the
/// reopen leave the scanner in the same state), `` `...` `` and `[...]` as
/// quoted identifiers, `--` to the end of the line, and `/* ... */`. A quote or
/// comment left open runs to the end of the fragment, so a `;` after it is
/// inside, which is what SQLite makes of it too.
pub fn reject_sql_batch(builtin: &str, fragment: &str) -> anyhow::Result<()> {
    #[derive(Clone, Copy, PartialEq)]
    enum Lex {
        Code,
        Single,
        Double,
        Backtick,
        Bracket,
        Line,
        Block,
    }
    let bytes = fragment.as_bytes();
    let mut state = Lex::Code;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        let next = bytes.get(i + 1).copied();
        match state {
            Lex::Code => match b {
                b'\'' => state = Lex::Single,
                b'"' => state = Lex::Double,
                b'`' => state = Lex::Backtick,
                b'[' => state = Lex::Bracket,
                b'-' if next == Some(b'-') => {
                    state = Lex::Line;
                    i += 1;
                }
                b'/' if next == Some(b'*') => {
                    state = Lex::Block;
                    i += 1;
                }
                b';' => {
                    return Err(bad_arg(
                        builtin,
                        "one SQL statement: no `;` outside a string literal, quoted identifier or comment",
                        "a `;` that would begin a second statement",
                    ));
                }
                _ => {}
            },
            Lex::Single if b == b'\'' => state = Lex::Code,
            Lex::Double if b == b'"' => state = Lex::Code,
            Lex::Backtick if b == b'`' => state = Lex::Code,
            Lex::Bracket if b == b']' => state = Lex::Code,
            Lex::Line if b == b'\n' => state = Lex::Code,
            Lex::Block if b == b'*' && next == Some(b'/') => {
                state = Lex::Code;
                i += 1;
            }
            _ => {}
        }
        i += 1;
    }
    Ok(())
}

/// Gate an effecting call. Returns `Ok(())` if the call may proceed (and records
/// an audit entry), or a [`SafetyError`] with a stable code, an actionable hint,
/// and — for approvable actions — a bound approval token.
/// The configured egress allowlist, or `None` when `IRONSHELL_NET_ALLOW` is unset
/// or blank. `*` allows every host.
pub fn net_allowlist() -> Option<String> {
    std::env::var("IRONSHELL_NET_ALLOW")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// The refusal for a call that reaches past the egress allowlist. Shared by
/// [`guard`] (for `Effect::Network` builtins) and by [`check_egress`] and
/// [`check_egress_unknown`] (for `Exec`-class builtins that go to the network
/// through a program), so every network refusal has one shape and one audit entry.
fn egress_denied(
    builtin: &str,
    effect: Effect,
    resource: &str,
    allow: &str,
    detail: String,
) -> SafetyError {
    let _ = audit(
        builtin,
        effect,
        "deny_egress",
        resource,
        json!({ "allow": allow, "detail": detail }),
    );
    SafetyError {
        code: ErrorCode::PolicyDeny,
        message: format!("{}: egress denied: {}", builtin, detail),
        builtin: builtin.to_string(),
        hint: format!(
            "IRONSHELL_NET_ALLOW permits only: {allow}; name an allowed host, or ask the operator to add this one"
        ),
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("a destination in {allow}"),
        got: detail,
        extra: serde_json::Map::new(),
    }
}

/// `Network` builtins whose string arguments are not hosts, so the dispatcher's
/// egress step must not judge them. Each one makes the destination-unknown check
/// itself (see [`check_egress_unknown`]), the way the package fetches do. Unlike
/// `SELF_GUARDED` this skips only the egress step: the governor, audit, and
/// approval checks still run centrally.
/// The scp builtins are here because the central step would judge the string the
/// caller wrote; their bodies judge the host ssh config resolves it to.
/// The git remote commands are here because their remote is read from
/// `.git/config` by their body ([`check_git_remote_egress`]), and skopeo because
/// its local transports (`dir:`, `oci:`, ...) are not network and its body judges
/// the `docker://` references it names.
const EGRESS_JUDGED_BY_BODY: &[&str] = &[
    "pkg_changelog",
    "scp_upload",
    "scp_download",
    "git_fetch",
    "git_pull",
    "git_push",
    "skopeo_copy",
    "skopeo_inspect",
    // Their bodies refuse every call under an allowlist (the host is in configuration),
    // so the central step's reading of a dotted argument as a host is not wanted.
    "trivy_scan",
    "trivy_image",
    "gh_repo",
    "gh_repo_cmd",
];

/// Egress allowlist for an `Exec`-class builtin whose destination is named in its
/// arguments: `targets` are judged by [`egress_permitted`], exactly as a
/// `Network` builtin's targets are in [`guard`]. A no-op unless
/// `IRONSHELL_NET_ALLOW` is set and the policy is not permissive, so with no
/// allowlist nothing changes. Call it before spawning the program.
pub fn check_egress(builtin: &str, targets: &[String]) -> Result<(), SafetyError> {
    if policy_permissive() {
        return Ok(());
    }
    let Some(allow) = net_allowlist() else {
        return Ok(());
    };
    match egress_permitted(targets, &allow) {
        Ok(()) => Ok(()),
        Err(detail) => Err(egress_denied(
            builtin,
            Effect::Exec,
            &targets.join(", "),
            &allow,
            detail,
        )),
    }
}

/// Fail closed for an `Exec`-class builtin whose destination cannot be read from
/// its arguments (a registry named by a config file, a chart repository, an
/// inventory). When `IRONSHELL_NET_ALLOW` is set and the policy is not
/// permissive, the call is refused with `reason` as its detail. Without an
/// allowlist this does nothing.
pub fn check_egress_unknown(builtin: &str, reason: &str) -> Result<(), SafetyError> {
    if policy_permissive() {
        return Ok(());
    }
    let Some(allow) = net_allowlist() else {
        return Ok(());
    };
    // `*` allows every destination, including one that cannot be read.
    if allow.split([';', ',']).any(|e| e.trim() == "*") {
        return Ok(());
    }
    Err(egress_denied(
        builtin,
        Effect::Exec,
        "",
        &allow,
        format!("{reason}; an allowlist is set, so the call is refused"),
    ))
}

/// Which container config file can name a registry mirror, and how it is read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MirrorConfig {
    /// Docker's `daemon.json`: `registry-mirrors`.
    DaemonJson,
    /// containers' `registries.conf` (podman, buildah): `[[registry.mirror]]` and
    /// `unqualified-search-registries`.
    RegistriesConf,
}

/// The most `registries.conf.d` drop-in files the mirror check reads, in all.
const MIRROR_DROPIN_MAX_FILES: usize = 64;

/// The value of `name` as a path, or `None` when it is unset or empty.
fn nonempty_path(
    var: &dyn Fn(&str) -> Option<std::ffi::OsString>,
    name: &str,
) -> Option<std::path::PathBuf> {
    var(name)
        .filter(|v| !v.is_empty())
        .map(std::path::PathBuf::from)
}

/// `HOME`, falling back to `USERPROFILE` as the ssh and git readers do.
fn home_dir(var: &dyn Fn(&str) -> Option<std::ffi::OsString>) -> Option<std::path::PathBuf> {
    nonempty_path(var, "HOME").or_else(|| nonempty_path(var, "USERPROFILE"))
}

/// The user config directories the container and rootless docker tools read:
/// `$XDG_CONFIG_HOME` when it is set and non-empty, and `$HOME/.config` as well.
/// Both are read, so a mirror in either one refuses. A directory named twice is
/// listed once.
fn user_config_dirs(var: &dyn Fn(&str) -> Option<std::ffi::OsString>) -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    if let Some(xdg) = nonempty_path(var, "XDG_CONFIG_HOME") {
        out.push(xdg);
    }
    if let Some(home_config) = home_dir(var).map(|h| h.join(".config")) {
        if !out.contains(&home_config) {
            out.push(home_config);
        }
    }
    out
}

/// The docker CLI's `config.json`: `$DOCKER_CONFIG` when set and non-empty, else
/// `$HOME/.docker`.
fn docker_config_json(
    var: &dyn Fn(&str) -> Option<std::ffi::OsString>,
) -> Option<std::path::PathBuf> {
    match nonempty_path(var, "DOCKER_CONFIG") {
        Some(dir) => Some(dir.join("config.json")),
        None => home_dir(var).map(|h| h.join(".docker").join("config.json")),
    }
}

/// Whether `name` is set and non-empty.
fn var_is_set(var: &dyn Fn(&str) -> Option<std::ffi::OsString>, name: &str) -> bool {
    var(name).is_some_and(|v| !v.is_empty())
}

/// The config files that can redirect the registry a pull reaches, with the
/// format each is read as, for `var` as the environment. Docker's daemon reads
/// `daemon.json` from `/etc/docker`, `%ProgramData%\docker\config`, `$HOME/.docker`
/// and, rootless, `docker/daemon.json` under `$XDG_CONFIG_HOME` and under
/// `$HOME/.config`. Containers read `registries.conf` from `/etc/containers` and
/// `containers/registries.conf` under the same two user directories; their drop-ins
/// are in [`container_dropin_dirs`]. An unset or empty variable names no location.
pub fn container_mirror_paths(
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Vec<(MirrorConfig, std::path::PathBuf)> {
    container_mirror_paths_at(&var, std::path::Path::new("/"))
}

/// [`container_mirror_paths`] with `system` as the root of the system directories.
/// `/` in use; a test passes a temp directory, so no real `/etc` path is named.
fn container_mirror_paths_at(
    var: &dyn Fn(&str) -> Option<std::ffi::OsString>,
    system: &std::path::Path,
) -> Vec<(MirrorConfig, std::path::PathBuf)> {
    let mut out = vec![(
        MirrorConfig::DaemonJson,
        system.join("etc").join("docker").join("daemon.json"),
    )];
    if let Some(pd) = nonempty_path(var, "ProgramData") {
        let path = pd.join("docker").join("config").join("daemon.json");
        out.push((MirrorConfig::DaemonJson, path));
    }
    out.push((
        MirrorConfig::RegistriesConf,
        system
            .join("etc")
            .join("containers")
            .join("registries.conf"),
    ));
    if let Some(h) = home_dir(var) {
        out.push((
            MirrorConfig::DaemonJson,
            h.join(".docker").join("daemon.json"),
        ));
    }
    for c in user_config_dirs(var) {
        out.push((
            MirrorConfig::RegistriesConf,
            c.join("containers").join("registries.conf"),
        ));
        out.push((
            MirrorConfig::DaemonJson,
            c.join("docker").join("daemon.json"),
        ));
    }
    out
}

/// The `registries.conf.d` drop-in directories podman and buildah read: every
/// `*.conf` in each is read as a registries.conf, in name order.
fn container_dropin_dirs(
    var: &dyn Fn(&str) -> Option<std::ffi::OsString>,
    system: &std::path::Path,
) -> Vec<std::path::PathBuf> {
    let mut out = vec![system
        .join("etc")
        .join("containers")
        .join("registries.conf.d")];
    for c in user_config_dirs(var) {
        out.push(c.join("containers").join("registries.conf.d"));
    }
    out
}

const MIRROR_UNREADABLE: &str =
    "a docker daemon.json or containers registries.conf cannot be read, so a registry mirror in it cannot be ruled out";
const MIRROR_UNPARSED: &str =
    "a docker daemon.json or containers registries.conf does not parse, so a registry mirror in it cannot be ruled out";
const MIRROR_NAMED: &str =
    "a docker daemon.json or containers registries.conf names a registry mirror or an unqualified search list, so the registry the pull reaches cannot be read";
const MIRROR_ENV: &str =
    "CONTAINERS_REGISTRIES_CONF names a registries.conf this check does not read, so a registry mirror in it cannot be ruled out";
const MIRROR_TOO_MANY: &str =
    "a containers registries.conf.d holds more drop-in files than the check reads, so a registry mirror in them cannot be ruled out";
const MIRROR_REMOTE_DOCKER: &str =
    "DOCKER_HOST or DOCKER_CONTEXT names a daemon whose config this check does not read, so a registry mirror in it cannot be ruled out";
const MIRROR_CONTEXT_DOCKER: &str =
    "the docker config.json names a current context, which selects a daemon whose config this check does not read, so a registry mirror in it cannot be ruled out";
const MIRROR_REMOTE_PODMAN: &str =
    "CONTAINER_HOST or CONTAINER_CONNECTION names an engine whose config this check does not read, so a registry mirror in it cannot be ruled out";

/// Whether a docker `daemon.json` names a mirror: `registry-mirrors` is a
/// non-empty list. Absent or `null` is no mirror. Anything else that does not
/// parse as a JSON object, or a `registry-mirrors` that is not a list, is `Err`.
pub fn daemon_json_mirrors(text: &str) -> Result<bool, &'static str> {
    let value: serde_json::Value = serde_json::from_str(text).map_err(|_| MIRROR_UNPARSED)?;
    let object = value.as_object().ok_or(MIRROR_UNPARSED)?;
    match object.get("registry-mirrors") {
        None | Some(serde_json::Value::Null) => Ok(false),
        Some(serde_json::Value::Array(list)) => Ok(!list.is_empty()),
        Some(_) => Err(MIRROR_UNPARSED),
    }
}

/// Whether a containers `registries.conf` can redirect a pull: a non-empty
/// `unqualified-search-registries` (or the v1 `[registries.search]` list), or a
/// `[[registry.mirror]]` table under any `[[registry]]`. Text that does not parse,
/// or a key of the wrong type, is `Err`.
pub fn registries_conf_redirects(text: &str) -> Result<bool, &'static str> {
    fn in_use(v: Option<&toml::Value>) -> Result<bool, &'static str> {
        match v {
            None => Ok(false),
            Some(toml::Value::Array(list)) => Ok(!list.is_empty()),
            Some(_) => Err(MIRROR_UNPARSED),
        }
    }
    let doc: toml::Table = text.parse().map_err(|_| MIRROR_UNPARSED)?;
    if in_use(doc.get("unqualified-search-registries"))? {
        return Ok(true);
    }
    let v1_search = doc
        .get("registries")
        .and_then(|r| r.get("search"))
        .and_then(|s| s.get("registries"));
    if in_use(v1_search)? {
        return Ok(true);
    }
    match doc.get("registry") {
        None => Ok(false),
        Some(toml::Value::Array(entries)) => {
            for entry in entries {
                let table = entry.as_table().ok_or(MIRROR_UNPARSED)?;
                match table.get("mirror") {
                    None => {}
                    Some(toml::Value::Array(list)) if list.is_empty() => {}
                    Some(_) => return Ok(true),
                }
            }
            Ok(false)
        }
        Some(_) => Err(MIRROR_UNPARSED),
    }
}

/// Reads each listed file that exists and returns the refusal reason if one can
/// redirect a registry. A missing file is no mirror. An unreadable file, one over
/// 1 MiB, one on a remote share (probing it would reach a host), or one that does
/// not parse refuses. The contents are never part of the reason.
fn mirror_refusal_in(paths: &[(MirrorConfig, std::path::PathBuf)]) -> Result<(), &'static str> {
    for (format, path) in paths {
        if names_a_remote_share(&path.to_string_lossy()) {
            return Err(MIRROR_UNREADABLE);
        }
        match path.try_exists() {
            Ok(false) => continue,
            Ok(true) => {}
            Err(_) => return Err(MIRROR_UNREADABLE),
        }
        let text = read_git_file(path).ok_or(MIRROR_UNREADABLE)?;
        let names = match format {
            MirrorConfig::DaemonJson => daemon_json_mirrors(&text),
            MirrorConfig::RegistriesConf => registries_conf_redirects(&text),
        };
        if names? {
            return Err(MIRROR_NAMED);
        }
    }
    Ok(())
}

/// The `*.conf` files in the drop-in directories, each directory's in name order.
/// A missing directory holds none. A directory that exists but cannot be listed
/// refuses, and so does a listing with more than [`MIRROR_DROPIN_MAX_FILES`] files.
/// Only `*.conf` names are read, as podman reads them.
fn dropin_files(
    dirs: &[std::path::PathBuf],
) -> Result<Vec<(MirrorConfig, std::path::PathBuf)>, &'static str> {
    let mut out = Vec::new();
    for dir in dirs {
        if names_a_remote_share(&dir.to_string_lossy()) {
            return Err(MIRROR_UNREADABLE);
        }
        match dir.try_exists() {
            Ok(false) => continue,
            Ok(true) => {}
            Err(_) => return Err(MIRROR_UNREADABLE),
        }
        let mut names = Vec::new();
        for entry in std::fs::read_dir(dir).map_err(|_| MIRROR_UNREADABLE)? {
            let name = entry.map_err(|_| MIRROR_UNREADABLE)?.file_name();
            if name.to_string_lossy().ends_with(".conf") {
                names.push(name);
            }
        }
        names.sort();
        for name in names {
            if out.len() == MIRROR_DROPIN_MAX_FILES {
                return Err(MIRROR_TOO_MANY);
            }
            out.push((MirrorConfig::RegistriesConf, dir.join(name)));
        }
    }
    Ok(out)
}

/// The docker CLI's `currentContext` in `config.json`. The default (absent, null,
/// empty or `default`) is no switch. Any other context selects a daemon this check
/// does not read. A missing file is no switch; a file that cannot be read, does not
/// parse as a JSON object, or has a non-string context refuses.
fn docker_context_refusal(
    var: &dyn Fn(&str) -> Option<std::ffi::OsString>,
) -> Result<(), &'static str> {
    let Some(path) = docker_config_json(var) else {
        return Ok(());
    };
    if names_a_remote_share(&path.to_string_lossy()) {
        return Err(MIRROR_UNREADABLE);
    }
    match path.try_exists() {
        Ok(false) => return Ok(()),
        Ok(true) => {}
        Err(_) => return Err(MIRROR_UNREADABLE),
    }
    let text = read_git_file(&path).ok_or(MIRROR_UNREADABLE)?;
    let value: serde_json::Value = serde_json::from_str(&text).map_err(|_| MIRROR_UNPARSED)?;
    let object = value.as_object().ok_or(MIRROR_UNPARSED)?;
    match object.get("currentContext") {
        None | Some(serde_json::Value::Null) => Ok(()),
        Some(serde_json::Value::String(c)) if c.is_empty() || c == "default" => Ok(()),
        Some(serde_json::Value::String(_)) => Err(MIRROR_CONTEXT_DOCKER),
        Some(_) => Err(MIRROR_UNPARSED),
    }
}

/// Whether the container config can redirect a pull, for `var` as the environment.
/// `CONTAINERS_REGISTRIES_CONF` set (podman's own override) names a file this does
/// not read, so it refuses without reading anything. Otherwise the files of
/// [`container_mirror_paths`] and the drop-ins are read.
pub fn container_mirror_refusal(
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Result<(), &'static str> {
    let env: &dyn Fn(&str) -> Option<std::ffi::OsString> = &var;
    if var_is_set(env, "CONTAINERS_REGISTRIES_CONF") {
        return Err(MIRROR_ENV);
    }
    let system = std::path::Path::new("/");
    mirror_refusal_in(&container_mirror_paths_at(env, system))?;
    mirror_refusal_in(&dropin_files(&container_dropin_dirs(env, system))?)
}

/// [`container_mirror_refusal`] for one runtime, with `system` as the root of the
/// system directories. Docker reads only `daemon.json` and the `currentContext` of
/// its `config.json`; podman reads only `registries.conf` and its drop-ins, so the
/// other runtime's files say nothing about where this call connects. A remote
/// daemon or engine named by the environment is not one whose config is read, so
/// it refuses before any file is read.
pub fn runtime_mirror_refusal_at(
    builtin: &str,
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
    system: &std::path::Path,
) -> Result<(), &'static str> {
    let env: &dyn Fn(&str) -> Option<std::ffi::OsString> = &var;
    if builtin.starts_with("docker") {
        if var_is_set(env, "DOCKER_HOST") || var_is_set(env, "DOCKER_CONTEXT") {
            return Err(MIRROR_REMOTE_DOCKER);
        }
        docker_context_refusal(env)?;
        let mut paths = container_mirror_paths_at(env, system);
        paths.retain(|(format, _)| *format == MirrorConfig::DaemonJson);
        return mirror_refusal_in(&paths);
    }
    if var_is_set(env, "CONTAINER_HOST") || var_is_set(env, "CONTAINER_CONNECTION") {
        return Err(MIRROR_REMOTE_PODMAN);
    }
    if var_is_set(env, "CONTAINERS_REGISTRIES_CONF") {
        return Err(MIRROR_ENV);
    }
    let mut paths = container_mirror_paths_at(env, system);
    paths.retain(|(format, _)| *format == MirrorConfig::RegistriesConf);
    mirror_refusal_in(&paths)?;
    mirror_refusal_in(&dropin_files(&container_dropin_dirs(env, system))?)
}

/// [`runtime_mirror_refusal_at`] with the real system root.
pub fn runtime_mirror_refusal(
    builtin: &str,
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Result<(), &'static str> {
    runtime_mirror_refusal_at(builtin, var, std::path::Path::new("/"))
}

/// The egress check for the container commands that pull an image (`docker_run`,
/// `podman_run`, `docker_pull`, `docker_push`, `podman_pull`, `podman_push`). The
/// registry the reference names is judged by the caller; a daemon or
/// registries.conf mirror redirects the request to a registry nobody judged, so
/// under an allowlist such a mirror makes the destination unknown and the call is
/// refused through [`check_egress_unknown`]. Without an allowlist, or under the
/// permissive policy or a `*` allowlist, nothing is read.
pub fn check_container_mirror_egress(builtin: &str) -> Result<(), SafetyError> {
    if policy_permissive() {
        return Ok(());
    }
    let Some(allow) = net_allowlist() else {
        return Ok(());
    };
    if allow.split([';', ',']).any(|e| e.trim() == "*") {
        return Ok(());
    }
    match runtime_mirror_refusal(builtin, |name| std::env::var_os(name)) {
        Ok(()) => Ok(()),
        Err(reason) => check_egress_unknown(builtin, reason),
    }
}

/// The most of `~/.ssh/config` the egress check reads. A larger file is refused
/// under an allowlist, since its destinations cannot be read in full.
const SSH_CONFIG_MAX_BYTES: u64 = 1024 * 1024;

/// The host an ssh-family call connects to, as the allowlist must judge it.
///
/// ssh takes the destination from `~/.ssh/config` when the name the caller wrote
/// is a `Host` alias with a `HostName`, so the allowlist judges the HostName. The
/// result has no `user@` prefix. Without an allowlist (or under the permissive
/// policy) the config is not read and the name comes back as written. Under an
/// allowlist, a destination the config cannot show refuses the call through
/// [`check_egress_unknown`].
pub fn ssh_egress_host(builtin: &str, host: &str) -> Result<String, SafetyError> {
    let name = host.rsplit('@').next().unwrap_or(host);
    if policy_permissive() || net_allowlist().is_none() {
        return Ok(name.to_string());
    }
    let config = match read_ssh_config() {
        Ok(Some(text)) => text,
        Ok(None) => return Ok(name.to_string()),
        Err(reason) => {
            check_egress_unknown(builtin, reason)?;
            return Ok(name.to_string());
        }
    };
    match ssh_config_destination(&config, name) {
        Ok(Some(resolved)) => Ok(resolved),
        Ok(None) => Ok(name.to_string()),
        Err(reason) => {
            check_egress_unknown(builtin, reason)?;
            Ok(name.to_string())
        }
    }
}

/// `~/.ssh/config` for the current user, found as `bi_ssh_config` finds it: `HOME`,
/// then `USERPROFILE`. `Ok(None)` means there is no file. The error is a reason
/// for the refusal; the file's content is never part of it.
fn read_ssh_config() -> Result<Option<String>, &'static str> {
    use std::io::Read;
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map_err(|_| "no home directory is set, so ~/.ssh/config cannot be found")?;
    let path = std::path::Path::new(&home).join(".ssh").join("config");
    let file = match std::fs::File::open(&path) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(_) => {
            return Err("~/.ssh/config cannot be opened, so the host it reaches cannot be read")
        }
    };
    let mut buf = Vec::new();
    if file
        .take(SSH_CONFIG_MAX_BYTES + 1)
        .read_to_end(&mut buf)
        .is_err()
    {
        return Err("~/.ssh/config cannot be read, so the host it reaches cannot be read");
    }
    if buf.len() as u64 > SSH_CONFIG_MAX_BYTES {
        return Err("~/.ssh/config is over 1 MiB, so the host it reaches cannot be read");
    }
    Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
}

/// What `~/.ssh/config` makes `name` connect to. A `Host` block counts only when
/// it applies to `name`: a pattern matches it and no negated pattern excludes it.
/// `Ok(Some(host))` is the first HostName that applies; `Ok(None)` means ssh
/// judges the name as written (no applying block sets a HostName). `Err` says why
/// the destination cannot be read from this text: an `Include` or `Match` anywhere
/// in the file (either can change what applies); a `ProxyJump` or `ProxyCommand`
/// in an applying block; a HostName in an applying wildcard block; or a HostName
/// with a `%` token. Options that do not change the destination (User,
/// ServerAliveInterval) are ignored. Keywords are case-insensitive, `key value`
/// and `key=value` both parse, and a line starting with `#` is a comment. The
/// text is pure input, so tests can pass strings, and it is never echoed back.
pub fn ssh_config_destination(config: &str, name: &str) -> Result<Option<String>, &'static str> {
    const INCLUDE: &str = "~/.ssh/config has an Include, so the host it reaches cannot be read";
    const MATCH: &str = "~/.ssh/config has a Match block, so the host it reaches cannot be read";
    const PROXY: &str =
        "~/.ssh/config has a ProxyJump or ProxyCommand that applies to this host, so the host it reaches cannot be read";
    const WILDCARD: &str =
        "~/.ssh/config sets HostName in a wildcard Host block that applies to this host, so the host it reaches cannot be read";
    const TOKEN: &str =
        "the HostName in ~/.ssh/config is empty or uses a % token, so the host it reaches cannot be read";

    let name = name.trim().to_ascii_lowercase();
    // Options before the first `Host` line apply to every name, so the block
    // starts out applying.
    let mut applies = true;
    // Whether the current block applies to `name` through a wildcard pattern.
    let mut block_wildcard = false;
    let mut resolved: Option<String> = None;
    for raw in config.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let end = line
            .find(|c: char| c.is_whitespace() || c == '=')
            .unwrap_or(line.len());
        let key = line[..end].to_ascii_lowercase();
        let value = line[end..]
            .trim_start_matches(|c: char| c.is_whitespace() || c == '=')
            .trim();
        match key.as_str() {
            "include" => return Err(INCLUDE),
            "match" => return Err(MATCH),
            "proxyjump" | "proxycommand" if applies => return Err(PROXY),
            "host" => {
                let mut positive = false;
                let mut negated = false;
                let mut wildcard = false;
                for pattern in value.split_whitespace().map(str::to_ascii_lowercase) {
                    match pattern.strip_prefix('!') {
                        Some(not) => negated |= ssh_glob(not, &name),
                        None => {
                            if ssh_glob(&pattern, &name) {
                                positive = true;
                                wildcard |= pattern.contains(['*', '?']);
                            }
                        }
                    }
                }
                applies = positive && !negated;
                block_wildcard = applies && wildcard;
            }
            "hostname" if applies => {
                if block_wildcard {
                    return Err(WILDCARD);
                }
                let host = value.trim_matches('"').trim();
                if host.is_empty() || host.contains('%') {
                    return Err(TOKEN);
                }
                resolved.get_or_insert_with(|| host.to_string());
            }
            _ => {}
        }
    }
    Ok(resolved)
}

/// ssh's host pattern match: `*` any run, `?` one character, both case-insensitive
/// (the caller lower-cases both sides).
fn ssh_glob(pattern: &str, name: &str) -> bool {
    fn go(p: &[u8], n: &[u8]) -> bool {
        match p.split_first() {
            None => n.is_empty(),
            Some((b'*', rest)) => (0..=n.len()).any(|i| go(rest, &n[i..])),
            Some((b'?', rest)) => !n.is_empty() && go(rest, &n[1..]),
            Some((c, rest)) => n.first() == Some(c) && go(rest, &n[1..]),
        }
    }
    go(pattern.as_bytes(), name.as_bytes())
}

/// The lower-cased host a string names, if it names one: a URL's authority,
/// the host of an scp-style `user@host:path`, or a bare hostname or address.
/// Anything else (a path, a query, a flag) names no host and returns `None`.
pub fn destination_host(s: &str) -> Option<String> {
    let s = s.trim();
    if let Some(rest) = s.split_once("://").map(|(_, r)| r) {
        let authority = rest.split(['/', '?', '#']).next()?;
        let host_port = authority.rsplit('@').next()?;
        let host = if let Some(v6) = host_port.strip_prefix('[') {
            v6.split(']').next()?
        } else {
            host_port.split(':').next()?
        };
        return (!host.is_empty()).then(|| host.to_ascii_lowercase());
    }
    let hostish = |h: &str| {
        !h.is_empty()
            && h.chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
            && (h.contains('.') || h.eq_ignore_ascii_case("localhost"))
            && !h.starts_with('.')
            && !h.starts_with('-')
    };
    // `user@host` and scp-style `user@host:path` (git@github.com:org/repo).
    if let Some((_, after)) = s.split_once('@') {
        let host = after.split(':').next().unwrap_or("");
        return hostish(host).then(|| host.to_ascii_lowercase());
    }
    // A bare host, optionally with a port. A dotted word with no slash is how
    // ping, dig and ssh take their destination; a file name like `notes.txt`
    // also matches, which errs toward asking rather than toward allowing.
    let host = s.rsplit_once(':').map_or(s, |(h, p)| {
        if p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty() {
            h
        } else {
            s
        }
    });
    hostish(host).then(|| host.to_ascii_lowercase())
}

/// Whether `host` is `entry` or a subdomain of it. `*` matches everything; a
/// leading `*.` or `.` on the entry is accepted and means the same thing.
fn host_matches(host: &str, entry: &str) -> bool {
    let entry = entry
        .trim()
        .trim_start_matches("*.")
        .trim_start_matches('.');
    entry == "*" || host == entry || host.ends_with(&format!(".{entry}"))
}

/// Judge a network call's string arguments against an allowlist (`;`- or
/// `,`-separated). Every host the arguments name must be allowed, and a call
/// that names none is refused: under an allowlist, a destination that cannot
/// be read is not one that can be trusted.
pub fn egress_permitted(targets: &[String], allow: &str) -> Result<(), String> {
    let entries: Vec<String> = allow
        .split([';', ','])
        .map(|e| e.trim().to_ascii_lowercase())
        .filter(|e| !e.is_empty())
        .collect();
    if entries.iter().any(|e| e == "*") {
        return Ok(());
    }
    // A URL states its destination outright, so when one is present the other
    // arguments are payload (an output file, a body) and are not read as hosts
    // -- `web_download(url, "out.json")` must not be refused for `out.json`.
    // Without a URL, a string that exists on disk is a path, not a host. A
    // remote share is never asked about: probing `\\host\x` is itself traffic
    // to `host`, which is what this check decides about.
    let urls: Vec<&String> = targets.iter().filter(|t| t.contains("://")).collect();
    let hosts: Vec<String> = if urls.is_empty() {
        targets
            .iter()
            .filter(|t| names_a_remote_share(t) || !std::path::Path::new(t.as_str()).exists())
            .filter_map(|t| destination_host(t))
            .collect()
    } else {
        urls.iter().filter_map(|t| destination_host(t)).collect()
    };
    if hosts.is_empty() {
        return Err("the destination host could not be determined from the arguments".to_string());
    }
    match hosts
        .iter()
        .find(|h| !entries.iter().any(|e| host_matches(h, e)))
    {
        Some(h) => Err(format!("'{h}' is not in the allowlist")),
        None => Ok(()),
    }
}

// ---------------------------------------------------------------------------
// git remotes. `git fetch`, `git pull` and `git push` take no remote name or URL:
// they contact the remote the repository's `.git/config` names. The reader below
// is pure (it is fed text), so tests pass it strings.
//
// READ: the repository's config (for a worktree, its common directory's) and the
// lower levels `git_config_layers` names: the system files, then the global files
// (`$XDG_CONFIG_HOME/git/config` or `$HOME/.config/git/config`, then
// `$HOME/.gitconfig`). The repository's value wins; rewrites from every level are
// combined. Setting GIT_CONFIG_GLOBAL, GIT_CONFIG_SYSTEM, GIT_CONFIG,
// GIT_CONFIG_PARAMETERS, GIT_CONFIG_COUNT or GIT_DIR in the environment changes
// what git reads, so those refuse as unknown.
// ---------------------------------------------------------------------------

/// What one git remote URL contacts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GitRemote {
    /// A path on this machine, or `file://`: no network.
    Local,
    /// A host. `ssh` means the transport is ssh, so the host is an ssh destination
    /// that `~/.ssh/config` may rewrite (see [`ssh_egress_host`]).
    Host { host: String, ssh: bool },
    /// Not determinable from the text. The reason is the refusal's detail.
    Unknown(&'static str),
}

const GIT_TRANSPORT_UNKNOWN: &str =
    "the remote URL uses an ext:: or fd:: transport, which runs a program";
const GIT_SCHEME_UNKNOWN: &str = "the remote URL uses a scheme this check does not read";
const GIT_NO_HOST: &str = "the remote URL names no host";
const GIT_SHARE_UNKNOWN: &str = "the remote is a Windows share path, which opens a host";
const GIT_ENV_OVERRIDE: &str = "a GIT_CONFIG*, GIT_DIR setting is in the environment, so the remote cannot be read from .git/config";
const GIT_NO_REPO: &str =
    "no git repository is found from the working directory, so the remote cannot be read";
const GIT_POINTER_MALFORMED: &str = "the .git here is a worktree or submodule file, or its commondir, that does not point to a readable git directory, so the remote cannot be read";
const GIT_CONFIG_UNREADABLE: &str = ".git/config cannot be read, so the remote cannot be read";
const GIT_HEAD_UNREADABLE: &str =
    ".git/HEAD cannot be read, so the branch and its remote cannot be read";
const GIT_CONFIG_UNPARSED: &str =
    ".git/config has a line this reader does not parse, so the remote cannot be read";
const GIT_CONFIG_ESCAPE: &str =
    ".git/config has a backslash in a value or name, so the remote cannot be read";
const GIT_CONFIG_INCLUDE: &str = ".git/config has an include, so the remote cannot be read";
const GIT_REMOTE_VCS: &str =
    "the remote sets remote.<name>.vcs, a remote helper, so the transport cannot be read";
const GIT_REMOTE_MISSING: &str =
    "the remote the command uses has no [remote] section in .git/config";
const GIT_REMOTE_NO_URL: &str = "the remote the command uses has no URL in .git/config";

/// Classify one remote URL, as git would read it after `insteadOf` rewriting.
/// Forms: `scheme://` URLs (`file`, `ssh`, `git+ssh`, `ssh+git`, `http`, `https`,
/// `git`), scp-style `[user@]host:path`, and plain paths (relative or absolute,
/// Windows drive paths included). An `ext::` or `fd::` transport, an unknown
/// scheme, a UNC share, and a URL with no host are `Unknown`.
pub fn git_remote_target(url: &str) -> GitRemote {
    let url = url.trim();
    if url.starts_with("ext::") || url.starts_with("fd::") {
        return GitRemote::Unknown(GIT_TRANSPORT_UNKNOWN);
    }
    if names_a_remote_share(url) {
        return GitRemote::Unknown(GIT_SHARE_UNKNOWN);
    }
    if let Some((scheme, _)) = url.split_once("://") {
        return match scheme.to_ascii_lowercase().as_str() {
            "file" => GitRemote::Local,
            "ssh" | "git+ssh" | "ssh+git" => match destination_host(url) {
                Some(host) => GitRemote::Host { host, ssh: true },
                None => GitRemote::Unknown(GIT_NO_HOST),
            },
            "http" | "https" | "git" => match destination_host(url) {
                Some(host) => GitRemote::Host { host, ssh: false },
                None => GitRemote::Unknown(GIT_NO_HOST),
            },
            _ => GitRemote::Unknown(GIT_SCHEME_UNKNOWN),
        };
    }
    // scp-style `[user@]host:path`. A colon after a slash, or a single letter
    // before it (a Windows drive), makes the text a local path.
    if let Some((before, _)) = url.split_once(':') {
        let is_drive = before.len() == 1 && before.chars().all(|c| c.is_ascii_alphabetic());
        if is_drive || before.contains('/') || before.contains('\\') {
            return GitRemote::Local;
        }
        let host = before.rsplit('@').next().unwrap_or("").trim();
        if host.is_empty() || host.contains('[') {
            return GitRemote::Unknown(GIT_NO_HOST);
        }
        return GitRemote::Host {
            host: host.to_ascii_lowercase(),
            ssh: true,
        };
    }
    GitRemote::Local
}

/// One `[section]`, `[section "sub"]` or `key = value` line of a git config file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitConfigEntry {
    pub section: String,
    pub subsection: Option<String>,
    pub key: String,
    pub value: String,
}

/// Parse a git config file's text. Section and key names are lower-cased; a
/// subsection keeps its case. An inline `#` or `;` outside quotes starts a
/// comment, and quotes are removed from values. A backslash in a value of a
/// section that names a destination, in a subsection name, or ending any value
/// is refused (git's escape rules are not read), as is an
/// `include` or `includeIf` section and any line this reader does not understand.
pub fn git_config_entries(text: &str) -> Result<Vec<GitConfigEntry>, &'static str> {
    let mut out = Vec::new();
    let mut current: Option<(String, Option<String>)> = None;
    for raw in text.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
            continue;
        }
        if let Some(rest) = line.strip_prefix('[') {
            let end = rest.find(']').ok_or(GIT_CONFIG_UNPARSED)?;
            let inner = &rest[..end];
            let after = rest[end + 1..].trim();
            if !after.is_empty() && !after.starts_with('#') && !after.starts_with(';') {
                return Err(GIT_CONFIG_UNPARSED);
            }
            let header = git_config_header(inner)?;
            if header.0 == "include" || header.0 == "includeif" {
                return Err(GIT_CONFIG_INCLUDE);
            }
            current = Some(header);
            continue;
        }
        let Some((section, subsection)) = current.clone() else {
            return Err(GIT_CONFIG_UNPARSED);
        };
        let mut value = String::new();
        let mut in_quote = false;
        for c in line.chars() {
            match c {
                '"' => {
                    in_quote = !in_quote;
                    value.push(c);
                }
                '#' | ';' if !in_quote => break,
                _ => value.push(c),
            }
        }
        let value = value.trim();
        let (key, val) = match value.split_once('=') {
            Some((k, v)) => (k.trim(), v.trim()),
            None => (value, "true"),
        };
        if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            return Err(GIT_CONFIG_UNPARSED);
        }
        // A trailing backslash continues the line, so it can hide a key. Elsewhere
        // only the sections that name a destination need their escapes read: a
        // Windows path in `http.sslCAInfo` says nothing about where git connects.
        let names_a_destination = matches!(section.as_str(), "remote" | "url" | "branch");
        if val.ends_with('\\') || (names_a_destination && val.contains('\\')) {
            return Err(GIT_CONFIG_ESCAPE);
        }
        out.push(GitConfigEntry {
            section,
            subsection,
            key: key.to_ascii_lowercase(),
            value: val.replace('"', "").trim().to_string(),
        });
    }
    Ok(out)
}

/// The name and subsection of a section header's inside: `remote "origin"`,
/// `url "https://x/"` or the old `remote.origin` form.
fn git_config_header(inner: &str) -> Result<(String, Option<String>), &'static str> {
    if let Some(q) = inner.find('"') {
        let name = inner[..q].trim().to_ascii_lowercase();
        let sub = inner[q + 1..]
            .strip_suffix('"')
            .ok_or(GIT_CONFIG_UNPARSED)?;
        if sub.contains('\\') {
            return Err(GIT_CONFIG_ESCAPE);
        }
        if name.is_empty() || sub.contains('"') {
            return Err(GIT_CONFIG_UNPARSED);
        }
        return Ok((name, Some(sub.to_string())));
    }
    let inner = inner.trim();
    match inner.split_once('.') {
        Some((name, sub)) => Ok((name.to_ascii_lowercase(), Some(sub.to_string()))),
        None if !inner.is_empty() => Ok((inner.to_ascii_lowercase(), None)),
        None => Err(GIT_CONFIG_UNPARSED),
    }
}

/// The branch `HEAD` names: `Some(name)` on a branch, `None` when detached.
fn git_head_branch(head: &str) -> Result<Option<String>, &'static str> {
    let head = head.trim();
    if let Some(r) = head.strip_prefix("ref: ") {
        return Ok(r.trim().strip_prefix("refs/heads/").map(str::to_string));
    }
    if head.len() >= 40 && head.chars().all(|c| c.is_ascii_hexdigit()) {
        return Ok(None);
    }
    Err(GIT_HEAD_UNREADABLE)
}

/// The URLs the command would contact, from the config and HEAD text.
///
/// `lower` is the config text of the levels git reads below the repository,
/// lowest precedence first: the system files, then the global files (see
/// [`git_config_layers`]). `config` is the repository's own config and `head`
/// its HEAD. A single value (the remote, its URLs, the branch's remote) comes
/// from the repository when the repository sets it, else from the lower levels,
/// the later file winning, as git reads them. Rewrites (`url.<base>.insteadOf`,
/// and `pushInsteadOf` for push) are combined across every level, and the
/// longest matching prefix wins.
///
/// The remote is the current branch's `branch.<b>.remote` (for push,
/// `branch.<b>.pushRemote` then `remote.pushDefault` first), else `origin`. A
/// remote named `.` is local and yields no URL. The URL is `remote.<n>.pushurl`
/// for push when set, else `remote.<n>.url`. Returns `Err` when the remote cannot
/// be determined from this text: an include at any level, a `vcs` helper, no
/// such remote, no URL, or an unreadable HEAD.
pub fn git_contact_urls(
    lower: &[&str],
    config: &str,
    head: &str,
    push: bool,
) -> Result<Vec<String>, &'static str> {
    let mut lower_entries = Vec::new();
    for text in lower {
        lower_entries.extend(git_config_entries(text)?);
    }
    let repo_entries = git_config_entries(config)?;
    let branch = git_head_branch(head)?;
    let all = || repo_entries.iter().chain(lower_entries.iter());
    let values = |section: &str, sub: Option<&str>, key: &str| -> Vec<String> {
        let pick = |entries: &[GitConfigEntry]| -> Vec<String> {
            entries
                .iter()
                .filter(|e| e.section == section && e.subsection.as_deref() == sub && e.key == key)
                .map(|e| e.value.clone())
                .collect()
        };
        let own = pick(&repo_entries);
        if own.is_empty() {
            pick(&lower_entries)
        } else {
            own
        }
    };
    let mut remote: Option<String> = None;
    if push {
        if let Some(b) = &branch {
            remote = values("branch", Some(b), "pushremote").pop();
        }
        if remote.is_none() {
            remote = values("remote", None, "pushdefault").pop();
        }
    }
    if remote.is_none() {
        if let Some(b) = &branch {
            remote = values("branch", Some(b), "remote").pop();
        }
    }
    let remote = remote.unwrap_or_else(|| "origin".to_string());
    if remote == "." {
        return Ok(Vec::new());
    }
    if !all().any(|e| e.section == "remote" && e.subsection.as_deref() == Some(remote.as_str())) {
        return Err(GIT_REMOTE_MISSING);
    }
    if all().any(|e| {
        e.section == "remote" && e.subsection.as_deref() == Some(remote.as_str()) && e.key == "vcs"
    }) {
        return Err(GIT_REMOTE_VCS);
    }
    let mut urls = if push {
        values("remote", Some(&remote), "pushurl")
    } else {
        Vec::new()
    };
    if urls.is_empty() {
        urls = values("remote", Some(&remote), "url");
    }
    if urls.is_empty() {
        return Err(GIT_REMOTE_NO_URL);
    }
    // (base, prefix) pairs: `[url "base"] insteadOf = prefix`, from every level.
    let rules = |key: &str| -> Vec<(String, String)> {
        all()
            .filter(|e| e.section == "url" && e.key == key)
            .filter_map(|e| e.subsection.clone().map(|b| (b, e.value.clone())))
            .filter(|(_, prefix)| !prefix.is_empty())
            .collect()
    };
    let instead = rules("insteadof");
    let push_instead = rules("pushinsteadof");
    let rewrite = |url: &str, rules: &[(String, String)]| -> Option<String> {
        rules
            .iter()
            .filter(|(_, p)| url.starts_with(p.as_str()))
            .max_by_key(|(_, p)| p.len())
            .map(|(base, p)| format!("{base}{}", &url[p.len()..]))
    };
    Ok(urls
        .iter()
        .map(|u| {
            if push {
                if let Some(r) = rewrite(u, &push_instead) {
                    return r;
                }
            }
            rewrite(u, &instead).unwrap_or_else(|| u.clone())
        })
        .collect())
}

/// `GIT_*` variables that change which config git reads or where the repository
/// is. Any of them set refuses the remote check as unknown.
const GIT_OVERRIDE_VARS: &[&str] = &[
    "GIT_DIR",
    "GIT_CONFIG",
    "GIT_CONFIG_GLOBAL",
    "GIT_CONFIG_SYSTEM",
    "GIT_CONFIG_PARAMETERS",
    "GIT_CONFIG_COUNT",
];

/// The egress check for `git fetch` (`push` false), `git pull` (false) and
/// `git push` (true), which contact the remote `.git/config` names (see
/// [`git_contact_urls`]). A no-op without an allowlist or under the permissive
/// policy. Under a `*` allowlist every host is allowed. Any remote that cannot
/// be determined refuses through [`check_egress_unknown`]. An ssh remote's host
/// is resolved through `~/.ssh/config` as ssh would. Call it before spawning git.
pub fn check_git_remote_egress(builtin: &str, push: bool) -> Result<(), SafetyError> {
    if policy_permissive() {
        return Ok(());
    }
    let Some(allow) = net_allowlist() else {
        return Ok(());
    };
    if allow.split([';', ',']).any(|e| e.trim() == "*") {
        return Ok(());
    }
    let urls = match git_urls_in_working_repo(push) {
        Ok(urls) => urls,
        Err(reason) => return check_egress_unknown(builtin, reason),
    };
    let mut targets = Vec::new();
    for url in urls {
        match git_remote_target(&url) {
            GitRemote::Local => {}
            GitRemote::Host { host, ssh } => {
                let host = if ssh {
                    ssh_egress_host(builtin, &host)?
                } else {
                    host
                };
                targets.push(format!("https://{host}"));
            }
            GitRemote::Unknown(reason) => return check_egress_unknown(builtin, reason),
        }
    }
    if targets.is_empty() {
        return Ok(());
    }
    check_egress(builtin, &targets)
}

/// The URLs the working repository's remote resolves to. The `.git` is found by
/// walking up from the working directory. A worktree's `.git` file is followed
/// once to its gitdir (which holds `HEAD`), and that gitdir's `commondir` once
/// to the common directory (which holds `config`). The lower levels come from
/// [`git_config_layers`].
fn git_urls_in_working_repo(push: bool) -> Result<Vec<String>, &'static str> {
    if GIT_OVERRIDE_VARS
        .iter()
        .any(|v| std::env::var_os(v).is_some())
    {
        return Err(GIT_ENV_OVERRIDE);
    }
    let cwd = std::env::current_dir().map_err(|_| GIT_NO_REPO)?;
    let dot_git = cwd
        .ancestors()
        .map(|d| d.join(".git"))
        .find(|p| p.exists())
        .ok_or(GIT_NO_REPO)?;
    let (git_dir, common_dir) = git_dirs_of(&dot_git)?;
    let config = read_git_file(&common_dir.join("config")).ok_or(GIT_CONFIG_UNREADABLE)?;
    let head = read_git_file(&git_dir.join("HEAD")).ok_or(GIT_HEAD_UNREADABLE)?;
    let layers = git_config_layers()?;
    let lower: Vec<&str> = layers.iter().map(String::as_str).collect();
    git_contact_urls(&lower, &config, &head, push)
}

/// The gitdir and the common directory of the `.git` at `dot_git`. A directory is
/// both. A file must read `gitdir: <path>`, relative to the file's directory or
/// absolute. A malformed pointer, a remote share path (probing it would reach a
/// host, see [`names_a_remote_share`]), or a target that is not a directory
/// refuses as unknown.
fn git_dirs_of(
    dot_git: &std::path::Path,
) -> Result<(std::path::PathBuf, std::path::PathBuf), &'static str> {
    if dot_git.is_dir() {
        let common = common_dir_of(dot_git)?;
        return Ok((dot_git.to_path_buf(), common));
    }
    if !dot_git.is_file() {
        return Err(GIT_NO_REPO);
    }
    let text = read_git_file(dot_git).ok_or(GIT_POINTER_MALFORMED)?;
    let target = text
        .lines()
        .next()
        .and_then(|l| l.trim().strip_prefix("gitdir:"))
        .map(str::trim)
        .filter(|t| !t.is_empty() && !names_a_remote_share(t))
        .ok_or(GIT_POINTER_MALFORMED)?;
    let base = dot_git.parent().ok_or(GIT_POINTER_MALFORMED)?;
    let git_dir = base.join(target);
    if !git_dir.is_dir() {
        return Err(GIT_POINTER_MALFORMED);
    }
    let common = common_dir_of(&git_dir)?;
    Ok((git_dir, common))
}

/// The common directory of a gitdir: the path its `commondir` file names,
/// relative to the gitdir, or the gitdir itself when there is no such file. The
/// file is read once and not followed.
fn common_dir_of(git_dir: &std::path::Path) -> Result<std::path::PathBuf, &'static str> {
    let file = git_dir.join("commondir");
    if !file.try_exists().map_err(|_| GIT_POINTER_MALFORMED)? {
        return Ok(git_dir.to_path_buf());
    }
    let text = read_git_file(&file).ok_or(GIT_POINTER_MALFORMED)?;
    let rel = text.lines().next().unwrap_or("").trim();
    if rel.is_empty() || names_a_remote_share(rel) {
        return Err(GIT_POINTER_MALFORMED);
    }
    let common = git_dir.join(rel);
    if !common.is_dir() {
        return Err(GIT_POINTER_MALFORMED);
    }
    Ok(common)
}

/// The config text git reads below the repository, lowest precedence first: the
/// system files, then the global files. See [`git_config_paths`] for which files.
fn git_config_layers() -> Result<Vec<String>, &'static str> {
    read_config_layers(&git_config_paths(|name| std::env::var_os(name)))
}

/// The config files git reads below the repository, lowest precedence first,
/// with `var` as the environment.
///
/// System: `/etc/gitconfig` and `%ProgramData%\Git\config`. On Windows, Git for
/// Windows also reads `etc\gitconfig` and `mingw64\etc\gitconfig` under its
/// install directory, which [`git_install_dir`] finds from the `git.exe` on
/// `PATH`. `GIT_CONFIG_NOSYSTEM`, which git honours, drops the system files.
///
/// Global, as git reads them: `$XDG_CONFIG_HOME/git/config` when that is set and
/// not empty, else `$HOME/.config/git/config`; then `$HOME/.gitconfig`. `HOME`
/// falls back to `USERPROFILE`, as git on Windows does.
pub fn git_config_paths(
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Vec<std::path::PathBuf> {
    use std::path::PathBuf;
    let set = |name: &str| var(name).filter(|v| !v.is_empty());
    let truthy = |name: &str| {
        set(name).is_some_and(|v| {
            let v = v.to_string_lossy().trim().to_ascii_lowercase();
            !matches!(v.as_str(), "0" | "false" | "no" | "off")
        })
    };
    let mut paths: Vec<PathBuf> = Vec::new();
    if !truthy("GIT_CONFIG_NOSYSTEM") {
        paths.push(PathBuf::from("/etc/gitconfig"));
        if let Some(pd) = set("ProgramData") {
            paths.push(PathBuf::from(pd).join("Git").join("config"));
        }
        if let Some(install) = set("PATH").and_then(|p| git_install_dir(&p)) {
            paths.push(install.join("etc").join("gitconfig"));
            paths.push(install.join("mingw64").join("etc").join("gitconfig"));
        }
    }
    let home = set("HOME")
        .or_else(|| set("USERPROFILE"))
        .map(PathBuf::from);
    match set("XDG_CONFIG_HOME") {
        Some(xdg) => paths.push(PathBuf::from(xdg).join("git").join("config")),
        None => {
            if let Some(h) = &home {
                paths.push(h.join(".config").join("git").join("config"));
            }
        }
    }
    if let Some(h) = &home {
        paths.push(h.join(".gitconfig"));
    }
    paths
}

/// The directory a Git for Windows install lives in, derived from the path of a
/// `git` program. The wrapper is `<install>\cmd\git.exe` and the program itself is
/// `<install>\mingw64\bin\git.exe`; `<install>\bin\git.exe` is read the same way.
/// The string is the only input: nothing is run and nothing is probed. `None`
/// when the name is not git or the directory is not one of those shapes.
pub fn git_install_dir_of(git_exe: &str) -> Option<String> {
    let parts: Vec<&str> = git_exe.split(['\\', '/']).collect();
    let (name, dirs) = parts.split_last()?;
    if !name.eq_ignore_ascii_case("git.exe") && !name.eq_ignore_ascii_case("git") {
        return None;
    }
    let last = dirs.last()?.to_ascii_lowercase();
    let keep = match last.as_str() {
        "cmd" => dirs.len() - 1,
        "bin" if dirs.len() >= 2 && dirs[dirs.len() - 2].eq_ignore_ascii_case("mingw64") => {
            dirs.len() - 2
        }
        "bin" => dirs.len() - 1,
        _ => return None,
    };
    if keep == 0 {
        return None;
    }
    Some(dirs[..keep].join("\\"))
}

/// The Git for Windows install directory, from the first `git.exe` on `path_var`
/// (the program is located, never run). Windows only: elsewhere git's system
/// config is not under the install. A PATH entry on a remote share is skipped,
/// since testing for a file there would reach a host.
fn git_install_dir(path_var: &std::ffi::OsStr) -> Option<std::path::PathBuf> {
    if !cfg!(windows) {
        return None;
    }
    let git = std::env::split_paths(path_var)
        .filter(|dir| !names_a_remote_share(&dir.to_string_lossy()))
        .map(|dir| dir.join("git.exe"))
        .find(|p| p.is_file())?;
    git_install_dir_of(&git.to_string_lossy()).map(std::path::PathBuf::from)
}

/// The text of each file in `paths` that exists, in order. A missing file is
/// skipped. A file that cannot be read, is over 1 MiB, or names a remote share
/// (probing it would reach a host) refuses as unknown. The parser refuses an
/// include at any level.
fn read_config_layers(paths: &[std::path::PathBuf]) -> Result<Vec<String>, &'static str> {
    let mut out = Vec::new();
    for path in paths {
        if names_a_remote_share(&path.to_string_lossy()) {
            return Err(GIT_CONFIG_UNREADABLE);
        }
        match path.try_exists() {
            Ok(false) => continue,
            Ok(true) => {}
            Err(_) => return Err(GIT_CONFIG_UNREADABLE),
        }
        out.push(read_git_file(path).ok_or(GIT_CONFIG_UNREADABLE)?);
    }
    Ok(out)
}

/// A git file's text, at most 1 MiB. `None` when it cannot be read.
fn read_git_file(path: &std::path::Path) -> Option<String> {
    use std::io::Read;
    let file = std::fs::File::open(path).ok()?;
    let mut buf = Vec::new();
    file.take(SSH_CONFIG_MAX_BYTES + 1)
        .read_to_end(&mut buf)
        .ok()?;
    if buf.len() as u64 > SSH_CONFIG_MAX_BYTES {
        return None;
    }
    Some(String::from_utf8_lossy(&buf).into_owned())
}

/// Judge one redirect hop of a request the gate already admitted.
///
/// `guard` sees only the URL a builtin was called with. When curl followed
/// redirects itself (`-L`), every later hop reached a host nobody checked, so
/// an allowed host could send the request anywhere. The hop is not a new call
/// and asks for no new approval; it must stay inside the allowlist, and a hop
/// from a public host may not land on this machine or a private network, the
/// classic SSRF bounce. Every hop is judged, including one that began on a
/// local address: the first URL is refused before any request is made, so
/// no hop starts there.
pub fn guard_redirect(
    builtin: &str,
    from: &str,
    to: &str,
) -> anyhow::Result<crate::security::CheckedHttpUrl> {
    let scheme = url::Url::parse(to).map(|u| u.scheme().to_string());
    if !matches!(scheme.as_deref(), Ok("http" | "https")) || to.chars().any(char::is_control) {
        let _ = audit(
            builtin,
            Effect::Network,
            "deny_redirect_scheme",
            to,
            json!({ "from": from }),
        );
        return Err(policy_deny(
            builtin,
            format!("{builtin}: {from} redirected to {to:?}, which is not an http or https URL"),
            "only http and https redirects are followed; a file: or other target would reach past the network guards",
        ));
    }
    if !policy_permissive() {
        if let Some(allow) = net_allowlist() {
            if let Err(detail) = egress_permitted(&[to.to_string()], &allow) {
                let _ = audit(
                    builtin,
                    Effect::Network,
                    "deny_egress_redirect",
                    to,
                    json!({ "from": from, "allow": allow, "detail": detail }),
                );
                return Err(policy_deny(
                    builtin,
                    format!("{builtin}: redirect to {to} denied: {detail}"),
                    format!("IRONSHELL_NET_ALLOW permits only: {allow}; the server redirected outside it"),
                ));
            }
        }
    }
    match crate::security::check_http_url(builtin, to) {
        Ok(checked) => Ok(checked),
        Err(e) => {
            let _ = audit(
                builtin,
                Effect::Network,
                "deny_redirect_ssrf",
                to,
                json!({ "from": from, "detail": e.to_string() }),
            );
            Err(policy_deny(
                builtin,
                format!("{builtin}: {from} redirected to {to}, which is refused: {e}"),
                "a public server may not redirect a request onto this machine or a private network",
            ))
        }
    }
}

/// The first component of `path` whose stem (the text before its first `.`,
/// trailing spaces ignored) is a Windows reserved device name: `CON`, `PRN`,
/// `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`, in any case, with or without an
/// extension. Returns the stem as written. `/` and `\` both separate
/// components. Platform-independent; callers decide whether it applies.
pub fn reserved_device_name(path: &str) -> Option<String> {
    for part in path.split(['/', '\\']) {
        let stem = part.split('.').next().unwrap_or("").trim_end_matches(' ');
        let up = stem.to_ascii_uppercase();
        let device = matches!(
            up.as_str(),
            "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
        ) || (up.len() == 4
            && (up.starts_with("COM") || up.starts_with("LPT"))
            && up.as_bytes()[3].is_ascii_digit()
            && up.as_bytes()[3] != b'0');
        if device {
            return Some(stem.to_string());
        }
    }
    None
}

/// `E_BAD_ARG` for a path with a reserved device-name component (Windows).
pub fn reserved_device_error(builtin: &str, name: &str) -> SafetyError {
    SafetyError {
        code: ErrorCode::BadArg,
        message: format!("{builtin}: `{name}` is a reserved device name on Windows"),
        builtin: builtin.to_string(),
        hint: "Windows treats CON, PRN, AUX, NUL, COM1-COM9 and LPT1-LPT9 (with or without an extension) as devices, and a file with such a name cannot be removed; choose another name".to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "a name that is not a Windows device name".to_string(),
        got: name.to_string(),
        extra: serde_json::Map::new(),
    }
}

/// The first reason Windows would not keep the path a write names as written,
/// as `E_BAD_ARG`: a reserved device name (`CON`, `NUL`, ...), a component that
/// ends in a dot or a space (the OS strips it, so `a.txt.` is `a.txt`), or a `:`
/// in a component after the drive prefix (`f.txt:stream` is an alternate data
/// stream, not a file of that name). Platform-independent; callers decide
/// whether it applies. `/` and `\` both separate components, and a `\\?\`,
/// `\\.\` or drive prefix is skipped.
pub fn windows_name_refusal(builtin: &str, path: &str) -> Option<SafetyError> {
    if let Some(name) = reserved_device_name(path) {
        return Some(reserved_device_error(builtin, &name));
    }
    let mut rest = path;
    for prefix in ["\\\\?\\", "\\\\.\\", "//?/", "//./"] {
        if let Some(r) = rest.strip_prefix(prefix) {
            rest = r;
            break;
        }
    }
    let bytes = rest.as_bytes();
    if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
        rest = &rest[2..];
    }
    for part in rest.split(['/', '\\']) {
        if part.is_empty() || part == "." || part == ".." {
            continue;
        }
        if part.contains(':') {
            return Some(SafetyError {
                code: ErrorCode::BadArg,
                message: format!(
                    "{builtin}: `{part}` names an alternate data stream on Windows (a `:` after the drive)"
                ),
                builtin: builtin.to_string(),
                hint: "Windows reads `name:stream` as a hidden stream of the file `name`, not as a file called that; choose a name without a colon".to_string(),
                approval: None,
                did_you_mean: Vec::new(),
                expected: "a name without a `:`".to_string(),
                got: part.to_string(),
                extra: serde_json::Map::new(),
            });
        }
        if part.ends_with('.') || part.ends_with(' ') {
            return Some(SafetyError {
                code: ErrorCode::BadArg,
                message: format!(
                    "{builtin}: `{part}` ends in a dot or a space, which Windows would strip, so the write would land on a different name"
                ),
                builtin: builtin.to_string(),
                hint: "Windows silently drops a trailing dot or space from a name, so `a.txt.` writes `a.txt`; remove it from the name".to_string(),
                approval: None,
                did_you_mean: Vec::new(),
                expected: "a name that does not end in a dot or a space".to_string(),
                got: part.to_string(),
                extra: serde_json::Map::new(),
            });
        }
    }
    None
}

pub fn guard(ctx: GuardCtx) -> Result<(), SafetyError> {
    let mode = current_mode();
    let resource = ctx.targets.join(", ");

    // Windows names that are not what they say: a device name (a file made under
    // one cannot be deleted), a trailing dot or space the OS strips, and an
    // alternate data stream. Refused for every write, in either mode, before the
    // jail is consulted.
    if cfg!(windows) && ctx.effect.is_filesystem() && ctx.fs_paths {
        for t in &ctx.targets {
            // A read keeps `name:stream` and a trailing dot as they are; only a
            // write or a delete is refused for them.
            let refusal = if matches!(ctx.effect, Effect::WriteLocal | Effect::Destructive) {
                windows_name_refusal(ctx.builtin, t)
            } else {
                reserved_device_name(t).map(|name| reserved_device_error(ctx.builtin, &name))
            };
            if let Some(e) = refusal {
                return Err(e);
            }
        }
    }

    // 0. Resource governors (§7.6): bound the per-run blast radius before any
    //    other check, so a runaway loop is stopped even if every op is allowed.
    if let Err(e) = governor_admit(ctx.effect, ctx.builtin) {
        let _ = audit(
            ctx.builtin,
            ctx.effect,
            "deny_budget",
            &resource,
            json!({ "governor": governor_snapshot() }),
        );
        return Err(e);
    }

    // 1. Workspace jail for filesystem path targets.
    if jail_enforced(mode) && ctx.effect.is_filesystem() && ctx.fs_paths {
        for t in &ctx.targets {
            if !within_workspace(t) {
                let _ = audit(
                    ctx.builtin,
                    ctx.effect,
                    "deny_outside_workspace",
                    &resource,
                    json!({ "target": t }),
                );
                return Err(SafetyError {
                    code: ErrorCode::OutsideWorkspace,
                    message: format!("{}: '{}' is outside the workspace root", ctx.builtin, t),
                    builtin: ctx.builtin.to_string(),
                    hint: outside_workspace_hint(),
                    approval: None,
                    did_you_mean: Vec::new(),
                    expected: String::new(),
                    got: String::new(),
                    extra: serde_json::Map::new(),
                });
            }
            // The audited party must not own the evidence (AS-2026-02).
            //
            // `audit_path()` defaults to `<workspace>/.ironshell/audit.log`, which is
            // inside the jail — the one region a jailed builtin may write. So an
            // ordinary `file.write` to it was allowed, and since the hash chain
            // is unkeyed, the log could be rewritten end-to-end with a fresh,
            // internally consistent chain that `audit_verify()` accepts.
            //
            // This is defence in depth, not a complete fix, and the limit is
            // worth stating: it stops a *jailed filesystem* builtin. An approved
            // `Exec` call can still reach the file, and the chain is still
            // unkeyed. Keying it needs key management, which is a design
            // decision rather than a patch. What this closes is the cheap path.
            if is_audit_artifact(t) {
                let _ = audit(
                    ctx.builtin,
                    ctx.effect,
                    "deny_audit_tamper",
                    &resource,
                    json!({ "target": t }),
                );
                // The path is inside the workspace, so the refusal is a policy
                // decision about protected evidence, not a containment failure.
                return Err(SafetyError {
                    code: ErrorCode::PolicyDeny,
                    message: format!(
                        "{}: '{}' is the audit log or its directory, which is protected and cannot be written by a guarded builtin",
                        ctx.builtin, t
                    ),
                    builtin: ctx.builtin.to_string(),
                    hint: "the audit trail is evidence about this session, so the session \
                           may not edit it; point IRONSHELL_AUDIT_LOG elsewhere if you need a \
                           different location"
                        .to_string(),
                    approval: None,
                    did_you_mean: Vec::new(),
                    expected: String::new(),
                    got: String::new(),
                    extra: serde_json::Map::new(),
                });
            }
            // The gate's own configuration, for the same reason: what the
            // audited party may not edit is what decides what it may do.
            if is_governance_file(t) {
                let _ = audit(
                    ctx.builtin,
                    ctx.effect,
                    "deny_governance_tamper",
                    &resource,
                    json!({ "target": t }),
                );
                return Err(SafetyError {
                    code: ErrorCode::OutsideWorkspace,
                    message: format!(
                        "{}: '{}' configures this shell's access control or audit key and cannot be written by a guarded builtin",
                        ctx.builtin, t
                    ),
                    builtin: ctx.builtin.to_string(),
                    hint: "the RBAC config and the audit key are read at startup and govern \
                           later calls, so the session may not edit them; set \
                           IRONSHELL_RBAC_CONFIG or IRONSHELL_AUDIT_KEY_FILE to a path outside the \
                           workspace"
                        .to_string(),
                    approval: None,
                    did_you_mean: Vec::new(),
                    expected: String::new(),
                    got: String::new(),
                    extra: serde_json::Map::new(),
                });
            }
            if mode == Mode::Agent && is_git_control_path(t) {
                let _ = audit(
                    ctx.builtin,
                    ctx.effect,
                    "deny_git_control",
                    &resource,
                    json!({ "target": t }),
                );
                return Err(SafetyError {
                    code: ErrorCode::OutsideWorkspace,
                    message: format!(
                        "{}: '{}' is inside a .git directory and cannot be written by an agent",
                        ctx.builtin, t
                    ),
                    builtin: ctx.builtin.to_string(),
                    hint: "git runs programs named in .git/config and .git/hooks, so a write \
                           there would run code on the next git call; use the git_* builtins \
                           to change a repository"
                        .to_string(),
                    approval: None,
                    did_you_mean: Vec::new(),
                    expected: String::new(),
                    got: String::new(),
                    extra: serde_json::Map::new(),
                });
            }
        }
    }

    // 1b. Egress allowlist. Before RBAC for the same reason as the jail: an
    //     operator-configured boundary is not something a role escapes.
    //     A builtin in `EGRESS_JUDGED_BY_BODY` is exempt: its argument is not a
    //     host (a package name), and its body makes the destination-unknown check.
    if ctx.effect == Effect::Network
        && !policy_permissive()
        && !EGRESS_JUDGED_BY_BODY.contains(&ctx.builtin)
    {
        if let Some(allow) = net_allowlist() {
            if let Err(detail) = egress_permitted(&ctx.targets, &allow) {
                return Err(egress_denied(
                    ctx.builtin,
                    ctx.effect,
                    &resource,
                    &allow,
                    detail,
                ));
            }
        }
    }

    // 2. RBAC: an authorized principal bypasses the approval requirement.
    //    (The workspace jail above is intentionally NOT bypassed — defense in
    //    depth: authorization grants capabilities, not an escape from the jail.)
    if let Some(true) = rbac_authorized(ctx.effect, ctx.builtin) {
        let _ = audit(
            ctx.builtin,
            ctx.effect,
            "rbac_allow",
            &resource,
            json!({ "principal": current_principal() }),
        );
        return Ok(());
    }

    // 3. Policy decision, with the egress rule `effective_decision` adds.
    //    `Network` is `Allow` in the policy table; the rule that makes it ask in
    //    agent mode is there, not here.
    // `exit` is a process-lifecycle call, so it stays `Process` for the audit and
    // the governor. What it ends is this ish process alone: nothing outside it
    // changes, and agent mode had been asking for approval to do that. The
    // transaction refusal for it is separate and still applies.
    let decision = match ctx.builtin {
        "exit" => Decision::Allow,
        _ => effective_decision(ctx.effect, mode),
    };
    match decision {
        Decision::Allow => {
            let _ = audit(ctx.builtin, ctx.effect, "allow", &resource, json!({}));
            Ok(())
        }
        Decision::Deny => {
            let _ = audit(ctx.builtin, ctx.effect, "deny", &resource, json!({}));
            Err(SafetyError {
                code: ErrorCode::PolicyDeny,
                message: format!(
                    "{}: {} operations are denied by policy in agent mode",
                    ctx.builtin,
                    ctx.effect.as_str()
                ),
                builtin: ctx.builtin.to_string(),
                hint: "this effect class has no approval path; perform it outside agent mode"
                    .to_string(),
                approval: None,
                did_you_mean: Vec::new(),
                expected: String::new(),
                got: String::new(),
                extra: serde_json::Map::new(),
            })
        }
        Decision::Approve => {
            let descriptor = ApprovalDescriptor::new(
                ctx.what,
                ctx.builtin,
                ctx.targets.clone(),
                ctx.blast_radius.clone(),
                ctx.reversible,
            )
            .map_err(|e| ic_refusal(ctx.builtin, e))?;
            if is_token_approved(&descriptor.token) {
                let _ = audit(
                    ctx.builtin,
                    ctx.effect,
                    "approved",
                    &resource,
                    json!({ "token": descriptor.token }),
                );
                Ok(())
            } else {
                let _ = audit(
                    ctx.builtin,
                    ctx.effect,
                    "needs_approval",
                    &resource,
                    json!({ "token": descriptor.token }),
                );
                let token = descriptor.token.clone();
                let hint = approval_refusal_hint(&token, ctx.effect == Effect::Network);
                Err(SafetyError {
                    code: ErrorCode::NeedsApproval,
                    message: format!("{}: requires approval ({})", ctx.builtin, ctx.what),
                    builtin: ctx.builtin.to_string(),
                    hint,
                    approval: Some(descriptor),
                    did_you_mean: Vec::new(),
                    expected: String::new(),
                    got: String::new(),
                    extra: serde_json::Map::new(),
                })
            }
        }
    }
}

// ════════════════════════════════════════════════════════════════════════
// Central enforcement
// ════════════════════════════════════════════════════════════════════════
//
// `effect_of` is an *advertisement*; `guard` is the *control*. Until 7.1.0 only
// 51 of ~1,300 builtins reached the control, so 6.0.0's classification of 306
// process-spawning builtins improved what the ontology told an agent without
// changing what the shell would let one do. An agent that reads `x-effect` and
// respects it was protected; an agent that simply called the tool was not.
//
// `guard_dispatch` closes that at the dispatcher, which is the one place every
// builtin already passes through.

/// Builtins that enforce policy themselves. They are skipped centrally so a
/// single action is not admitted twice — double-guarding would charge the
/// resource governor twice and write two audit entries for one call.
///
/// "Enforces itself" means calling a `guard_*` helper **or** consulting the
/// approval system directly. That second form is not a technicality: `apply`
/// gates a whole plan on one plan-derived token, checks the jail per operation,
/// and snapshots into a transaction. Guarding it centrally as a generic `Exec`
/// demanded a *second*, unrelated token and pre-empted the `needs_approval`
/// response that carries the plan token — turning a working approval flow into
/// a dead end. Found by `tests/transactions.rs`, which is why the detector reads
/// for approval checks and not merely for the word `guard`.
///
/// Hand-written, and verified against the source by
/// `tests/guard_enforcement.rs`, so it cannot drift as call sites are added or
/// removed.
pub const SELF_GUARDED: &[&str] = &[
    "age_decrypt",
    "age_encrypt",
    "age_keygen",
    "agent_with_mcp",
    "apply",
    "at_remove",
    "at_schedule",
    "bat_view",
    "bzip2_compress",
    "bzip2_decompress",
    "cd",
    "cloud_instance_destroy",
    "code_format",
    "cron_add",
    "cron_disable",
    "cron_enable",
    "cron_remove",
    "db_csv_to_sqlite",
    "db_kv_delete",
    "db_sqlite_backup",
    "db_sqlite_create",
    "db_sqlite_delete",
    "db_sqlite_drop_table",
    "db_sqlite_to_csv",
    "docker_compose_down",
    "docker_exec",
    "docker_rm",
    "file_append",
    "file_backup",
    "file_copy",
    "file_delete_lines",
    "file_diff",
    "file_edit",
    "file_insert",
    "file_mkdir",
    "file_move",
    "file_patch",
    "file_write",
    "fs_chmod",
    "fs_chown",
    "fs_link",
    "fs_symlink",
    "git_ignore",
    "gpg_decrypt",
    "gpg_encrypt",
    "gui_ocr",
    "gui_screenshot",
    "gui_screenshot_window",
    "gzip_compress",
    "gzip_decompress",
    "http_get",
    "json_set",
    "k8s_delete",
    "k8s_exec",
    "ltrace_cmd",
    "marketplace_info",
    "marketplace_search",
    "marketplace_update",
    "nc_listen",
    "net_close",
    "net_connect",
    "net_listen",
    "net_recv",
    "net_send",
    "openssl_genrsa",
    "pager",
    "perf_record",
    "perf_stat",
    "perm_set",
    "platform_db_delete",
    "platform_db_export",
    "podman_exec",
    "podman_rm",
    "proc_kill",
    "proc_spawn",
    "project_scripts",
    "rbac_principal",
    "refactor_rename_file",
    "repl_connect",
    "repl_serve",
    "rlm_spawn",
    "rm",
    "rmdir",
    "save_json",
    "scp_download",
    "sed_replace",
    "session_export",
    "sh",
    "ssh_exec",
    "ssh_keygen",
    "strace_cmd",
    "tar_create",
    "tar_extract",
    "tee_output",
    "terraform_destroy",
    "timeout_cmd",
    "tmux_new",
    "tmux_send",
    "tool_exec",
    "touch",
    "web_check_url",
    "web_cookies",
    "web_download",
    "web_fetch",
    "web_form_submit",
    "web_graphql",
    "web_headers",
    "web_json_get",
    "web_json_post",
    "web_open_url",
    "web_post",
    "web_rest_api",
    "web_scrape",
    "web_upload_file",
    "wget_download",
    "xargs_exec",
    "xz_compress",
    "xz_decompress",
    "zip_add",
    "zip_create",
    "zip_extract",
    "zstd_compress",
    "zstd_decompress",
];

/// Whether an effect is one the policy table can refuse.
///
/// Only these are enforced centrally. In agent mode `WriteLocal` and `Network`
/// already decide to `Allow`, so guarding them here would change no decision
/// while doubling their audit and governor accounting — cost without safety.
/// They stay with the hand-written call sites, which know their real targets.
fn centrally_enforced(effect: Effect) -> bool {
    matches!(
        effect,
        Effect::Process
            | Effect::Destructive
            | Effect::Exec
            | Effect::Privileged
            // `Network` was not here, and `IRONSHELL_MAX_NET` therefore governed
            // only the builtins that happened to call `guard_network`
            // themselves. Measured on 2026-09-22: of 57 builtins classified
            // `Network`, 53 were never charged. Under `--agent --policy strict`
            // with `IRONSHELL_MAX_NET=0`, `scp_upload` invoked `scp` (it failed
            // only because the local file was absent), `git_fetch` ran, and
            // `host_lookup` resolved. `http_get` was refused, which is why the
            // hole was invisible: the builtin everyone tests was the one that
            // worked.
            //
            // Safe to add because `Network` decides `Allow` in agent mode, so
            // this changes no policy outcome -- it only routes the call through
            // `guard`, which charges the governor and audits. The 19 builtins
            // that call `guard_network` are all in `SELF_GUARDED`, which
            // `guard_dispatch` checks *first*, so none is charged twice.
            | Effect::Network
    )
}

/// Declared parameter names whose argument names a path or a host. Only these
/// reach the audit log for a call the gate does not judge.
const TARGET_PARAMS: &[&str] = &[
    "path",
    "file",
    "filename",
    "file_path",
    "source",
    "destination",
    "dest",
    "target",
    "url",
    "host",
    "hostname",
];

/// The audit resource for a call the gate does not judge: the arguments that
/// the signature declares as paths or hosts, with a count in place of the rest.
/// Content arguments (the text a write puts in a file, a request body) are never
/// named, because the log outlives the call and would keep its secrets.
fn target_resource(builtin: &str, args: &[crate::value::Value]) -> String {
    let named: Vec<&str> = crate::signature::signature_of(builtin)
        .map(|sig| {
            sig.params
                .iter()
                .enumerate()
                .filter(|(_, p)| !p.variadic && TARGET_PARAMS.contains(&p.name))
                .filter_map(|(i, _)| match args.get(i) {
                    Some(crate::value::Value::Str(s)) => Some(s.as_str()),
                    _ => None,
                })
                .collect()
        })
        .unwrap_or_default();
    let rest = args.len() - named.len();
    match (named.is_empty(), rest) {
        (true, 0) => String::new(),
        (true, n) => format!("<{n} arguments>"),
        (false, 0) => named.join(", "),
        (false, n) => format!("{}, <{n} more arguments>", named.join(", ")),
    }
}

/// Enforce policy for a builtin that does not guard itself. Called from the
/// dispatcher immediately before a builtin runs.
///
/// The targets are the call's string arguments, which is the best a central
/// point can do: it cannot know which of them are paths.
///
/// The jail is applied to the subset it *can* be sure about — arguments that
/// name a path which already exists on disk. A string that resolves to a real
/// file or directory is a path by observation rather than by guesswork, and a
/// mutating call naming one outside the workspace is exactly what the jail is
/// for. Anything else (a subcommand, a container name, a SQL fragment, a path
/// that does not yet exist) is left to the hand-written call sites, which know
/// their arguments' meaning. That asymmetry is deliberate: a missed jail check
/// is a gap the call sites still cover, while a false one rejects a legitimate
/// call and has no workaround.
pub fn existing_paths(args: &[String]) -> Vec<String> {
    args.iter()
        .filter(|s| {
            !s.is_empty()
                && s.len() <= 4096
                && !s.contains('\n')
                && !names_a_remote_share(s)
                && std::path::Path::new(s).exists()
        })
        .cloned()
        .collect()
}

/// Whether asking if `s` exists would reach another machine. On Windows a
/// string that begins with two separators is a UNC or device path, and
/// `exists()` on `\\host\share` opens an SMB session to `host`: a 48 s stall
/// for an XPath such as `//p/text()`, and for `\\attacker\x` an NTLM
/// handshake offered to whoever runs `attacker`, before any policy decision.
/// Such a string is not evidence of a local path, so it is never probed; the
/// call sites that know an argument is a path still jail it.
pub fn names_a_remote_share(s: &str) -> bool {
    let b = s.as_bytes();
    cfg!(windows) && b.len() >= 2 && matches!(b[0], b'/' | b'\\') && matches!(b[1], b'/' | b'\\')
}
/// Declared parameter names whose argument is a credential.
const CREDENTIAL_PARAMS: &[&str] = &["password", "private_key", "token"];

/// `args` with every argument in a credential position replaced by
/// [`REDACTION_MARKER`], or `None` when the builtin declares no such position
/// or the call does not reach one.
fn without_credentials(
    builtin: &str,
    args: &[crate::value::Value],
) -> Option<Vec<crate::value::Value>> {
    let sig = crate::signature::signature_of(builtin)?;
    let mut out: Option<Vec<crate::value::Value>> = None;
    for (i, p) in sig.params.iter().enumerate() {
        if i < args.len() && CREDENTIAL_PARAMS.contains(&p.name) {
            out.get_or_insert_with(|| args.to_vec())[i] =
                crate::value::Value::Str(REDACTION_MARKER.to_string());
        }
    }
    out
}

lazy_static! {
    /// Every alias that reaches a self-guarding implementation under another
    /// spelling, mapped to the spelling the body guards under.
    ///
    /// The dispatcher used to judge `mv` as `mv`, while the body it reached
    /// (`file_move`, same dispatch index) judged as `file_move`. The approval
    /// token names the builtin, so the refusal's token could never admit the
    /// retry, and the jail was only checked by the body, after the central
    /// approval had already issued a token for an outside target. Judging the
    /// alias under the name its body guards under makes the two agree by
    /// construction. Built from `builtins::alias_groups`, like `INHERITED_EFFECT`,
    /// so a new alias cannot drift from its implementation.
    static ref GUARDED_UNDER: std::collections::HashMap<&'static str, &'static str> = {
        let mut map = std::collections::HashMap::new();
        for group in crate::builtins::alias_groups() {
            let Some(canonical) = group.iter().copied().find(|n| SELF_GUARDED.contains(n)) else {
                continue;
            };
            for name in group {
                if !SELF_GUARDED.contains(&name) {
                    map.insert(name, canonical);
                }
            }
        }
        map
    };
}

pub fn guard_dispatch(builtin: &str, args: &[crate::value::Value]) -> Result<(), SafetyError> {
    // An alias whose implementation guards itself is judged under the body's own
    // name, so the token the dispatcher would name is the one the body demands.
    let builtin = GUARDED_UNDER.get(builtin).copied().unwrap_or(builtin);
    let effect = effect_of(builtin);
    // `Pure` and `ReadLocal` are neither centrally enforced nor audited, so
    // every path below ends in `Ok(())` for them. They are most calls, and
    // this used to copy every string argument first -- a piped document
    // included -- before finding out.
    if matches!(effect, Effect::Pure | Effect::ReadLocal) {
        return Ok(());
    }
    // A credential passed by position must not become an audit target or part
    // of the logged descriptor: `rbac_login(user, password)` wrote the password
    // into the hash-chained audit log. `redact_str` catches secret *shapes*, and
    // a password has none; the declared parameter name is the evidence.
    let redacted = without_credentials(builtin, args);
    let args = redacted.as_deref().unwrap_or(args);
    let args_as_strings: Vec<String> = args
        .iter()
        .filter_map(|a| match a {
            crate::value::Value::Str(s) => Some(s.clone()),
            _ => None,
        })
        .collect();
    if SELF_GUARDED.contains(&builtin) {
        return Ok(());
    }
    if !centrally_enforced(effect) {
        // Containment is not the policy decision, and conflating the two left the
        // jail reaching 8 of the 119 `WriteLocal` builtins.
        //
        // The original reasoning here was that `WriteLocal` and `Network` decide
        // `Allow`, so there is no decision to make and nothing to do but audit.
        // That is true about the *policy* and beside the point about the *jail*,
        // which lives inside `guard` and is therefore skipped by this early
        // return. §5.3 promises `WriteLocal` is "jailed to workspace"; in
        // practice only the eight builtins that guard themselves were, and
        // `copy_file` would overwrite a file outside the workspace that
        // `file_write` was refused for — demonstrated, then fixed here.
        //
        // Scope, stated precisely because the restriction is load-bearing: this
        // judges only arguments naming a path that *already exists*, exactly as
        // the centrally-enforced branch below does. A string that resolves to a
        // real file is a path by observation; one that does not may be a
        // container name, a subcommand or a SQL fragment, and refusing those
        // would break legitimate calls with no workaround. So creating a *new*
        // file outside the workspace is still the call site's job — what this
        // catches is overwriting something already there, which is the half that
        // can damage a system rather than litter it.
        // A central jail for `WriteLocal` was tried here and reverted, and the
        // reason is worth keeping so it is not tried again.
        //
        // The gap is real: `guard` holds the jail, this early return skips it, and
        // §5.3 promises `WriteLocal` is "jailed to workspace" — so `copy_file`
        // would overwrite a file outside the workspace that `file_write` was
        // refused for. Demonstrated in `tests/writelocal_jail.rs`.
        //
        // The obvious fix — run the jail over `existing_paths(&args)` here, as the
        // centrally-enforced branch does — was implemented, and then measured:
        // it refuses `copy_file <outside-source> <inside-destination>`, which is
        // copying a file *into* the workspace. That is a legitimate call. Reading
        // from outside is allowed by policy (`ReadLocal` is unjailed) and the
        // write lands inside the jail, so refusing it is a false positive with no
        // workaround — precisely what the comment below warns about.
        //
        // The two cases are indistinguishable from here: both are "a `WriteLocal`
        // call naming an existing path outside the workspace". Only the call site
        // knows which of its arguments is the destination. So the jail stays at
        // call sites, and `tests/writelocal_jail.rs` measures how many builtins
        // have one rather than assuming they all do.
        //
        // "Allowed" and "unobserved" are different things, and until this these
        // left no trace at all. Record them so an agent session can be
        // reconstructed afterwards, which is most of what an audit log is for.
        //
        // Agent surface only: a human REPL should not pay a log write per file
        // write, and its actions were never gated to begin with.
        if matches!(effect, Effect::WriteLocal | Effect::Network) && current_mode() == Mode::Agent {
            let _ = audit(
                builtin,
                effect,
                "allow_unguarded",
                &target_resource(builtin, args),
                json!({ "central": true }),
            );
        }
        return Ok(());
    }
    // Jail only what is demonstrably a path. `guard` applies the workspace
    // check when `fs_paths` is set, so the targets handed to it in that case
    // must all be real paths — otherwise a container name or a subcommand would
    // be judged "outside the workspace" and the call refused for no reason.
    let real_paths = existing_paths(&args_as_strings);
    let jailable = effect.is_filesystem() && !real_paths.is_empty();
    let targets = if jailable {
        real_paths
    } else {
        args_as_strings
    };
    // The approval token is a hash of the descriptor, so whatever distinguishes
    // two calls must appear in it. Passing only the *string* arguments meant
    // `git_clean(true)` (dry run) and `git_clean(false)` (deletes untracked
    // files) produced an identical token: approving the harmless preview
    // silently authorised the destructive call, which is the exact opposite of
    // what content-binding is for. Every argument goes in, typed.
    let argv = serde_json::to_value(args).unwrap_or(Json::Null);
    // The approval named only the prompt. An `ai` call also sends the gateway key
    // to a destination, so the descriptor (and therefore the token) carries it.
    let mut blast_radius = json!({ "args": argv });
    if builtin == "ai" {
        if let Some(destination) = crate::ai::ai_gate_destination() {
            blast_radius["destination"] = json!(destination);
        }
    }
    guard(GuardCtx {
        builtin,
        effect,
        what: effect.as_str(),
        targets,
        blast_radius,
        // Honest rather than optimistic: a journalled file write can be rewound,
        // but this path covers process/exec/destructive classes whose effects
        // reach outside the filesystem, and claiming reversibility would make an
        // approval prompt read as safer than it is.
        reversible: false,
        fs_paths: jailable,
    })
}

// ════════════════════════════════════════════════════════════════════════
// Secret hygiene (§7.6)
// ════════════════════════════════════════════════════════════════════════
//
// Two complementary defenses, both deterministic:
//
// 1. **Shape redaction** — `redact_str` scrubs known secret *shapes* (API-key
//    prefixes, JWTs, AWS access-key ids, PEM private-key blocks, URL credentials,
//    and `key=secret` assignment forms) from any text. Applied to agent output
//    (`builtins::render_agent`) and to every audit entry, so a secret that flows
//    through a result or a guarded call's metadata never lands in the agent's
//    context window or the persistent, hash-chained audit log.
// 2. **Name gating** — `env_secret_gated` reports whether reading an env var by a
//    secret-denoting name (`*_KEY`, `*TOKEN*`, `*SECRET*`, …) should be replaced
//    with an opaque `[REDACTED:NAME]` handle *before* the value ever enters the
//    program's value space. Active only in agent mode and only when the value
//    isn't explicitly permitted (`IRONSHELL_SECRETS=allow`).
//
// All of this is opt-out via `IRONSHELL_REDACT=off` for trusted automation; human
// mode keeps full fidelity (the gate is agent-only; render redaction runs on the
// agent render path only).

/// The marker substituted for a redacted secret. ASCII + bracketed to match the
/// house style (`[PATH]`, `[SECURITY WARNING]`) and to tokenize cheaply.
pub const REDACTION_MARKER: &str = "[REDACTED]";

lazy_static! {
    /// Self-contained secret tokens — the whole match *is* the secret and is
    /// replaced wholesale. Ordered alternation; each branch is anchored on a
    /// distinctive prefix/structure so it can't fire on ordinary prose.
    static ref SECRET_TOKEN_RE: regex::Regex = regex::Regex::new(concat!(
        r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----",
        r"|eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}", // JWT
        r"|AKIA[0-9A-Z]{16}",                                                 // AWS access key id
        r"|sk-(?:ant-)?[A-Za-z0-9_-]{16,}",                                   // OpenAI / Anthropic
        r"|gh[pousr]_[A-Za-z0-9]{20,}",                                       // GitHub PAT/OAuth
        r"|xox[baprs]-[A-Za-z0-9-]{10,}",                                     // Slack
        r"|AIza[0-9A-Za-z_-]{20,}",                                           // Google API key
        r"|[rs]k_(?:live|test)_[A-Za-z0-9]{16,}",                             // Stripe
        r"|\bhf_[A-Za-z0-9]{30,}",                                            // Hugging Face
        r"|github_pat_[A-Za-z0-9_]{22,}",                                     // GitHub fine-grained PAT
        r"|glpat-[A-Za-z0-9_-]{20,}",                                         // GitLab PAT
    )).unwrap();

    /// Secret-named URL query parameters: `?key=…`, `&token=…`. Only a `?` or `&`
    /// before the name counts, so prose such as "the key=value syntax" is left
    /// alone. Group 1 (the name and `=`) is kept; the value is redacted.
    static ref URL_QUERY_SECRET_RE: regex::Regex = regex::Regex::new(
        r#"(?i)([?&](?:api[_-]?key|apikey|access[_-]?token|access[_-]?key|token|key|secret|password|passwd|pwd)=)([^&\s#"'<>]{6,})"#
    ).unwrap();

    /// URL credentials: `scheme://user:password@host` — redact only the password,
    /// keeping the scheme/user/host so the result stays diagnostic.
    static ref URL_CRED_RE: regex::Regex =
        regex::Regex::new(r"([a-zA-Z][a-zA-Z0-9+.\-]*://[^/\s:@]+:)([^/\s:@]+)(@)").unwrap();

    /// `key = secret` / `key: secret` assignment forms (case-insensitive key,
    /// value ≥6 chars to skip trivial placeholders). Group 1 (key + separator)
    /// is kept; group 2 (the value) is redacted.
    static ref SECRET_ASSIGN_RE: regex::Regex = regex::Regex::new(
        // A backslash ends the value when it begins a JSON escape (`\n`, `\t`,
        // `\"`, `\\`, `\u`...): in JSON text a newline is the two characters `\n`,
        // and a value that ran through it swallowed the next line. A backslash
        // before any other character is still part of the value, so a Windows
        // path or a password containing `\x` stays whole.
        r#"(?i)((?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|client[_-]?secret|auth[_-]?token)["']?\s*[:=]\s*["']?)((?:[^\s"',}\\]|\\[^nrtbfu"\\/\s]){6,})"#
    ).unwrap();
}

/// Whether secret redaction is active. On by default; `IRONSHELL_REDACT=off`
/// (or `0`/`false`/`no`) disables it for trusted automation.
pub fn redaction_enabled() -> bool {
    !matches!(
        std::env::var("IRONSHELL_REDACT").ok().as_deref(),
        Some("off") | Some("0") | Some("false") | Some("no")
    )
}

/// Whether the caller has explicitly permitted reading secret-named env vars in
/// the clear (`IRONSHELL_SECRETS=allow`). Defaults to denied in agent mode.
pub fn secrets_permitted() -> bool {
    matches!(
        std::env::var("IRONSHELL_SECRETS").ok().as_deref(),
        Some("allow") | Some("1") | Some("true")
    )
}

/// Whether an env-var name denotes a secret. Conservative substring match
/// (uppercased) on strong indicators only — `KEY` alone is excluded to avoid
/// `KEYBOARD`/`MONKEY` false positives; `_KEY` requires the underscore.
pub fn is_secret_name(name: &str) -> bool {
    let n = name.to_ascii_uppercase();
    const NEEDLES: &[&str] = &[
        "SECRET",
        "TOKEN",
        "PASSWORD",
        "PASSWD",
        "PASSPHRASE",
        "_KEY",
        "APIKEY",
        "API_KEY",
        "ACCESS_KEY",
        "PRIVATE_KEY",
        "CREDENTIAL",
        "CLIENT_SECRET",
        "AUTH_TOKEN",
        "SESSION_KEY",
    ];
    // Suffixes, not substrings: `_AUTH` inside `GIT_AUTHOR_NAME` and `_PAT`
    // inside `LD_LIBRARY_PATH` are not secrets.
    const SUFFIXES: &[&str] = &["_PAT", "_CREDS", "_CREDENTIALS", "_AUTH"];
    NEEDLES.iter().any(|needle| n.contains(needle)) || SUFFIXES.iter().any(|s| n.ends_with(s))
}

/// Whether reading the env var `name` should be replaced with an opaque handle:
/// agent mode, redaction enabled, the name denotes a secret, and the operator
/// has not explicitly permitted clear reads. Human mode is never gated (a person
/// at a REPL reading their own env is legitimate and wants the value).
pub fn env_secret_gated(name: &str) -> bool {
    current_mode() == Mode::Agent
        && redaction_enabled()
        && !secrets_permitted()
        && is_secret_name(name)
}

/// Whether the environment variable `name` steers a child program, the code
/// loaded into it, its configuration or credentials, or the network destination
/// of the data it is given. An agent may not change such a variable.
///
/// Matched case-insensitively, as Windows matches names. Exact names decide
/// which program runs (`PATH`, `PATHEXT`, `COMSPEC`), what it reads as home and
/// configuration (`HOME`, `APPDATA`, `GIT`, `KUBECONFIG`), and which startup
/// file or interpreter path it loads (`BASH_ENV`, `NODE_OPTIONS`, `PYTHONPATH`).
/// Prefixes cover whole families: the shell's and the gateway's own settings,
/// the git, loader (`LD_`, `DYLD_`) and toolchain families. Suffixes cover
/// proxies (`HTTP_PROXY`, `https_proxy`) and every provider endpoint or key.
pub(crate) fn env_name_steers_children(name: &str) -> bool {
    const EXACT: &[&str] = &[
        "PATH",
        "PATHEXT",
        "HOME",
        "USERPROFILE",
        "HOMEDRIVE",
        "HOMEPATH",
        "APPDATA",
        "LOCALAPPDATA",
        "COMSPEC",
        "SYSTEMROOT",
        "IFS",
        "BASH_ENV",
        "ENV",
        "ZDOTDIR",
        "SHELL",
        "PAGER",
        "EDITOR",
        "VISUAL",
        "BROWSER",
        "PYTHONPATH",
        "PYTHONSTARTUP",
        "PYTHONHOME",
        "NODE_OPTIONS",
        "NODE_PATH",
        "PERL5LIB",
        "PERL5OPT",
        "RUBYOPT",
        "RUBYLIB",
        "CURL_HOME",
        "WGETRC",
        "SSH_ASKPASS",
        "SUDO_ASKPASS",
        "SSH_AUTH_SOCK",
        "SSL_CERT_FILE",
        "SSL_CERT_DIR",
        "REQUESTS_CA_BUNDLE",
        "NODE_EXTRA_CA_CERTS",
        "DOCKER_HOST",
        "DOCKER_CONFIG",
        "KUBECONFIG",
        "GNUPGHOME",
        "MANPAGER",
        "GIT",
    ];
    const PREFIXES: &[&str] = &[
        "IRONSHELL_",
        "IRONGATE_",
        "GIT_",
        "LD_",
        "DYLD_",
        "XDG_",
        "CARGO_",
        "RUSTC_",
        "NPM_CONFIG_",
        "PIP_",
    ];
    const SUFFIXES: &[&str] = &[
        "_PROXY",
        "_API_KEY",
        "_TOKEN",
        "_BASE_URL",
        "_API_BASE",
        "_ENDPOINT",
    ];
    let upper = name.to_ascii_uppercase();
    EXACT.contains(&upper.as_str())
        || PREFIXES.iter().any(|p| upper.starts_with(p))
        || SUFFIXES.iter().any(|s| upper.ends_with(s))
}

/// Whether this process must refuse to change the variable `name`: agent mode,
/// and a name that [`env_name_steers_children`] classes as steering.
pub(crate) fn env_change_refused(name: &str) -> bool {
    current_mode() == Mode::Agent && env_name_steers_children(name)
}

/// Refuse to read the clipboard's contents in agent mode unless the operator
/// permits clear secret reads (`IRONSHELL_SECRETS=allow`) or the policy is
/// permissive. A clipboard often holds a password copied from a password
/// manager, and a bare password has no shape for redaction to recognise.
/// Listing the clipboard's types reads no contents and is not gated.
pub fn clipboard_read_gate(builtin: &str) -> anyhow::Result<()> {
    if current_mode() == Mode::Agent && !policy_permissive() && !secrets_permitted() {
        return Err(policy_deny(
            builtin,
            "agent mode does not read the clipboard, which often holds a password \
             that redaction cannot recognise; NOTHING WAS READ",
            "set IRONSHELL_SECRETS=allow to permit it, or pass the text as an argument",
        ));
    }
    Ok(())
}

/// Redact known secret shapes from a string. Returns the scrubbed string and
/// whether anything changed. Deterministic; each pass only ever *replaces* a
/// secret with [`REDACTION_MARKER`], never inflates non-secret text.
pub fn redact_str(s: &str) -> (String, bool) {
    let mut cur = s.to_string();
    let mut changed = false;
    if SECRET_TOKEN_RE.is_match(&cur) {
        cur = SECRET_TOKEN_RE
            .replace_all(&cur, REDACTION_MARKER)
            .into_owned();
        changed = true;
    }
    if URL_CRED_RE.is_match(&cur) {
        cur = URL_CRED_RE
            .replace_all(&cur, concat!("${1}", "[REDACTED]", "${3}"))
            .into_owned();
        changed = true;
    }
    if SECRET_ASSIGN_RE.is_match(&cur) {
        let mut replaced = false;
        cur = SECRET_ASSIGN_RE
            .replace_all(&cur, |caps: &regex::Captures| {
                let value = &caps[2];
                let word = value.trim_end_matches(')');
                // `token: String) -> Record` is a signature, which describes a
                // secret without holding one. The shape cannot tell the two
                // apart, so a value that is a signature type name is left.
                if crate::signature::Ty::is_type_name(word) {
                    return caps[0].to_string();
                }
                // An approval handle must be echoed back, and is no secret
                // (see `is_capability_token`); hiding it made the approval
                // `ish -b` prints unusable.
                if is_capability_token(word) {
                    return caps[0].to_string();
                }
                // `DEPLOY_TOKEN: DEPLOY_TOKEN must be set` names a variable
                // that holds a secret; the name itself is not one.
                if names_secret_variable(word) {
                    return caps[0].to_string();
                }
                replaced = true;
                // The pattern swallows a closing paren after the value; put it back.
                format!("{}[REDACTED]{}", &caps[1], &value[word.len()..])
            })
            .into_owned();
        changed |= replaced;
    }
    if URL_QUERY_SECRET_RE.is_match(&cur) {
        cur = URL_QUERY_SECRET_RE
            .replace_all(&cur, concat!("${1}", "[REDACTED]"))
            .into_owned();
        changed = true;
    }
    (cur, changed)
}

/// Whether `word` is the name of a variable that holds a secret (`GITHUB_TOKEN`,
/// `$DB_PASSWORD`), as opposed to a secret: upper-case words joined by `_`,
/// with a secret-sounding name. A credential is not spelled that way.
fn names_secret_variable(word: &str) -> bool {
    let name = word.strip_prefix('$').unwrap_or(word);
    name.contains('_')
        && name.starts_with(|c: char| c.is_ascii_uppercase())
        && name
            .chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
        && is_secret_name(name)
}

/// Recursively redact secret shapes from a JSON value in place: every string
/// leaf is shape-scrubbed, and any object member whose *key* denotes a secret
/// is replaced with the marker even if its value isn't shape-matched. Used to
/// keep secrets out of the persistent audit log.
/// Whether a string is an approval or plan **capability handle** rather than a
/// credential.
///
/// `apv_…`/`apl_…` are content hashes the caller is required to echo back. They
/// are not secret — anyone who knows the action can recompute one — and hiding
/// them breaks the flows that depend on them: `plan()` returned an unusable
/// `token` field, and an audit entry saying `needs_approval` with the token
/// blanked cannot be correlated with the grant that followed it.
///
/// Shared by both redaction layers (`redact_json` here, `redact_field_map` in
/// `builtins`) so the two cannot drift apart.
pub fn is_capability_token(s: &str) -> bool {
    s.starts_with("apv_") || s.starts_with("apl_")
}

pub fn redact_json(v: &mut Json) {
    match v {
        Json::String(s) => {
            let (r, changed) = redact_str(s);
            if changed {
                *s = r;
            }
        }
        Json::Array(items) => {
            for it in items.iter_mut() {
                redact_json(it);
            }
        }
        Json::Object(map) => {
            for (k, val) in map.iter_mut() {
                // Only a *string* under a secret-sounding name can be a secret.
                // `TOKEN` matches `full_tokens`/`page_tokens`, which are counts,
                // and blanking a number destroys information for no gain.
                let hide =
                    is_secret_name(k) && matches!(val, Json::String(s) if !is_capability_token(s));
                if hide {
                    *val = Json::String(REDACTION_MARKER.to_string());
                } else {
                    redact_json(val);
                }
            }
        }
        _ => {}
    }
}

// ============================================================================
// Evaluation deadline
// ============================================================================
//
// Closes the residual left by finding 6a. The Agent API's request deadline
// frees the connection and the async worker, but it cannot stop the
// evaluation: dropping a `spawn_blocking` handle does not cancel the closure,
// so a wedged evaluation keeps a blocking-pool thread until it returns on its
// own. Stopping it needs cooperation from the interpreter, which is here.
//
// The language has no loop constructs — unbounded work arrives as recursion or
// as very large data — so a check at the top of `eval_expr` covers it.
//
// **What this bounds and what it does not.** It interrupts *evaluation*:
// runaway recursion and large computations. It cannot interrupt a builtin that
// is already blocking inside a syscall — `sleep 3600`, a subprocess wait, a
// network read — because those never return to the interpreter to be asked.
// That is a real remaining gap and it is the honest statement of it.

thread_local! {
    /// When evaluation must stop, if a limit is in force.
    static DEADLINE: std::cell::Cell<Option<std::time::Instant>> =
        const { std::cell::Cell::new(None) };
    /// Steps since the clock was last read.
    ///
    /// Sampling rather than reading `Instant::now()` per AST node is a
    /// precaution, not a measured optimisation — no before/after benchmark was
    /// run, and this comment previously implied one had been. A clock read is
    /// on the order of tens of nanoseconds and `eval_expr` is the interpreter's
    /// hot path, so the cost seemed worth avoiding for a deadline that does not
    /// need per-node resolution. If it ever matters, measure before tuning
    /// `DEADLINE_CHECK_INTERVAL`.
    static STEPS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// The limit, in seconds, the command line (`--timeout`, `IRONSHELL_TIMEOUT`)
/// put on this process; 0 when none. Only used to word the expiry message.
static CLI_TIMEOUT_SECS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Bound the whole run of this thread to `secs` seconds, until the guard drops.
/// The expiry message names `secs`.
pub fn enter_cli_deadline(secs: u64) -> DeadlineGuard {
    CLI_TIMEOUT_SECS.store(secs, std::sync::atomic::Ordering::Relaxed);
    enter_deadline(std::time::Duration::from_secs(secs))
}

/// How many `eval_expr` entries pass between clock reads.
const DEADLINE_CHECK_INTERVAL: u32 = 1024;

/// Clears the deadline when it goes out of scope.
///
/// A bare setter would leave the deadline set on a pooled thread, so the *next*
/// piece of work on that thread would inherit an already-expired limit and fail
/// immediately. Tying it to a scope is what makes it safe to use from a thread
/// pool at all.
pub struct DeadlineGuard {
    previous: Option<std::time::Instant>,
}

impl Drop for DeadlineGuard {
    fn drop(&mut self) {
        DEADLINE.with(|d| d.set(self.previous));
        STEPS.with(|s| s.set(0));
    }
}

/// Bound evaluation on this thread to `limit`, until the returned guard drops.
///
/// Nested calls restore the outer deadline rather than clearing it.
pub fn enter_deadline(limit: std::time::Duration) -> DeadlineGuard {
    let previous = DEADLINE.with(|d| d.get());
    DEADLINE.with(|d| d.set(Some(std::time::Instant::now() + limit)));
    STEPS.with(|s| s.set(0));
    DeadlineGuard { previous }
}

/// Limit blocking native I/O to the remaining evaluation deadline.
/// Unlike the amortized evaluator check, this checks the clock on every call.
#[cfg(feature = "native")]
pub(crate) fn bounded_io_timeout(
    builtin: &str,
    requested: std::time::Duration,
) -> anyhow::Result<std::time::Duration> {
    DEADLINE.with(|d| match d.get() {
        None => Ok(requested),
        Some(at) => {
            let remaining = at.saturating_duration_since(std::time::Instant::now());
            if remaining.is_zero() {
                Err(budget_exceeded(
                    builtin,
                    "evaluation deadline expired before socket I/O".into(),
                    "use a sufficient evaluation time limit",
                ))
            } else {
                Ok(requested.min(remaining))
            }
        }
    })
}

/// The time left before this thread's evaluation deadline, or `None` when no
/// deadline is in force. Unlike `bounded_io_timeout` this is not tied to socket
/// I/O, so it is available on every build.
pub(crate) fn remaining_deadline() -> Option<std::time::Duration> {
    DEADLINE.with(|d| {
        d.get()
            .map(|at| at.saturating_duration_since(std::time::Instant::now()))
    })
}

/// Fail if this thread's evaluation deadline has passed.
///
/// Called from `eval_expr`. Cheap by design: with no deadline set — the REPL,
/// scripts, every test — this is one thread-local read and a `None` check.
#[inline]
pub fn check_deadline() -> anyhow::Result<()> {
    // The memory budget is read at every step: one allocation can double the
    // live bytes, so the amortized clock interval below would be too coarse.
    crate::memory::check()?;
    let n = STEPS.with(|s| {
        let n = s.get().wrapping_add(1);
        s.set(n);
        n
    });
    if !n.is_multiple_of(DEADLINE_CHECK_INTERVAL) {
        return Ok(());
    }
    DEADLINE.with(|d| match d.get() {
        Some(at) if std::time::Instant::now() >= at => Err(budget_exceeded(
            "eval",
            match CLI_TIMEOUT_SECS.load(std::sync::atomic::Ordering::Relaxed) {
                0 => "evaluation exceeded its time limit and was cancelled".to_string(),
                n => format!("evaluation exceeded the {n} s deadline"),
            },
            "make the evaluation shorter, or give it a longer time limit (--timeout SECONDS)",
        )),
        _ => Ok(()),
    })
}

// ============================================================================
// Recursion depth
// ============================================================================
//
// Finding 13: `let f = fn(x) => f(x)` overflowed the stack and *aborted the
// process*. The evaluation deadline above cannot catch that — a stack overflow
// is not a `Result`, so nothing unwinds.
//
// Two halves, and the order matters. A depth limit on its own is not a fix:
// measured on Windows debug builds the stack died at ~35 frames, so a limit low
// enough to fire (~25) would reject ordinary recursive programs, while a usable
// limit (~1000) would never fire before the stack did. So the stack is enlarged
// first (`EVAL_STACK_SIZE`, applied at the process entry point and to the
// runtime's worker threads), which is what makes `MAX_CALL_DEPTH` meaningful.

/// Stack for threads that evaluate IronShell code.
///
/// This is *reserved* address space, not committed memory — pages are backed
/// only as they are touched — so a large value costs essentially nothing on a
/// 64-bit host. Sized so that `MAX_CALL_DEPTH` is reached with a wide margin
/// even in a debug build, where frames were measured at roughly 30 KB.
pub const EVAL_STACK_SIZE: usize = 256 * 1024 * 1024;

/// Maximum nested lambda calls before evaluation is refused.
///
/// Chosen against the measured worst case rather than a round number:
/// 256 MB / ~30 KB per debug frame ≈ 8,500 frames available, so firing at 2,000
/// leaves roughly a 4× margin. Release frames are smaller, so the margin there
/// is larger still. Deep enough that realistic recursive programs are
/// unaffected; shallow enough to fire long before the stack does.
pub const MAX_CALL_DEPTH: u32 = 2_000;

thread_local! {
    static CALL_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// Decrements the call depth however the call exits, including on `?`.
pub struct CallDepthGuard;

impl Drop for CallDepthGuard {
    fn drop(&mut self) {
        CALL_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
    }
}

/// Enter one level of lambda nesting, or fail if that would go too deep.
///
/// Hold the returned guard for the duration of the call — the depth is released
/// when it drops, so an error propagating out of a nested call still unwinds
/// the count correctly.
pub fn enter_call() -> anyhow::Result<CallDepthGuard> {
    let depth = CALL_DEPTH.with(|d| {
        let n = d.get() + 1;
        d.set(n);
        n
    });
    if depth > MAX_CALL_DEPTH {
        // Release immediately; the caller gets an error, not a guard.
        CALL_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
        return Err(budget_exceeded(
            "call",
            format!(
                "recursion too deep (limit {MAX_CALL_DEPTH}) — a function is most \
                 likely calling itself without a base case"
            ),
            &format!(
                "calls nest at most {MAX_CALL_DEPTH} deep; if the recursion is intended, \
                 iterate instead with reduce over arr.range(n), or check the base case"
            ),
        ));
    }
    Ok(CallDepthGuard)
}

/// Current nesting depth. Test/diagnostic use.
pub fn current_call_depth() -> u32 {
    CALL_DEPTH.with(|d| d.get())
}

/// Run `f` on a thread with a stack large enough for deep evaluation.
///
/// Used at the process entry point so the REPL, scripts and `-c` all evaluate
/// with room for `MAX_CALL_DEPTH`. Panics are propagated so behaviour matches
/// running `f` directly — swallowing them here would turn a crash into a silent
/// wrong answer.
pub fn with_eval_stack<T, F>(f: F) -> T
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    // No inline fallback: the closure is moved into `spawn`, so it cannot be
    // reused if that fails. Spawning the first thread failing means the process
    // is out of memory or handles, where a clear abort beats limping on with a
    // small stack and overflowing later somewhere less obvious.
    let handle = std::thread::Builder::new()
        .name("ironshell-eval".into())
        .stack_size(EVAL_STACK_SIZE)
        .spawn(f)
        .expect("failed to spawn the evaluation thread");

    match handle.join() {
        Ok(v) => v,
        Err(panic) => std::panic::resume_unwind(panic),
    }
}

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

    #[test]
    fn the_hint_names_the_kind_in_the_plural() {
        for (kind, plural) in [
            ("process", "processes"),
            ("job", "jobs"),
            ("log file", "log files"),
        ] {
            let e = not_found("x", kind, "1");
            let hint = &e.downcast_ref::<SafetyError>().unwrap().hint;
            assert!(hint.contains(&format!("available {plural} and")), "{hint}");
        }
    }
}

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

    #[test]
    fn depth_is_released_when_the_guard_drops() {
        let before = current_call_depth();
        {
            let _g = enter_call().expect("first level must be allowed");
            assert_eq!(current_call_depth(), before + 1);
        }
        assert_eq!(
            current_call_depth(),
            before,
            "depth must unwind, or a long-lived thread would drift to the limit"
        );
    }

    #[test]
    fn exceeding_the_limit_is_an_error_not_a_crash() {
        let mut guards = Vec::new();
        let mut refused = false;
        for _ in 0..(MAX_CALL_DEPTH + 10) {
            match enter_call() {
                Ok(g) => guards.push(g),
                Err(e) => {
                    assert!(e.to_string().contains("recursion too deep"), "got {e}");
                    refused = true;
                    break;
                }
            }
        }
        assert!(refused, "the limit must be enforced");
        drop(guards);
        assert_eq!(current_call_depth(), 0, "depth must return to zero");
    }

    /// A refused call must not consume a level, or repeated failures would
    /// ratchet the counter down and reject progressively shallower calls.
    #[test]
    fn a_refused_call_does_not_leak_depth() {
        let mut guards = Vec::new();
        while let Ok(g) = enter_call() {
            guards.push(g);
        }
        let at_limit = current_call_depth();
        for _ in 0..5 {
            assert!(enter_call().is_err());
        }
        assert_eq!(
            current_call_depth(),
            at_limit,
            "a rejected call must leave the depth unchanged"
        );
    }
}

#[cfg(test)]
mod deadline_tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn no_deadline_means_no_interruption() {
        for _ in 0..(DEADLINE_CHECK_INTERVAL * 4) {
            check_deadline().expect("must not fail when no deadline is set");
        }
    }

    #[test]
    fn an_expired_deadline_is_reported() {
        let _g = enter_deadline(Duration::from_millis(1));
        std::thread::sleep(Duration::from_millis(20));
        // Only sampled every DEADLINE_CHECK_INTERVAL steps, so drive it there.
        let mut hit = false;
        for _ in 0..(DEADLINE_CHECK_INTERVAL * 2) {
            if check_deadline().is_err() {
                hit = true;
                break;
            }
        }
        assert!(hit, "an expired deadline must eventually stop evaluation");
    }

    #[test]
    fn a_live_deadline_does_not_fire() {
        let _g = enter_deadline(Duration::from_secs(60));
        for _ in 0..(DEADLINE_CHECK_INTERVAL * 4) {
            check_deadline().expect("a deadline far in the future must not fire");
        }
    }

    /// The guard must restore, not clear — otherwise the next task on a pooled
    /// thread inherits an expired deadline and fails for no reason.
    #[test]
    fn the_guard_restores_state_so_pooled_threads_are_not_poisoned() {
        {
            let _g = enter_deadline(Duration::from_millis(1));
            std::thread::sleep(Duration::from_millis(20));
        }
        for _ in 0..(DEADLINE_CHECK_INTERVAL * 4) {
            check_deadline().expect("deadline must not outlive its guard");
        }
    }

    #[test]
    fn nesting_restores_the_outer_deadline() {
        let _outer = enter_deadline(Duration::from_secs(60));
        {
            let _inner = enter_deadline(Duration::from_millis(1));
            std::thread::sleep(Duration::from_millis(20));
        }
        for _ in 0..(DEADLINE_CHECK_INTERVAL * 4) {
            check_deadline().expect("the outer deadline is still live and must not fire");
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn verbatim_prefix_is_stripped_only_for_a_drive_path() {
        // String-only: nothing here touches the filesystem.
        use std::path::{Path, PathBuf};
        let strip = |s: &str| super::strip_verbatim_prefix(Path::new(s));
        assert_eq!(
            strip(r"\\?\C:\Users\x\f.txt"),
            PathBuf::from(r"C:\Users\x\f.txt")
        );
        assert_eq!(strip(r"\\?\d:\x"), PathBuf::from(r"d:\x"));
        assert_eq!(strip(r"C:\Users\x"), PathBuf::from(r"C:\Users\x"));
        assert_eq!(strip(r"relative\f"), PathBuf::from(r"relative\f"));
    }

    #[test]
    fn existing_paths_never_probes_a_remote_share() {
        // Each of these, probed, opens an SMB session on Windows (about 48 s to
        // time out for a host that does not answer); none is a local path.
        let args: Vec<String> = [
            "//p/text()",
            "\\\\ae-no-such-host.invalid\\share",
            "/\\ae-no-such-host.invalid/share",
            "\\\\?\\UNC\\ae-no-such-host.invalid\\share",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        for a in &args {
            assert_eq!(names_a_remote_share(a), cfg!(windows), "{a}");
        }
        let started = std::time::Instant::now();
        let found = existing_paths(&args);
        if cfg!(windows) {
            assert!(found.is_empty(), "{found:?}");
            assert!(
                started.elapsed().as_secs() < 5,
                "probed: {:?}",
                started.elapsed()
            );
        }
        // Under an allowlist, a share is judged as a destination, not probed.
        let started = std::time::Instant::now();
        assert!(egress_permitted(&args[1..2], "example.com").is_err());
        if cfg!(windows) {
            assert!(
                started.elapsed().as_secs() < 5,
                "probed: {:?}",
                started.elapsed()
            );
        }
        // A local path is still found, and a single leading slash is not a share.
        let here = std::env::current_dir().unwrap().display().to_string();
        assert_eq!(existing_paths(&[here.clone()]), [here]);
        assert!(!names_a_remote_share("/tmp"));
        assert!(!names_a_remote_share("C:\\x"));
    }

    use super::*;

    // Env mutation in these tests is process-global; serialize them via the
    // crate-wide lock (defined at module scope, since tests in other modules
    // read `IRONSHELL_MODE` too and must take the same lock).
    use super::ENV_LOCK;

    fn clear_env() {
        for k in [
            "IRONSHELL_MODE",
            "IRONSHELL_AGENT",
            "IRONSHELL_POLICY",
            "IRONSHELL_APPROVE",
            "IRONSHELL_APPROVE_ALL",
            "IRONSHELL_WORKSPACE",
            "IRONSHELL_AUDIT_LOG",
            "IRONSHELL_AUDIT_REQUIRED",
            "IRONSHELL_MAX_OPS",
            "IRONSHELL_MAX_FILES",
            "IRONSHELL_MAX_PROCS",
            "IRONSHELL_MAX_NET",
            "IRONSHELL_TIMEOUT_MS",
        ] {
            std::env::remove_var(k);
        }
        if let Ok(mut g) = GRANTED.lock() {
            g.clear();
        }
        set_principal(None);
        clear_rbac_manager();
        governor_reset();
    }

    /// Point auditing at a unique throwaway file and reset the in-memory chain,
    /// so tests that exercise agent mode don't share or inherit chain state.
    fn isolate_audit(tag: &str) -> PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!("ae_audit_{}_{}.log", tag, std::process::id()));
        let _ = std::fs::remove_file(&p);
        std::env::set_var("IRONSHELL_AUDIT_LOG", p.to_string_lossy().to_string());
        // The audit layer resets its chain automatically when the log path
        // changes, so no manual state reset is needed here.
        p
    }

    #[test]
    fn agent_mode_refuses_a_remote_bind_unless_allowed() {
        use std::net::{IpAddr, Ipv4Addr};
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::remove_var("IRONSHELL_ALLOW_REMOTE_BIND");
        // TEST-NET-1: never assigned to a host, and nothing here is bound.
        let remote = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
        let loopback = IpAddr::V4(Ipv4Addr::LOCALHOST);
        // Human mode is unchanged: any address may be bound.
        assert!(refuse_remote_bind("nc_listen", remote).is_ok());
        std::env::set_var("IRONSHELL_MODE", "agent");
        assert!(refuse_remote_bind("nc_listen", loopback).is_ok());
        let err = refuse_remote_bind("nc_listen", remote).expect_err("agent mode refuses");
        assert!(format!("{err}").contains("in agent mode"), "{err}");
        std::env::set_var("IRONSHELL_ALLOW_REMOTE_BIND", "true");
        assert!(refuse_remote_bind("nc_listen", remote).is_ok());
        clear_env();
        std::env::remove_var("IRONSHELL_ALLOW_REMOTE_BIND");
    }

    #[test]
    fn human_mode_allows_everything() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        assert_eq!(decide(Effect::Destructive, Mode::Human), Decision::Allow);
        assert_eq!(decide(Effect::Exec, Mode::Human), Decision::Allow);
        assert_eq!(decide(Effect::Privileged, Mode::Human), Decision::Allow);
    }

    #[test]
    fn fips_mode_rejects_non_approved_hashes() {
        // Pure classifier (no env).
        assert!(is_weak_hash("md5") && is_weak_hash("MD5") && is_weak_hash("sha-1"));
        assert!(!is_weak_hash("sha256") && !is_weak_hash("sha512"));

        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        // FIPS off (default) → all algorithms pass through.
        assert!(require_fips_hash("md5").is_ok());
        // FIPS on → md5/sha1 refused, SHA-2 family allowed.
        std::env::set_var("IRONSHELL_FIPS", "1");
        assert!(require_fips_hash("md5").is_err());
        assert!(require_fips_hash("sha1").is_err());
        assert!(require_fips_hash("sha256").is_ok());
        std::env::remove_var("IRONSHELL_FIPS");
    }

    #[test]
    fn destination_hosts_are_read_from_urls_scp_and_bare_names() {
        assert_eq!(
            destination_host("https://api.example.com/v1/x?q=1").as_deref(),
            Some("api.example.com")
        );
        assert_eq!(
            destination_host("http://user:pw@Host.COM:8080/p").as_deref(),
            Some("host.com")
        );
        assert_eq!(destination_host("http://[::1]:80/").as_deref(), Some("::1"));
        assert_eq!(
            destination_host("git@github.com:org/repo.git").as_deref(),
            Some("github.com")
        );
        assert_eq!(
            destination_host("example.org:22").as_deref(),
            Some("example.org")
        );
        assert_eq!(destination_host("localhost").as_deref(), Some("localhost"));
        assert_eq!(destination_host("not a url"), None);
        assert_eq!(destination_host("--flag"), None);
        assert_eq!(destination_host("./dir/file"), None);
    }

    #[test]
    fn egress_allowlist_policy() {
        let t = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        // Exact host and subdomain match, with either separator.
        assert!(egress_permitted(&t(&["https://example.com/x"]), "example.com").is_ok());
        assert!(egress_permitted(&t(&["https://api.example.com/x"]), "example.com").is_ok());
        assert!(
            egress_permitted(&t(&["https://a.b.example.com/x"]), "foo.org; example.com").is_ok()
        );
        assert!(
            egress_permitted(&t(&["https://a.b.example.com/x"]), "foo.org,example.com").is_ok()
        );
        assert!(egress_permitted(&t(&["https://anything.test/x"]), "*").is_ok());
        // A lookalike suffix is not a subdomain.
        assert!(egress_permitted(&t(&["https://evil.com/x"]), "example.com").is_err());
        assert!(egress_permitted(&t(&["https://notexample.com/x"]), "example.com").is_err());
        // No readable destination under an allowlist is refused.
        assert!(egress_permitted(&t(&["garbage words"]), "example.com").is_err());
        // With a URL present, other arguments are payload, not hosts.
        assert!(
            egress_permitted(&t(&["https://example.com/f", "out.json"]), "example.com").is_ok()
        );
    }

    #[test]
    fn agent_mode_gates_dangerous() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        assert_eq!(decide(Effect::ReadLocal, Mode::Agent), Decision::Allow);
        assert_eq!(decide(Effect::Destructive, Mode::Agent), Decision::Approve);
        assert_eq!(decide(Effect::Exec, Mode::Agent), Decision::Approve);
        assert_eq!(decide(Effect::Privileged, Mode::Agent), Decision::Deny);
    }

    #[test]
    fn network_is_allow_in_the_table_and_approve_for_guard() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        // The table says Allow; the decision guard applies asks first.
        assert_eq!(decide(Effect::Network, Mode::Agent), Decision::Allow);
        assert_eq!(
            effective_decision(Effect::Network, Mode::Agent),
            Decision::Approve
        );
        assert_eq!(
            effective_decision(Effect::Network, Mode::Human),
            Decision::Allow
        );
        std::env::set_var("IRONSHELL_NET_ALLOW", "example.com");
        assert_eq!(
            effective_decision(Effect::Network, Mode::Agent),
            Decision::Allow
        );
        clear_env();
        std::env::set_var("IRONSHELL_POLICY", "permissive");
        assert_eq!(
            effective_decision(Effect::Network, Mode::Agent),
            Decision::Allow
        );
        clear_env();
    }

    #[test]
    fn permissive_policy_allows_all_in_agent() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_POLICY", "permissive");
        assert_eq!(decide(Effect::Destructive, Mode::Agent), Decision::Allow);
        assert_eq!(decide(Effect::Privileged, Mode::Agent), Decision::Allow);
        clear_env();
    }

    #[test]
    fn approval_token_is_bound_to_action() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        let a = ApprovalDescriptor::new(
            "delete",
            "rm",
            vec!["/x/a".into()],
            json!({"files":1}),
            false,
        )
        .unwrap();
        let b = ApprovalDescriptor::new(
            "delete",
            "rm",
            vec!["/x/b".into()],
            json!({"files":1}),
            false,
        )
        .unwrap();
        assert_ne!(
            a.token, b.token,
            "different targets must yield different tokens"
        );
        assert!(a.token.starts_with("apv_"));
    }

    #[test]
    fn chain_tag_is_hmac_sha256_over_the_canonical_core() {
        // Reference values computed outside this code (HMAC-SHA256 and SHA-256
        // over the same bytes). They pin the layout: the tag covers the exact
        // UTF-8 bytes of the core string and nothing else.
        let key = b"audit-test-key-0123456789";
        let core = r#"{"builtin":"rm","decision":"allow","mac":"hmac-sha256","seq":7,"ts":"2026-10-29T00:00:00Z"}"#;
        assert_eq!(
            chain_tag(Some(key), core).unwrap(),
            "2863021df08b3835ed91e3978034891196c7467116155ce7eb55d032443480fc"
        );
        assert_eq!(
            chain_tag(None, core).unwrap(),
            "43af3b9ad29795952251109b222ce66c9222f573a776b09c0a9e2724f799fe73"
        );
        // A different tag layout (say, the key appended, or a trailing newline)
        // would change these values, so an old audit log would stop verifying.
        assert_ne!(
            chain_tag(Some(key), &format!("{core}\n")).unwrap(),
            "2863021df08b3835ed91e3978034891196c7467116155ce7eb55d032443480fc"
        );
    }

    #[test]
    fn audit_key_id_is_the_first_16_hex_of_domain_separated_sha256() {
        let key = b"audit-test-key-0123456789";
        assert_eq!(audit_key_id(key).unwrap(), "e8fca1b737b081c3");
    }

    #[test]
    fn ic_fill_random_fills_and_is_not_constant() {
        let mut a = [0u8; 64];
        let mut b = [0u8; 64];
        ic_fill_random("test", &mut a).unwrap();
        ic_fill_random("test", &mut b).unwrap();
        assert!(a.iter().any(|&x| x != 0), "64 zero bytes from the DRBG");
        assert_ne!(a, b, "two draws must differ");
    }

    #[test]
    fn guard_blocks_then_allows_with_token() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        let log = isolate_audit("approve");
        // Use a workspace so the jail does not interfere with this approval test.
        let tmp = std::env::temp_dir();
        std::env::set_var("IRONSHELL_WORKSPACE", &tmp);
        let target = tmp
            .join("ae_safety_test_file")
            .to_string_lossy()
            .to_string();

        let mk = || GuardCtx {
            builtin: "rm",
            effect: Effect::Destructive,
            what: "delete",
            targets: vec![target.clone()],
            blast_radius: json!({"files": 1}),
            reversible: false,
            fs_paths: true,
        };

        let err = guard(mk()).unwrap_err();
        assert_eq!(err.code, ErrorCode::NeedsApproval);
        let token = err.approval.unwrap().token;

        std::env::set_var("IRONSHELL_APPROVE", &token);
        assert!(
            guard(mk()).is_ok(),
            "matching token should permit the action"
        );
        let _ = std::fs::remove_file(&log);
        clear_env();
    }

    #[test]
    fn jail_blocks_paths_outside_workspace() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        let log = isolate_audit("jail");
        let tmp = std::env::temp_dir();
        std::env::set_var("IRONSHELL_WORKSPACE", &tmp);

        let outside = if cfg!(windows) {
            "C:/Windows/System32/x"
        } else {
            "/etc/x"
        };
        let ctx = GuardCtx::new("rm", Effect::Destructive, "delete", outside);
        let err = guard(ctx).unwrap_err();
        assert_eq!(err.code, ErrorCode::OutsideWorkspace);
        let _ = std::fs::remove_file(&log);
        clear_env();
    }

    #[test]
    fn rbac_authorized_principal_bypasses_approval() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        let tmp = std::env::temp_dir();
        std::env::set_var("IRONSHELL_WORKSPACE", &tmp);
        let _log = isolate_audit("rbac");

        // Build an RBAC manager: a role granting effect:destructive, a user holding it.
        let mgr = std::sync::Arc::new(crate::auth::RbacManager::new());
        mgr.add_role(crate::auth::Role::new("destroyer").with_permission("effect:destructive"));
        let user = crate::auth::User::new("alice");
        let uid = user.id.clone();
        mgr.add_user(user).unwrap();
        mgr.assign_role(&uid, "destroyer").unwrap();
        set_rbac_manager(mgr);

        let target = tmp.join("rbac_target").to_string_lossy().to_string();
        let mk = || GuardCtx {
            builtin: "rm",
            effect: Effect::Destructive,
            what: "delete",
            targets: vec![target.clone()],
            blast_radius: json!({}),
            reversible: false,
            fs_paths: true,
        };

        // Anonymous principal → normal approval gating applies.
        set_principal(None);
        assert_eq!(guard(mk()).unwrap_err().code, ErrorCode::NeedsApproval);

        // Authorized principal → allowed without approval.
        set_principal(Some(uid.clone()));
        assert!(
            guard(mk()).is_ok(),
            "principal with effect:destructive should bypass approval"
        );

        // An unrelated principal (no such permission) is still gated.
        let other = crate::auth::User::new("bob");
        let other_id = other.id.clone();
        // bob isn't in the manager → check_permission false → defer to policy.
        set_principal(Some(other_id));
        assert_eq!(guard(mk()).unwrap_err().code, ErrorCode::NeedsApproval);

        clear_env();
    }

    #[test]
    fn audit_chain_verifies_and_detects_tampering() {
        let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        let mut log = std::env::temp_dir();
        log.push(format!("ae_audit_test_{}.log", std::process::id()));
        let _ = std::fs::remove_file(&log);
        std::env::set_var("IRONSHELL_AUDIT_LOG", log.to_string_lossy().to_string());
        // The chain resets automatically for this fresh (removed) log path.

        audit("rm", Effect::Destructive, "allow", "/x/a", json!({})).unwrap();
        audit("sh", Effect::Exec, "approved", "echo hi", json!({})).unwrap();
        audit("kill", Effect::Process, "allow", "1234", json!({})).unwrap();

        let n = verify_audit(&log).expect("clean chain verifies");
        assert_eq!(n, 3);

        // Tamper: flip a byte in the middle line's resource.
        let content = std::fs::read_to_string(&log).unwrap();
        let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
        lines[1] = lines[1].replace("echo hi", "rm -rf /");
        std::fs::write(&log, lines.join("\n")).unwrap();
        assert!(verify_audit(&log).is_err(), "tampering must be detected");

        let _ = std::fs::remove_file(&log);
        clear_env();
    }

    // ──────────────────────────────────────────────────────────────────
    // Secret hygiene (§7.6)
    // ──────────────────────────────────────────────────────────────────

    #[test]
    fn redact_str_scrubs_known_secret_shapes() {
        // Provider token prefixes.
        let (r, c) = redact_str("authorization: Bearer sk-abcdefghijklmnopqrstuvwxyz12");
        assert!(c && r.contains("[REDACTED]") && !r.contains("abcdefghij"));
        let (r, _) = redact_str("token ghp_0123456789abcdefABCDEFghijklmnop12");
        assert!(r.contains("[REDACTED]") && !r.contains("ghp_0123"));
        // AWS access key id.
        let (r, _) = redact_str("AKIAIOSFODNN7EXAMPLE in the config");
        assert!(r.contains("[REDACTED]") && !r.contains("AKIAIOSF"));
        // JWT.
        let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N";
        let (r, _) = redact_str(jwt);
        assert!(r.contains("[REDACTED]") && !r.contains("eyJzdWIi"));
        // PEM private-key block.
        let pem =
            "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA\n-----END RSA PRIVATE KEY-----";
        let (r, _) = redact_str(pem);
        assert!(r.contains("[REDACTED]") && !r.contains("MIIEpAIB"));
    }

    #[test]
    fn redact_str_scrubs_url_credentials_and_assignments() {
        let (r, _) = redact_str("postgres://admin:hunter2pass@db.internal:5432/app");
        assert!(
            r.contains("admin:[REDACTED]@") && !r.contains("hunter2pass"),
            "password redacted, scheme/user/host kept: {r}"
        );
        let (r, _) = redact_str("password = swordfish123");
        assert!(r.contains("[REDACTED]") && !r.contains("swordfish123"));
        let (r, _) = redact_str("api_key: \"abcdef123456\"");
        assert!(r.contains("[REDACTED]") && !r.contains("abcdef123456"));
    }

    #[test]
    fn redact_str_keeps_json_quotes_handles_and_variable_names() {
        // The opening quote stays, so redacted JSON still parses.
        let (r, c) = redact_str(r#"{"password":"swordfish123","n":1}"#);
        assert!(c);
        assert_eq!(r, r#"{"password":"[REDACTED]","n":1}"#);
        serde_json::from_str::<Json>(&r).expect("still JSON");
        // An approval handle must be echoed back; it is left.
        let line = r#"{"token":"apv_0123456789abcdef","what":"exec"}"#;
        assert_eq!(redact_str(line), (line.to_string(), false));
        // A variable's name is not its value.
        let msg = "deploy.sh: line 1: DEPLOY_TOKEN: DEPLOY_TOKEN must be set";
        assert_eq!(redact_str(msg), (msg.to_string(), false));
        let (r, _) = redact_str("token: $GITHUB_TOKEN");
        assert_eq!(r, "token: $GITHUB_TOKEN");
        // A mixed-case value is still a secret.
        let (r, _) = redact_str("token: Ab_Cd_EfGh123");
        assert_eq!(r, "token: [REDACTED]");
        // In JSON text a newline is the two characters `\n`. The value stops
        // there, so the second assignment is redacted on its own, not swallowed.
        let env = r#"{"x":"API_KEY=sk-test-123456789\nDB_PASSWORD=hunter2hunter2"}"#;
        let (r, c) = redact_str(env);
        assert!(c);
        assert!(r.contains(r"\nDB_PASSWORD=[REDACTED]"), "{r}");
        assert!(
            !r.contains("sk-test-123456789") && !r.contains("hunter2hunter2"),
            "{r}"
        );
        // A backslash that is not a JSON escape stays inside the value.
        let (r, _) = redact_str(r"password=ab\cdefgh");
        assert_eq!(r, "password=[REDACTED]");
    }

    #[test]
    fn redact_str_leaves_ordinary_text_untouched() {
        let plain = "the quick brown fox reads file.txt at 12:00 and exits 0";
        let (r, c) = redact_str(plain);
        assert!(!c, "no secret shape — must report unchanged");
        assert_eq!(r, plain, "ordinary prose must pass through byte-for-byte");
    }

    #[test]
    fn is_secret_name_matches_indicators_not_false_positives() {
        for yes in [
            "OPENAI_API_KEY",
            "AWS_SECRET_ACCESS_KEY",
            "GITHUB_TOKEN",
            "DB_PASSWORD",
            "ANTHROPIC_KEY",
            "client_secret",
        ] {
            assert!(is_secret_name(yes), "{yes} should be a secret name");
        }
        for no in ["PATH", "KEYBOARD", "MONKEY", "HOME", "USER", "LANG"] {
            assert!(!is_secret_name(no), "{no} must not be flagged");
        }
    }

    #[test]
    fn redact_json_scrubs_values_and_secret_named_keys() {
        let mut v = json!({
            "note": "use sk-abcdefghijklmnopqrstuvwx99 to auth",
            "API_KEY": "literally-anything",
            "nested": { "PASSWORD": "p", "ok": "plain text" },
            "list": ["ghp_0123456789abcdefABCDEFghijklmnop12", "fine"],
        });
        redact_json(&mut v);
        assert_eq!(v["API_KEY"], json!("[REDACTED]"));
        assert_eq!(v["nested"]["PASSWORD"], json!("[REDACTED]"));
        assert_eq!(v["nested"]["ok"], json!("plain text"));
        assert!(v["note"].as_str().unwrap().contains("[REDACTED]"));
        assert!(!v["note"].as_str().unwrap().contains("sk-abcdef"));
        assert_eq!(v["list"][1], json!("fine"));
        assert!(v["list"][0].as_str().unwrap().contains("[REDACTED]"));
    }

    #[test]
    fn env_secret_gated_is_agent_only_and_policy_aware() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::remove_var("IRONSHELL_REDACT");
        std::env::remove_var("IRONSHELL_SECRETS");

        // Human mode: never gated (legibility — the person reads their own env).
        assert!(!env_secret_gated("OPENAI_API_KEY"));

        // Agent mode: secret names gated, ordinary names not.
        std::env::set_var("IRONSHELL_MODE", "agent");
        assert!(env_secret_gated("OPENAI_API_KEY"));
        assert!(!env_secret_gated("HOME"));

        // Explicit permission re-opens clear reads.
        std::env::set_var("IRONSHELL_SECRETS", "allow");
        assert!(!env_secret_gated("OPENAI_API_KEY"));
        std::env::remove_var("IRONSHELL_SECRETS");

        // Global opt-out disables redaction entirely.
        std::env::set_var("IRONSHELL_REDACT", "off");
        assert!(!env_secret_gated("OPENAI_API_KEY"));

        clear_env();
        std::env::remove_var("IRONSHELL_REDACT");
    }

    // ──────────────────────────────────────────────────────────────────
    // Resource governors (§7.6)
    // ──────────────────────────────────────────────────────────────────

    #[test]
    fn governor_is_inert_in_human_mode_and_when_unset() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();

        // Human mode: even a tiny limit is ignored.
        std::env::set_var("IRONSHELL_MAX_FILES", "1");
        for _ in 0..5 {
            assert!(governor_admit(Effect::Destructive, "rm").is_ok());
        }

        // Agent mode but no limit set: unlimited.
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        for _ in 0..50 {
            assert!(governor_admit(Effect::Destructive, "rm").is_ok());
        }
        clear_env();
    }

    #[test]
    fn governor_breaches_file_and_op_budgets_independently() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        std::env::set_var("IRONSHELL_MAX_FILES", "2");

        assert!(governor_admit(Effect::WriteLocal, "file_write").is_ok());
        assert!(governor_admit(Effect::Destructive, "rm").is_ok());
        let err = governor_admit(Effect::WriteLocal, "file_write").unwrap_err();
        assert_eq!(err.code, ErrorCode::BudgetExceeded);
        assert!(err.to_json()["error"]["retryable"] == json!(false));

        // A non-file effect class is not charged to the file budget.
        assert!(governor_admit(Effect::Process, "proc_kill").is_ok());

        // Snapshot reflects the tally.
        let snap = governor_snapshot();
        assert_eq!(snap["used"]["files"], json!(3)); // attempts counted, incl. the breached one
        assert_eq!(snap["limits"]["max_files"], json!(2));

        clear_env();
    }

    #[test]
    fn governor_enforces_network_egress_budget() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        std::env::set_var("IRONSHELL_MAX_NET", "2");

        assert!(governor_admit(Effect::Network, "http_get").is_ok());
        assert!(governor_admit(Effect::Network, "web_fetch").is_ok());
        let err = governor_admit(Effect::Network, "http_get").unwrap_err();
        assert_eq!(err.code, ErrorCode::BudgetExceeded);
        assert!(err.message.contains("network-egress"));

        // A non-network effect is not charged to the egress budget.
        assert!(governor_admit(Effect::WriteLocal, "file_write").is_ok());

        let snap = governor_snapshot();
        assert_eq!(snap["used"]["net"], json!(3));
        assert_eq!(snap["limits"]["max_net"], json!(2));

        clear_env();
    }

    #[test]
    fn governor_enforces_total_op_budget_across_effects() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        std::env::set_var("IRONSHELL_MAX_OPS", "3");

        assert!(governor_admit(Effect::WriteLocal, "file_write").is_ok());
        assert!(governor_admit(Effect::Process, "proc_kill").is_ok());
        assert!(governor_admit(Effect::Exec, "sh").is_ok());
        let err = governor_admit(Effect::ReadLocal, "cat").unwrap_err();
        assert_eq!(err.code, ErrorCode::BudgetExceeded);

        clear_env();
    }

    #[test]
    fn governor_enforces_wall_clock_timeout() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        std::env::set_var("IRONSHELL_TIMEOUT_MS", "1");

        // First call starts the clock (elapsed 0 ≤ 1 → admitted).
        assert!(governor_admit(Effect::WriteLocal, "file_write").is_ok());
        std::thread::sleep(std::time::Duration::from_millis(15));
        // Now elapsed (~15ms) exceeds the 1ms budget.
        let err = governor_admit(Effect::WriteLocal, "file_write").unwrap_err();
        assert_eq!(err.code, ErrorCode::BudgetExceeded);
        assert!(err.message.contains("wall-clock"));

        clear_env();
    }

    #[test]
    fn governor_reset_starts_a_fresh_envelope() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        clear_env();
        std::env::set_var("IRONSHELL_MODE", "agent");
        std::env::set_var("IRONSHELL_MAX_OPS", "1");

        assert!(governor_admit(Effect::WriteLocal, "file_write").is_ok());
        assert!(governor_admit(Effect::WriteLocal, "file_write").is_err());
        governor_reset();
        // After reset the budget is available again.
        assert!(governor_admit(Effect::WriteLocal, "file_write").is_ok());

        clear_env();
    }

    #[cfg(windows)]
    #[test]
    fn same_existing_file_matches_hard_links_only() {
        let dir = std::env::temp_dir().join(format!("ae-fileid-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let a = dir.join("a.txt");
        let link = dir.join("link.txt");
        let other = dir.join("other.txt");
        let missing = dir.join("missing.txt");
        std::fs::write(&a, "a").unwrap();
        std::fs::hard_link(&a, &link).unwrap();
        std::fs::write(&other, "b").unwrap();

        assert!(same_existing_file(&a, &link));
        assert!(same_existing_file(&link, &a));
        assert!(!same_existing_file(&a, &other));
        assert!(!same_existing_file(&a, &missing));
        assert!(!same_existing_file(&missing, &missing));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn lock_poisoned_is_bad_state_and_names_the_builtin() {
        let err = lock_poisoned("feature_set", "the feature table");
        let se = err.downcast_ref::<SafetyError>().expect("a SafetyError");
        assert_eq!(se.code, ErrorCode::BadState);
        assert!(se.message.contains("feature_set"), "{}", se.message);
        assert_eq!(se.builtin, "feature_set");
    }

    fn lock_feature_table(m: &std::sync::Mutex<u32>) -> anyhow::Result<u32> {
        let g = m
            .lock()
            .map_err(|_| lock_poisoned("feature_set", "the feature table"))?;
        Ok(*g)
    }

    #[test]
    fn a_poisoned_mutex_maps_to_bad_state() {
        let m = std::sync::Arc::new(std::sync::Mutex::new(7u32));
        let held = std::sync::Arc::clone(&m);
        let joined = std::thread::spawn(move || {
            let _guard = held.lock().unwrap();
            panic!("poison the lock for the test");
        })
        .join();
        assert!(joined.is_err(), "the thread must have panicked");

        let err = lock_feature_table(&m).expect_err("a poisoned mutex must not lock");
        let se = err.downcast_ref::<SafetyError>().expect("a SafetyError");
        assert_eq!(se.code, ErrorCode::BadState);
        assert!(se.message.contains("feature_set"), "{}", se.message);
    }
}

#[cfg(test)]
mod mirror_and_git_install_tests {
    use super::*;
    use std::ffi::OsString;
    use std::path::PathBuf;

    fn env_of(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<OsString> {
        move |name: &str| {
            pairs
                .iter()
                .find(|(k, _)| *k == name)
                .map(|(_, v)| OsString::from(v))
        }
    }

    #[test]
    fn daemon_json_names_a_mirror_only_when_the_list_is_non_empty() {
        assert_eq!(daemon_json_mirrors("{}"), Ok(false));
        assert_eq!(
            daemon_json_mirrors(r#"{"registry-mirrors": []}"#),
            Ok(false)
        );
        assert_eq!(
            daemon_json_mirrors(r#"{"registry-mirrors": null}"#),
            Ok(false)
        );
        assert_eq!(
            daemon_json_mirrors(r#"{"registry-mirrors": ["https://mirror.example.invalid"]}"#),
            Ok(true)
        );
        assert_eq!(
            daemon_json_mirrors(r#"{"log-level": "info", "registry-mirrors": ["https://m"]}"#),
            Ok(true)
        );
    }

    #[test]
    fn daemon_json_that_does_not_parse_fails_closed() {
        assert!(daemon_json_mirrors("").is_err());
        assert!(daemon_json_mirrors("{").is_err());
        assert!(daemon_json_mirrors("[]").is_err());
        assert!(daemon_json_mirrors(r#"{"registry-mirrors": "https://m"}"#).is_err());
        assert!(daemon_json_mirrors(r#"{"registry-mirrors": {"a": 1}}"#).is_err());
    }

    #[test]
    fn registries_conf_names_a_mirror_or_a_search_list_in_use() {
        let mirror = "[[registry]]\nlocation = \"docker.io\"\n\n[[registry.mirror]]\nlocation = \"mirror.example.invalid\"\n";
        assert_eq!(registries_conf_redirects(mirror), Ok(true));
        assert_eq!(
            registries_conf_redirects("unqualified-search-registries = [\"docker.io\"]\n"),
            Ok(true)
        );
        // The v1 layout keeps its search list under [registries.search].
        assert_eq!(
            registries_conf_redirects("[registries.search]\nregistries = [\"quay.io\"]\n"),
            Ok(true)
        );
    }

    #[test]
    fn registries_conf_without_a_mirror_or_search_list_is_no_redirect() {
        assert_eq!(registries_conf_redirects(""), Ok(false));
        assert_eq!(
            registries_conf_redirects("unqualified-search-registries = []\n"),
            Ok(false)
        );
        assert_eq!(
            registries_conf_redirects("[[registry]]\nlocation = \"docker.io\"\n"),
            Ok(false)
        );
        assert_eq!(
            registries_conf_redirects("[[registry]]\nlocation = \"docker.io\"\nmirror = []\n"),
            Ok(false)
        );
    }

    #[test]
    fn registries_conf_that_does_not_parse_fails_closed() {
        assert!(registries_conf_redirects("not = [toml").is_err());
        assert!(
            registries_conf_redirects("unqualified-search-registries = \"docker.io\"\n").is_err()
        );
        assert!(registries_conf_redirects("registry = \"docker.io\"\n").is_err());
    }

    #[test]
    fn mirror_paths_follow_docker_and_containers_locations() {
        let home = PathBuf::from("/fake/home");
        let paths = container_mirror_paths(env_of(&[
            ("HOME", "/fake/home"),
            ("ProgramData", "/fake/pd"),
        ]));
        assert_eq!(
            paths,
            vec![
                (
                    MirrorConfig::DaemonJson,
                    PathBuf::from("/etc/docker/daemon.json")
                ),
                (
                    MirrorConfig::DaemonJson,
                    PathBuf::from("/fake/pd")
                        .join("docker")
                        .join("config")
                        .join("daemon.json"),
                ),
                (
                    MirrorConfig::RegistriesConf,
                    PathBuf::from("/etc/containers/registries.conf"),
                ),
                (
                    MirrorConfig::DaemonJson,
                    home.join(".docker").join("daemon.json")
                ),
                (
                    MirrorConfig::RegistriesConf,
                    home.join(".config")
                        .join("containers")
                        .join("registries.conf"),
                ),
                (
                    MirrorConfig::DaemonJson,
                    home.join(".config").join("docker").join("daemon.json"),
                ),
            ]
        );
    }

    #[test]
    fn an_unset_or_empty_variable_names_no_mirror_location() {
        let paths = container_mirror_paths(env_of(&[("HOME", ""), ("ProgramData", "")]));
        assert_eq!(
            paths,
            vec![
                (
                    MirrorConfig::DaemonJson,
                    PathBuf::from("/etc/docker/daemon.json")
                ),
                (
                    MirrorConfig::RegistriesConf,
                    PathBuf::from("/etc/containers/registries.conf"),
                ),
            ]
        );
        // HOME falls back to USERPROFILE.
        let paths = container_mirror_paths(env_of(&[("USERPROFILE", "/fake/up")]));
        assert!(paths.contains(&(
            MirrorConfig::DaemonJson,
            PathBuf::from("/fake/up")
                .join(".docker")
                .join("daemon.json"),
        )));
    }

    #[test]
    fn a_set_xdg_config_home_is_read_together_with_home_config() {
        let root = Path::new("/fake/root");
        let xdg = PathBuf::from("/fake/xdg");
        let home_config = PathBuf::from("/fake/home").join(".config");
        let paths = container_mirror_paths_at(
            &env_of(&[("HOME", "/fake/home"), ("XDG_CONFIG_HOME", "/fake/xdg")]),
            root,
        );
        for (format, path) in [
            (
                MirrorConfig::RegistriesConf,
                xdg.join("containers").join("registries.conf"),
            ),
            (
                MirrorConfig::DaemonJson,
                xdg.join("docker").join("daemon.json"),
            ),
            (
                MirrorConfig::RegistriesConf,
                home_config.join("containers").join("registries.conf"),
            ),
            (
                MirrorConfig::DaemonJson,
                home_config.join("docker").join("daemon.json"),
            ),
        ] {
            assert!(
                paths.contains(&(format, path.clone())),
                "{path:?} in {paths:?}"
            );
        }
        // The same directory named twice is listed once.
        let paths = container_mirror_paths_at(
            &env_of(&[
                ("HOME", "/fake/home"),
                ("XDG_CONFIG_HOME", "/fake/home/.config"),
            ]),
            root,
        );
        let registries = home_config.join("containers").join("registries.conf");
        let listed = paths
            .iter()
            .filter(|(f, p)| *f == MirrorConfig::RegistriesConf && *p == registries)
            .count();
        assert_eq!(listed, 1, "{paths:?}");
        // An empty XDG_CONFIG_HOME is unset: only $HOME/.config is read.
        let paths = container_mirror_paths_at(
            &env_of(&[("HOME", "/fake/home"), ("XDG_CONFIG_HOME", "")]),
            root,
        );
        assert!(paths.contains(&(MirrorConfig::RegistriesConf, registries)));
        assert!(!paths.iter().any(|(_, p)| p.starts_with(&xdg)));
    }

    #[test]
    fn a_mirror_under_home_config_is_refused_while_xdg_points_elsewhere() {
        let f = MirrorFixture::new("home_config_under_xdg");
        let xdg = [("XDG_CONFIG_HOME", f.xdg().to_string_lossy().into_owned())];
        // XDG holds a clean registries.conf, so the mirror can only be the one
        // under $HOME/.config.
        f.put(f.xdg().join("containers/registries.conf"), "");
        f.put(
            f.home().join(".config/containers/registries.conf"),
            MIRROR_CONF,
        );
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&xdg), &f.system()),
            Err(MIRROR_NAMED)
        );
        // The same for a drop-in under $HOME/.config.
        let g = MirrorFixture::new("home_config_dropin_under_xdg");
        let xdg = [("XDG_CONFIG_HOME", g.xdg().to_string_lossy().into_owned())];
        g.put(
            g.home().join(".config/containers/registries.conf.d/m.conf"),
            MIRROR_CONF,
        );
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", g.env(&xdg), &g.system()),
            Err(MIRROR_NAMED)
        );
        // Rootless docker's daemon.json under $HOME/.config.
        let h = MirrorFixture::new("home_config_docker_under_xdg");
        let xdg = [("XDG_CONFIG_HOME", h.xdg().to_string_lossy().into_owned())];
        h.put(
            h.home().join(".config/docker/daemon.json"),
            r#"{"registry-mirrors": ["https://m.example.invalid"]}"#,
        );
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", h.env(&xdg), &h.system()),
            Err(MIRROR_NAMED)
        );
    }

    /// A temp root with a system directory and a home, for the container tests.
    /// Each test names its own root, so no real `/etc` file or home is read.
    struct MirrorFixture {
        root: PathBuf,
    }

    impl MirrorFixture {
        fn new(tag: &str) -> Self {
            Self {
                root: temp_dir(tag),
            }
        }
        fn system(&self) -> PathBuf {
            self.root.join("sys")
        }
        fn home(&self) -> PathBuf {
            self.root.join("home")
        }
        fn xdg(&self) -> PathBuf {
            self.root.join("xdg")
        }
        fn put(&self, path: PathBuf, text: &str) {
            std::fs::create_dir_all(path.parent().expect("parent")).expect("fixture dir");
            std::fs::write(&path, text).expect("fixture file");
        }
        /// The environment: `HOME` is the fixture's home, plus `extra`. Nothing
        /// else is read from the real environment.
        fn env(&self, extra: &[(&str, String)]) -> impl Fn(&str) -> Option<OsString> {
            let mut pairs: Vec<(String, String)> = vec![(
                "HOME".to_string(),
                self.home().to_string_lossy().into_owned(),
            )];
            pairs.extend(extra.iter().map(|(k, v)| (k.to_string(), v.clone())));
            move |name: &str| {
                pairs
                    .iter()
                    .find(|(k, _)| k == name)
                    .map(|(_, v)| OsString::from(v))
            }
        }
    }

    impl Drop for MirrorFixture {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.root);
        }
    }

    const MIRROR_CONF: &str =
        "[[registry]]\nlocation = \"docker.io\"\n\n[[registry.mirror]]\nlocation = \"m.example.invalid\"\n";

    #[test]
    fn dropins_are_listed_in_name_order_and_only_conf_files_count() {
        let f = MirrorFixture::new("dropin_order");
        let dir = f.system().join("etc/containers/registries.conf.d");
        f.put(dir.join("b.conf"), "");
        f.put(dir.join("a.conf"), "");
        f.put(dir.join("notes.txt"), MIRROR_CONF);
        assert_eq!(
            dropin_files(&[dir.clone()]),
            Ok(vec![
                (MirrorConfig::RegistriesConf, dir.join("a.conf")),
                (MirrorConfig::RegistriesConf, dir.join("b.conf")),
            ])
        );
    }

    #[test]
    fn a_system_dropin_that_names_a_mirror_refuses_podman_and_docker_ignores_it() {
        let f = MirrorFixture::new("dropin_system");
        f.put(
            f.system()
                .join("etc/containers/registries.conf.d/mirror.conf"),
            MIRROR_CONF,
        );
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Err(MIRROR_NAMED)
        );
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&[]), &f.system()),
            Ok(())
        );
    }

    #[test]
    fn a_user_dropin_is_read_under_xdg_config_home_or_home_config() {
        let f = MirrorFixture::new("dropin_user");
        let xdg = [("XDG_CONFIG_HOME", f.xdg().to_string_lossy().into_owned())];
        f.put(
            f.xdg().join("containers/registries.conf.d/m.conf"),
            MIRROR_CONF,
        );
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&xdg), &f.system()),
            Err(MIRROR_NAMED)
        );
        // Without XDG_CONFIG_HOME the user directory is $HOME/.config, which is empty.
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Ok(())
        );
        f.put(
            f.home().join(".config/containers/registries.conf.d/m.conf"),
            MIRROR_CONF,
        );
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Err(MIRROR_NAMED)
        );
    }

    #[test]
    fn an_absent_dropin_directory_or_a_non_conf_file_is_no_mirror() {
        let f = MirrorFixture::new("dropin_absent");
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Ok(())
        );
        f.put(
            f.system()
                .join("etc/containers/registries.conf.d/notes.txt"),
            MIRROR_CONF,
        );
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Ok(())
        );
    }

    #[test]
    fn a_dropin_path_that_exists_but_cannot_be_listed_refuses() {
        let f = MirrorFixture::new("dropin_unlistable");
        // A file where the directory should be: it exists and cannot be listed.
        f.put(f.system().join("etc/containers/registries.conf.d"), "");
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Err(MIRROR_UNREADABLE)
        );
    }

    #[test]
    fn more_than_64_dropin_files_refuse_and_64_do_not() {
        let f = MirrorFixture::new("dropin_cap");
        let dir = f.system().join("etc/containers/registries.conf.d");
        for i in 0..64 {
            f.put(dir.join(format!("{i:02}.conf")), "");
        }
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Ok(())
        );
        f.put(dir.join("64.conf"), "");
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Err(MIRROR_TOO_MANY)
        );
    }

    #[test]
    fn rootless_docker_daemon_json_is_read_under_xdg_or_home_config() {
        let f = MirrorFixture::new("rootless_docker");
        let mirror_json = r#"{"registry-mirrors": ["https://m.example.invalid"]}"#;
        let xdg = [("XDG_CONFIG_HOME", f.xdg().to_string_lossy().into_owned())];
        f.put(f.xdg().join("docker/daemon.json"), mirror_json);
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&xdg), &f.system()),
            Err(MIRROR_NAMED)
        );
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&[]), &f.system()),
            Ok(())
        );
        f.put(f.home().join(".config/docker/daemon.json"), mirror_json);
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&[]), &f.system()),
            Err(MIRROR_NAMED)
        );
        // podman does not read daemon.json.
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Ok(())
        );
    }

    #[test]
    fn a_remote_docker_daemon_refuses_for_docker_only() {
        let f = MirrorFixture::new("docker_remote");
        for name in ["DOCKER_HOST", "DOCKER_CONTEXT"] {
            assert_eq!(
                runtime_mirror_refusal_at(
                    "docker_pull",
                    f.env(&[(name, "x".to_string())]),
                    &f.system()
                ),
                Err(MIRROR_REMOTE_DOCKER),
                "{name}"
            );
        }
        assert_eq!(
            runtime_mirror_refusal_at(
                "docker_pull",
                f.env(&[("DOCKER_HOST", String::new())]),
                &f.system()
            ),
            Ok(()),
            "an empty DOCKER_HOST is unset"
        );
        assert_eq!(
            runtime_mirror_refusal_at(
                "podman_pull",
                f.env(&[("DOCKER_HOST", "x".to_string())]),
                &f.system()
            ),
            Ok(()),
            "podman does not read DOCKER_HOST"
        );
    }

    #[test]
    fn a_remote_podman_engine_refuses_for_podman_only() {
        let f = MirrorFixture::new("podman_remote");
        for name in ["CONTAINER_HOST", "CONTAINER_CONNECTION"] {
            assert_eq!(
                runtime_mirror_refusal_at(
                    "podman_pull",
                    f.env(&[(name, "x".to_string())]),
                    &f.system()
                ),
                Err(MIRROR_REMOTE_PODMAN),
                "{name}"
            );
            assert_eq!(
                runtime_mirror_refusal_at(
                    "docker_pull",
                    f.env(&[(name, "x".to_string())]),
                    &f.system()
                ),
                Ok(()),
                "docker does not read {name}"
            );
        }
        assert_eq!(
            runtime_mirror_refusal_at(
                "podman_pull",
                f.env(&[("CONTAINER_HOST", String::new())]),
                &f.system()
            ),
            Ok(()),
            "an empty CONTAINER_HOST is unset"
        );
    }

    #[test]
    fn a_switched_docker_context_in_config_json_refuses_for_docker() {
        let f = MirrorFixture::new("docker_context");
        let cfg = f.home().join(".docker/config.json");
        f.put(cfg.clone(), r#"{"currentContext": "remote"}"#);
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&[]), &f.system()),
            Err(MIRROR_CONTEXT_DOCKER)
        );
        assert_eq!(
            runtime_mirror_refusal_at("podman_run", f.env(&[]), &f.system()),
            Ok(()),
            "podman does not read the docker config.json"
        );
        for text in [
            r#"{"currentContext": "default"}"#,
            "{}",
            r#"{"currentContext": null}"#,
            r#"{"currentContext": ""}"#,
        ] {
            f.put(cfg.clone(), text);
            assert_eq!(
                runtime_mirror_refusal_at("docker_run", f.env(&[]), &f.system()),
                Ok(()),
                "{text}"
            );
        }
        f.put(cfg.clone(), "{ not json");
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&[]), &f.system()),
            Err(MIRROR_UNPARSED)
        );
        f.put(cfg.clone(), r#"{"currentContext": 5}"#);
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&[]), &f.system()),
            Err(MIRROR_UNPARSED)
        );
    }

    #[test]
    fn docker_config_env_names_the_config_json_instead_of_home() {
        let f = MirrorFixture::new("docker_config_env");
        f.put(
            f.home().join(".docker/config.json"),
            r#"{"currentContext": "remote"}"#,
        );
        let dc = [(
            "DOCKER_CONFIG",
            f.root.join("dc").to_string_lossy().into_owned(),
        )];
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&dc), &f.system()),
            Ok(()),
            "HOME's config.json is not read when DOCKER_CONFIG is set"
        );
        f.put(
            f.root.join("dc/config.json"),
            r#"{"currentContext": "remote"}"#,
        );
        assert_eq!(
            runtime_mirror_refusal_at("docker_run", f.env(&dc), &f.system()),
            Err(MIRROR_CONTEXT_DOCKER)
        );
    }

    fn temp_dir(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("ae_mirror_{tag}_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("temp dir");
        dir
    }

    /// Only temp files are read here: `mirror_refusal_in` takes the list, so the
    /// real /etc files are never part of the test.
    #[test]
    fn a_listed_file_that_names_a_mirror_refuses_and_an_absent_one_does_not() {
        let dir = temp_dir("list");
        let absent = dir.join("absent.json");
        let daemon = dir.join("daemon.json");
        let conf = dir.join("registries.conf");
        std::fs::write(&daemon, "{}").expect("daemon.json");
        std::fs::write(
            &conf,
            "[[registry]]\nlocation = \"docker.io\"\n\n[[registry.mirror]]\nlocation = \"m\"\n",
        )
        .expect("registries.conf");
        assert_eq!(
            mirror_refusal_in(&[(MirrorConfig::DaemonJson, absent.clone())]),
            Ok(())
        );
        assert_eq!(
            mirror_refusal_in(&[(MirrorConfig::DaemonJson, daemon.clone())]),
            Ok(())
        );
        assert_eq!(
            mirror_refusal_in(&[
                (MirrorConfig::DaemonJson, absent.clone()),
                (MirrorConfig::RegistriesConf, conf.clone()),
            ]),
            Err(MIRROR_NAMED)
        );
        // The format decides how a file is read: the registries.conf text is not
        // a daemon.json, so it does not parse as one.
        assert_eq!(
            mirror_refusal_in(&[(MirrorConfig::DaemonJson, conf.clone())]),
            Err(MIRROR_UNPARSED)
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_listed_file_that_cannot_be_parsed_refuses() {
        let dir = temp_dir("bad");
        let bad = dir.join("daemon.json");
        std::fs::write(&bad, "{ not json").expect("bad daemon.json");
        assert_eq!(
            mirror_refusal_in(&[(MirrorConfig::DaemonJson, bad)]),
            Err(MIRROR_UNPARSED)
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_remote_share_path_refuses_without_being_probed() {
        if !cfg!(windows) {
            return;
        }
        assert_eq!(
            mirror_refusal_in(&[(
                MirrorConfig::DaemonJson,
                PathBuf::from(r"\\ae-no-such-host\share\daemon.json"),
            )]),
            Err(MIRROR_UNREADABLE)
        );
    }

    #[test]
    fn containers_conf_override_refuses_without_reading_anything() {
        assert_eq!(
            container_mirror_refusal(env_of(&[("CONTAINERS_REGISTRIES_CONF", "/fake/x.conf")])),
            Err(MIRROR_ENV)
        );
    }

    #[test]
    fn git_install_dir_is_derived_from_the_program_path_alone() {
        let root = r"C:\Program Files\Git";
        assert_eq!(
            git_install_dir_of(r"C:\Program Files\Git\cmd\git.exe").as_deref(),
            Some(root)
        );
        assert_eq!(
            git_install_dir_of(r"C:\Program Files\Git\mingw64\bin\git.exe").as_deref(),
            Some(root)
        );
        assert_eq!(
            git_install_dir_of(r"C:\Program Files\Git\bin\git.exe").as_deref(),
            Some(root)
        );
        // Forward slashes and an upper-case name are the same program.
        assert_eq!(
            git_install_dir_of("D:/Tools/Git/cmd/GIT.EXE").as_deref(),
            Some(r"D:\Tools\Git")
        );
        // Not a git program, or not in a directory the install uses.
        assert_eq!(
            git_install_dir_of(r"C:\Program Files\Git\cmd\git-lfs.exe"),
            None
        );
        assert_eq!(git_install_dir_of(r"C:\Program Files\Git\git.exe"), None);
        assert_eq!(git_install_dir_of(r"C:\Tools\Git\usr\bin\rev.exe"), None);
        assert_eq!(git_install_dir_of("git.exe"), None);
    }

    #[test]
    fn git_config_paths_add_the_install_files_only_when_git_is_on_path() {
        // No PATH, or a PATH without git, adds nothing. This never probes a real
        // directory: the names are fakes that do not exist.
        let plain = git_config_paths(env_of(&[("HOME", "/fake/home")]));
        assert_eq!(plain[0], PathBuf::from("/etc/gitconfig"));
        assert!(!plain
            .iter()
            .any(|p| p.ends_with("gitconfig") && p.to_string_lossy().contains("mingw64")));
        let none = git_config_paths(env_of(&[
            ("HOME", "/fake/home"),
            ("PATH", r"\\ae-no-such-host\share"),
        ]));
        assert_eq!(none, plain);
    }
}