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
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
39263
39264
39265
39266
39267
39268
39269
39270
39271
39272
39273
39274
39275
39276
39277
39278
39279
39280
39281
39282
39283
39284
39285
39286
39287
39288
39289
39290
39291
39292
39293
39294
39295
39296
39297
39298
39299
39300
39301
39302
39303
39304
39305
39306
39307
39308
39309
39310
39311
39312
39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338
39339
39340
39341
39342
39343
39344
39345
39346
39347
39348
39349
39350
39351
39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376
39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
39403
39404
39405
39406
39407
39408
39409
39410
39411
39412
39413
39414
39415
39416
39417
39418
39419
39420
39421
39422
39423
39424
39425
39426
39427
39428
39429
39430
39431
39432
39433
39434
39435
39436
39437
39438
39439
39440
39441
39442
39443
39444
39445
39446
39447
39448
39449
39450
39451
39452
39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472
39473
39474
39475
39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512
39513
39514
39515
39516
39517
39518
39519
39520
39521
39522
39523
39524
39525
39526
39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566
39567
39568
39569
39570
39571
39572
39573
39574
39575
39576
39577
39578
39579
39580
39581
39582
39583
39584
39585
39586
39587
39588
39589
39590
39591
39592
39593
39594
39595
39596
39597
39598
39599
39600
39601
39602
39603
39604
39605
39606
39607
39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620
39621
39622
39623
39624
39625
39626
39627
39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
39659
39660
39661
39662
39663
39664
39665
39666
39667
39668
39669
39670
39671
39672
39673
39674
39675
39676
39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687
39688
39689
39690
39691
39692
39693
39694
39695
39696
39697
39698
39699
39700
39701
39702
39703
39704
39705
39706
39707
39708
39709
39710
39711
39712
39713
39714
39715
39716
39717
39718
39719
39720
39721
39722
39723
39724
39725
39726
39727
39728
39729
39730
39731
39732
39733
39734
39735
39736
39737
39738
39739
39740
39741
39742
39743
39744
39745
39746
39747
39748
39749
39750
39751
39752
39753
39754
39755
39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772
39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805
39806
39807
39808
39809
39810
39811
39812
39813
39814
39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825
39826
39827
39828
39829
39830
39831
39832
39833
39834
39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847
39848
39849
39850
39851
39852
39853
39854
39855
39856
39857
39858
39859
39860
39861
39862
39863
39864
39865
39866
39867
39868
39869
39870
39871
39872
39873
39874
39875
39876
39877
39878
39879
39880
39881
39882
39883
39884
39885
39886
39887
39888
39889
39890
39891
39892
39893
39894
39895
39896
39897
39898
39899
39900
39901
39902
39903
39904
39905
39906
39907
39908
39909
39910
39911
39912
39913
39914
39915
39916
39917
39918
39919
39920
39921
39922
39923
39924
39925
39926
39927
39928
39929
39930
39931
39932
39933
39934
39935
39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947
39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962
39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974
39975
39976
39977
39978
39979
39980
39981
39982
39983
39984
39985
39986
39987
39988
39989
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
40000
40001
40002
40003
40004
40005
40006
40007
40008
40009
40010
40011
40012
40013
40014
40015
40016
40017
40018
40019
40020
40021
40022
40023
40024
40025
40026
40027
40028
40029
40030
40031
40032
40033
40034
40035
40036
40037
40038
40039
40040
40041
40042
40043
40044
40045
40046
40047
40048
40049
40050
40051
40052
40053
40054
40055
40056
40057
40058
40059
40060
40061
40062
40063
40064
40065
40066
40067
40068
40069
40070
40071
40072
40073
40074
40075
40076
40077
40078
40079
40080
40081
40082
40083
40084
40085
40086
40087
40088
40089
40090
40091
40092
40093
40094
40095
40096
40097
40098
40099
40100
40101
40102
40103
40104
40105
40106
40107
40108
40109
40110
40111
40112
40113
40114
40115
40116
40117
40118
40119
40120
40121
40122
40123
40124
40125
40126
40127
40128
40129
40130
40131
40132
40133
40134
40135
40136
40137
40138
40139
40140
40141
40142
40143
40144
40145
40146
40147
40148
40149
40150
40151
40152
40153
40154
40155
40156
40157
40158
40159
40160
40161
40162
40163
40164
40165
40166
40167
40168
40169
40170
40171
40172
40173
40174
40175
40176
40177
40178
40179
40180
40181
40182
40183
40184
40185
40186
40187
40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278
40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292
40293
40294
40295
40296
40297
40298
40299
40300
40301
40302
40303
40304
40305
40306
40307
40308
40309
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134
41135
41136
41137
41138
41139
41140
41141
41142
41143
41144
41145
41146
41147
41148
41149
41150
41151
41152
41153
41154
41155
41156
41157
41158
41159
41160
41161
41162
41163
41164
41165
41166
41167
41168
41169
41170
41171
41172
41173
41174
41175
41176
41177
41178
41179
41180
41181
41182
41183
41184
41185
41186
41187
41188
41189
41190
41191
41192
41193
41194
41195
41196
41197
41198
41199
41200
41201
41202
41203
41204
41205
41206
41207
41208
41209
41210
41211
41212
41213
41214
41215
41216
41217
41218
41219
41220
41221
41222
41223
41224
41225
41226
41227
41228
41229
41230
41231
41232
41233
41234
41235
41236
41237
41238
41239
41240
41241
41242
41243
41244
41245
41246
41247
41248
41249
41250
41251
41252
41253
41254
41255
41256
41257
41258
41259
41260
41261
41262
41263
41264
41265
41266
41267
41268
41269
41270
41271
41272
41273
41274
41275
41276
41277
41278
41279
41280
41281
41282
41283
41284
41285
41286
41287
41288
41289
41290
41291
41292
41293
41294
41295
41296
41297
41298
41299
41300
41301
41302
41303
41304
41305
41306
41307
41308
41309
41310
41311
41312
41313
41314
41315
41316
41317
41318
41319
41320
41321
41322
41323
41324
41325
41326
41327
41328
41329
41330
41331
41332
41333
41334
41335
41336
41337
41338
41339
41340
41341
41342
41343
41344
41345
41346
41347
41348
41349
41350
41351
41352
41353
41354
41355
41356
41357
41358
41359
41360
41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387
41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
41415
41416
41417
41418
41419
41420
41421
41422
41423
41424
41425
41426
41427
41428
41429
41430
41431
41432
41433
41434
41435
41436
41437
41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449
41450
41451
41452
41453
41454
41455
41456
41457
41458
41459
41460
41461
41462
41463
41464
41465
41466
41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
41509
41510
41511
41512
41513
41514
41515
41516
41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537
41538
41539
41540
41541
41542
41543
41544
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
41590
41591
41592
41593
41594
41595
41596
41597
41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
41627
41628
41629
41630
41631
41632
41633
41634
41635
41636
41637
41638
41639
41640
41641
41642
41643
41644
41645
41646
41647
41648
41649
41650
41651
41652
41653
41654
41655
41656
41657
41658
41659
41660
41661
41662
41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713
41714
41715
41716
41717
41718
41719
41720
41721
41722
41723
41724
41725
41726
41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741
41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41761
41762
41763
41764
41765
41766
41767
41768
41769
41770
41771
41772
41773
41774
41775
41776
41777
41778
41779
41780
41781
41782
41783
41784
41785
41786
41787
41788
41789
41790
41791
41792
41793
41794
41795
41796
41797
41798
41799
41800
41801
41802
41803
41804
41805
41806
41807
41808
41809
41810
41811
41812
41813
41814
41815
41816
41817
41818
41819
41820
41821
41822
41823
41824
41825
41826
41827
41828
41829
41830
41831
41832
41833
41834
41835
41836
41837
41838
41839
41840
41841
41842
41843
41844
41845
41846
41847
41848
41849
41850
41851
41852
41853
41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876
41877
41878
41879
41880
41881
41882
41883
41884
41885
41886
41887
41888
41889
41890
41891
41892
41893
41894
41895
41896
41897
41898
41899
41900
41901
41902
41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925
41926
41927
41928
41929
41930
41931
41932
41933
41934
41935
41936
41937
41938
41939
41940
41941
41942
41943
41944
41945
41946
41947
41948
41949
41950
41951
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970
41971
41972
41973
41974
41975
41976
41977
41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998
41999
42000
42001
42002
42003
42004
42005
42006
42007
42008
42009
42010
42011
42012
42013
42014
42015
42016
42017
42018
42019
42020
42021
42022
42023
42024
42025
42026
42027
42028
42029
42030
42031
42032
42033
42034
42035
42036
42037
42038
42039
42040
42041
42042
42043
42044
42045
42046
42047
42048
42049
42050
42051
42052
42053
42054
42055
42056
42057
42058
42059
42060
42061
42062
42063
42064
42065
42066
42067
42068
42069
42070
42071
42072
42073
42074
42075
42076
42077
42078
42079
42080
42081
42082
42083
42084
42085
42086
42087
42088
42089
42090
42091
42092
42093
42094
42095
42096
42097
42098
42099
42100
42101
42102
42103
42104
42105
42106
42107
42108
42109
42110
42111
42112
42113
42114
42115
42116
42117
42118
42119
42120
42121
42122
42123
42124
42125
42126
42127
42128
42129
42130
42131
42132
42133
42134
42135
42136
42137
42138
42139
42140
42141
42142
42143
42144
42145
42146
42147
42148
42149
42150
42151
42152
42153
42154
42155
42156
42157
42158
42159
42160
42161
42162
42163
42164
42165
42166
42167
42168
42169
42170
42171
42172
42173
42174
42175
42176
42177
42178
42179
42180
42181
42182
42183
42184
42185
42186
42187
42188
42189
42190
42191
42192
42193
42194
42195
42196
42197
42198
42199
42200
42201
42202
42203
42204
42205
42206
42207
42208
42209
42210
42211
42212
42213
42214
42215
42216
42217
42218
42219
42220
42221
42222
42223
42224
42225
42226
42227
42228
42229
42230
42231
42232
42233
42234
42235
42236
42237
42238
42239
42240
42241
42242
42243
42244
42245
42246
42247
42248
42249
42250
42251
42252
42253
42254
42255
42256
42257
42258
42259
42260
42261
42262
42263
42264
42265
42266
42267
42268
42269
42270
42271
42272
42273
42274
42275
42276
42277
42278
42279
42280
42281
42282
42283
42284
42285
42286
42287
42288
42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
42304
42305
42306
42307
42308
42309
42310
42311
42312
42313
42314
42315
42316
42317
42318
42319
42320
42321
42322
42323
42324
42325
42326
42327
42328
42329
42330
42331
42332
42333
42334
42335
42336
42337
42338
42339
42340
42341
42342
42343
42344
42345
42346
42347
42348
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
42364
42365
42366
42367
42368
42369
42370
42371
42372
42373
42374
42375
42376
42377
42378
42379
42380
42381
42382
42383
42384
42385
42386
42387
42388
42389
42390
42391
42392
42393
42394
42395
42396
42397
42398
42399
42400
42401
42402
42403
42404
42405
42406
42407
42408
42409
42410
42411
42412
42413
42414
42415
42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
42431
42432
42433
42434
42435
42436
42437
42438
42439
42440
42441
42442
42443
42444
42445
42446
42447
42448
42449
42450
42451
42452
42453
42454
42455
42456
42457
42458
42459
42460
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
42491
42492
42493
42494
42495
42496
42497
42498
42499
42500
42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517
42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532
42533
42534
42535
42536
42537
42538
42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552
42553
42554
42555
42556
42557
42558
42559
42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571
42572
42573
42574
42575
42576
42577
42578
42579
42580
42581
42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
42622
42623
42624
42625
42626
42627
42628
42629
42630
42631
42632
42633
42634
42635
42636
42637
42638
42639
42640
42641
42642
42643
42644
42645
42646
42647
42648
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
42664
42665
42666
42667
42668
42669
42670
42671
42672
42673
42674
42675
42676
42677
42678
42679
42680
42681
42682
42683
42684
42685
42686
42687
42688
42689
42690
42691
42692
42693
42694
42695
42696
42697
42698
42699
42700
42701
42702
42703
42704
42705
42706
42707
42708
42709
42710
42711
42712
42713
42714
42715
42716
42717
42718
42719
42720
42721
42722
42723
42724
42725
42726
42727
42728
42729
42730
42731
42732
42733
42734
42735
42736
42737
42738
42739
42740
42741
42742
42743
42744
42745
42746
42747
42748
42749
42750
42751
42752
42753
42754
42755
42756
42757
42758
42759
42760
42761
42762
42763
42764
42765
42766
42767
42768
42769
42770
42771
42772
42773
42774
42775
42776
42777
42778
42779
42780
42781
42782
42783
42784
42785
42786
42787
42788
42789
42790
42791
42792
42793
42794
42795
42796
42797
42798
42799
42800
42801
42802
42803
42804
42805
42806
42807
42808
42809
42810
42811
42812
42813
42814
42815
42816
42817
42818
42819
42820
42821
42822
42823
42824
42825
42826
42827
42828
42829
42830
42831
42832
42833
42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848
42849
42850
42851
42852
42853
42854
42855
42856
42857
42858
42859
42860
42861
42862
42863
42864
42865
42866
42867
42868
42869
42870
42871
42872
42873
42874
42875
42876
42877
42878
42879
42880
42881
42882
42883
42884
42885
42886
42887
42888
42889
42890
42891
42892
42893
42894
42895
42896
42897
42898
42899
42900
42901
42902
42903
42904
42905
42906
42907
42908
42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929
42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947
42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964
42965
42966
42967
42968
42969
42970
42971
42972
42973
42974
42975
42976
42977
42978
42979
42980
42981
42982
42983
42984
42985
42986
42987
42988
42989
42990
42991
42992
42993
42994
42995
42996
42997
42998
42999
43000
43001
43002
43003
43004
43005
43006
43007
43008
43009
43010
43011
43012
43013
43014
43015
43016
43017
43018
43019
43020
43021
43022
43023
43024
43025
43026
43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041
43042
43043
43044
43045
43046
43047
43048
43049
43050
43051
43052
43053
43054
43055
43056
43057
43058
43059
43060
43061
43062
43063
43064
43065
43066
43067
43068
43069
43070
43071
43072
43073
43074
43075
43076
43077
43078
43079
43080
43081
43082
43083
43084
43085
43086
43087
43088
43089
43090
43091
43092
43093
43094
43095
43096
43097
43098
43099
43100
43101
43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122
43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140
43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157
43158
43159
43160
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
43179
43180
43181
43182
43183
43184
43185
43186
43187
43188
43189
43190
43191
43192
43193
43194
43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
43219
43220
43221
43222
43223
43224
43225
43226
43227
43228
43229
43230
43231
43232
43233
43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411
43412
43413
43414
43415
43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946
43947
43948
43949
43950
43951
43952
43953
43954
43955
43956
43957
43958
43959
43960
43961
43962
43963
43964
43965
43966
43967
43968
43969
43970
43971
43972
43973
43974
43975
43976
43977
43978
43979
43980
43981
43982
43983
43984
43985
43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000
44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014
44015
44016
44017
44018
44019
44020
44021
44022
44023
44024
44025
44026
44027
44028
44029
44030
44031
44032
44033
44034
44035
44036
44037
44038
44039
44040
44041
44042
44043
44044
44045
44046
44047
44048
44049
44050
44051
44052
44053
44054
44055
44056
44057
44058
44059
44060
44061
44062
44063
44064
44065
44066
44067
44068
44069
44070
44071
44072
44073
44074
44075
44076
44077
44078
44079
44080
44081
44082
44083
44084
44085
44086
44087
44088
44089
44090
44091
44092
44093
44094
44095
44096
44097
44098
44099
44100
44101
44102
44103
44104
44105
44106
44107
44108
44109
44110
44111
44112
44113
44114
44115
44116
44117
44118
44119
44120
44121
44122
44123
44124
44125
44126
44127
44128
44129
44130
44131
44132
44133
44134
44135
44136
44137
44138
44139
44140
44141
44142
44143
44144
44145
44146
44147
44148
44149
44150
44151
44152
44153
44154
44155
44156
44157
44158
44159
44160
44161
44162
44163
44164
44165
44166
44167
44168
44169
44170
44171
44172
44173
44174
44175
44176
44177
44178
44179
44180
44181
44182
44183
44184
44185
44186
44187
44188
44189
44190
44191
44192
44193
44194
44195
44196
44197
44198
44199
44200
44201
44202
44203
44204
44205
44206
44207
44208
44209
44210
44211
44212
44213
44214
44215
44216
44217
44218
44219
44220
44221
44222
44223
44224
44225
44226
44227
44228
44229
44230
44231
44232
44233
44234
44235
44236
44237
44238
44239
44240
44241
44242
44243
44244
44245
44246
44247
44248
44249
44250
44251
44252
44253
44254
44255
44256
44257
44258
44259
44260
44261
44262
44263
44264
44265
44266
44267
44268
44269
44270
44271
44272
44273
44274
44275
44276
44277
44278
44279
44280
44281
44282
44283
44284
44285
44286
44287
44288
44289
44290
44291
44292
44293
44294
44295
44296
44297
44298
44299
44300
44301
44302
44303
44304
44305
44306
44307
44308
44309
44310
44311
44312
44313
44314
44315
44316
44317
44318
44319
44320
44321
44322
44323
44324
44325
44326
44327
44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
44343
44344
44345
44346
44347
44348
44349
44350
44351
44352
44353
44354
44355
44356
44357
44358
44359
44360
44361
44362
44363
44364
44365
44366
44367
44368
44369
44370
44371
44372
44373
44374
44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394
44395
44396
44397
44398
44399
44400
44401
44402
44403
44404
44405
44406
44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424
44425
44426
44427
44428
44429
44430
44431
44432
44433
44434
44435
44436
44437
44438
44439
44440
44441
44442
44443
44444
44445
44446
44447
44448
44449
44450
44451
44452
44453
44454
44455
44456
44457
44458
44459
44460
44461
44462
44463
44464
44465
44466
44467
44468
44469
44470
44471
44472
44473
44474
44475
44476
44477
44478
44479
44480
44481
44482
44483
44484
44485
44486
44487
44488
44489
44490
44491
44492
44493
44494
44495
44496
44497
44498
44499
44500
44501
44502
44503
44504
44505
44506
44507
44508
44509
44510
44511
44512
44513
44514
44515
44516
44517
44518
44519
44520
44521
44522
44523
44524
44525
44526
44527
44528
44529
44530
44531
44532
44533
44534
44535
44536
44537
44538
44539
44540
44541
44542
44543
44544
44545
44546
44547
44548
44549
44550
44551
44552
44553
44554
44555
44556
44557
44558
44559
44560
44561
44562
44563
44564
44565
44566
44567
44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
44660
44661
44662
44663
44664
44665
44666
44667
44668
44669
44670
44671
44672
44673
44674
44675
44676
44677
44678
44679
44680
44681
44682
44683
44684
44685
44686
44687
44688
44689
44690
44691
44692
44693
44694
44695
44696
44697
44698
44699
44700
44701
44702
44703
44704
44705
44706
44707
44708
44709
44710
44711
44712
44713
44714
44715
44716
44717
44718
44719
44720
44721
44722
44723
44724
44725
44726
44727
44728
44729
44730
44731
44732
44733
44734
44735
44736
44737
44738
44739
44740
44741
44742
44743
44744
44745
44746
44747
44748
44749
44750
44751
44752
44753
44754
44755
44756
44757
44758
44759
44760
44761
44762
44763
44764
44765
44766
44767
44768
44769
44770
44771
44772
44773
44774
44775
44776
44777
44778
44779
44780
44781
44782
44783
44784
44785
44786
44787
44788
44789
44790
44791
44792
44793
44794
44795
44796
44797
44798
44799
44800
44801
44802
44803
44804
44805
44806
44807
44808
44809
44810
44811
44812
44813
44814
44815
44816
44817
44818
44819
44820
44821
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
44837
44838
44839
44840
44841
44842
44843
44844
44845
44846
44847
44848
44849
44850
44851
44852
44853
44854
44855
44856
44857
44858
44859
44860
44861
44862
44863
44864
44865
44866
44867
44868
44869
44870
44871
44872
44873
44874
44875
44876
44877
44878
44879
44880
44881
44882
44883
44884
44885
44886
44887
44888
44889
44890
44891
44892
44893
44894
44895
44896
44897
44898
44899
44900
44901
44902
44903
44904
44905
44906
44907
44908
44909
44910
44911
44912
44913
44914
44915
44916
44917
44918
44919
44920
44921
44922
44923
44924
44925
44926
44927
44928
44929
44930
44931
44932
44933
44934
44935
44936
44937
44938
44939
44940
44941
44942
44943
44944
44945
44946
44947
44948
44949
44950
44951
44952
44953
44954
44955
44956
44957
44958
44959
44960
44961
44962
44963
44964
44965
44966
44967
44968
44969
44970
44971
44972
44973
44974
44975
44976
44977
44978
44979
44980
44981
44982
44983
44984
44985
44986
44987
44988
44989
44990
44991
44992
44993
44994
44995
44996
44997
44998
44999
45000
45001
45002
45003
45004
45005
45006
45007
45008
45009
45010
45011
45012
45013
45014
45015
45016
45017
45018
45019
45020
45021
45022
45023
45024
45025
45026
45027
45028
45029
45030
45031
45032
45033
45034
45035
45036
45037
45038
45039
45040
45041
45042
45043
45044
45045
45046
45047
45048
45049
45050
45051
45052
45053
45054
45055
45056
45057
45058
45059
45060
45061
45062
45063
45064
45065
45066
45067
45068
45069
45070
45071
45072
45073
45074
45075
45076
45077
45078
45079
45080
45081
45082
45083
45084
45085
45086
45087
45088
45089
45090
45091
45092
45093
45094
45095
45096
45097
45098
45099
45100
45101
45102
45103
45104
45105
45106
45107
45108
45109
45110
45111
45112
45113
45114
45115
45116
45117
45118
45119
45120
45121
45122
45123
45124
45125
45126
45127
45128
45129
45130
45131
45132
45133
45134
45135
45136
45137
45138
45139
45140
45141
45142
45143
45144
45145
45146
45147
45148
45149
45150
45151
45152
45153
45154
45155
45156
45157
45158
45159
45160
45161
45162
45163
45164
45165
45166
45167
45168
45169
45170
45171
45172
45173
45174
45175
45176
45177
45178
45179
45180
45181
45182
45183
45184
45185
45186
45187
45188
45189
45190
45191
45192
45193
45194
45195
45196
45197
45198
45199
45200
45201
45202
45203
45204
45205
45206
45207
45208
45209
45210
45211
45212
45213
45214
45215
45216
45217
45218
45219
45220
45221
45222
45223
45224
45225
45226
45227
45228
45229
45230
45231
45232
45233
45234
45235
45236
45237
45238
45239
45240
45241
45242
45243
45244
45245
45246
45247
45248
45249
45250
45251
45252
45253
45254
45255
45256
45257
45258
45259
45260
45261
45262
45263
45264
45265
45266
45267
45268
45269
45270
45271
45272
45273
45274
45275
45276
45277
45278
45279
45280
45281
45282
45283
45284
45285
45286
45287
45288
45289
45290
45291
45292
45293
45294
45295
45296
45297
45298
45299
45300
45301
45302
45303
45304
45305
45306
45307
45308
45309
45310
45311
45312
45313
45314
45315
45316
45317
45318
45319
45320
45321
45322
45323
45324
45325
45326
45327
45328
45329
45330
45331
45332
45333
45334
45335
45336
45337
45338
45339
45340
45341
45342
45343
45344
45345
45346
45347
45348
45349
45350
45351
45352
45353
45354
45355
45356
45357
45358
45359
45360
45361
45362
45363
45364
45365
45366
45367
45368
45369
45370
45371
45372
45373
45374
45375
45376
45377
45378
45379
45380
45381
45382
45383
45384
45385
45386
45387
45388
45389
45390
45391
45392
45393
45394
45395
45396
45397
45398
45399
45400
45401
45402
45403
45404
45405
45406
45407
45408
45409
45410
45411
45412
45413
45414
45415
45416
45417
45418
45419
45420
45421
45422
45423
45424
45425
45426
45427
45428
45429
45430
45431
45432
45433
45434
45435
45436
45437
45438
45439
45440
45441
45442
45443
45444
45445
45446
45447
45448
45449
45450
45451
45452
45453
45454
45455
45456
45457
45458
45459
45460
45461
45462
45463
45464
45465
45466
45467
45468
45469
45470
45471
45472
45473
45474
45475
45476
45477
45478
45479
45480
45481
45482
45483
45484
45485
45486
45487
45488
45489
45490
45491
45492
45493
45494
45495
45496
45497
45498
45499
45500
45501
45502
45503
45504
45505
45506
45507
45508
45509
45510
45511
45512
45513
45514
45515
45516
45517
45518
45519
45520
45521
45522
45523
45524
45525
45526
45527
45528
45529
45530
45531
45532
45533
45534
45535
45536
45537
45538
45539
45540
45541
45542
45543
45544
45545
45546
45547
45548
45549
45550
45551
45552
45553
45554
45555
45556
45557
45558
45559
45560
45561
45562
45563
45564
45565
45566
45567
45568
45569
45570
45571
45572
45573
45574
45575
45576
45577
45578
45579
45580
45581
45582
45583
45584
45585
45586
45587
45588
45589
45590
45591
45592
45593
45594
45595
45596
45597
45598
45599
45600
45601
45602
45603
45604
45605
45606
45607
45608
45609
45610
45611
45612
45613
45614
45615
45616
45617
45618
45619
45620
45621
45622
45623
45624
45625
45626
45627
45628
45629
45630
45631
45632
45633
45634
45635
45636
45637
45638
45639
45640
45641
45642
45643
45644
45645
45646
45647
45648
45649
45650
45651
45652
45653
45654
45655
45656
45657
45658
45659
45660
45661
45662
45663
45664
45665
45666
45667
45668
45669
45670
45671
45672
45673
45674
45675
45676
45677
45678
45679
45680
45681
45682
45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
45698
45699
45700
45701
45702
45703
45704
45705
45706
45707
45708
45709
45710
45711
45712
45713
45714
45715
45716
45717
45718
45719
45720
45721
45722
45723
45724
45725
45726
45727
45728
45729
45730
45731
45732
45733
45734
45735
45736
45737
45738
45739
45740
45741
45742
45743
45744
45745
45746
45747
45748
45749
45750
45751
45752
45753
45754
45755
45756
45757
45758
45759
45760
45761
45762
45763
45764
45765
45766
45767
45768
45769
45770
45771
45772
45773
45774
45775
45776
45777
45778
45779
45780
45781
45782
45783
45784
45785
45786
45787
45788
45789
45790
45791
45792
45793
45794
45795
45796
45797
45798
45799
45800
45801
45802
45803
45804
45805
45806
45807
45808
45809
45810
45811
45812
45813
45814
45815
45816
45817
45818
45819
45820
45821
45822
45823
45824
45825
45826
45827
45828
45829
45830
45831
45832
45833
45834
45835
45836
45837
45838
45839
45840
45841
45842
45843
45844
45845
45846
45847
45848
45849
45850
45851
45852
45853
45854
45855
45856
45857
45858
45859
45860
45861
45862
45863
45864
45865
45866
45867
45868
45869
45870
45871
45872
45873
45874
45875
45876
45877
45878
45879
45880
45881
45882
45883
45884
45885
45886
45887
45888
45889
45890
45891
45892
45893
45894
45895
45896
45897
45898
45899
45900
45901
45902
45903
45904
45905
45906
45907
45908
45909
45910
45911
45912
45913
45914
45915
45916
45917
45918
45919
45920
45921
45922
45923
45924
45925
45926
45927
45928
45929
45930
45931
45932
45933
45934
45935
45936
45937
45938
45939
45940
45941
45942
45943
45944
45945
45946
45947
45948
45949
45950
45951
45952
45953
45954
45955
45956
45957
45958
45959
45960
45961
45962
45963
45964
45965
45966
45967
45968
45969
45970
45971
45972
45973
45974
45975
45976
45977
45978
45979
45980
45981
45982
45983
45984
45985
45986
45987
45988
45989
45990
45991
45992
45993
45994
45995
45996
45997
45998
45999
46000
46001
46002
46003
46004
46005
46006
46007
46008
46009
46010
46011
46012
46013
46014
46015
46016
46017
46018
46019
46020
46021
46022
46023
46024
46025
46026
46027
46028
46029
46030
46031
46032
46033
46034
46035
46036
46037
46038
46039
46040
46041
46042
46043
46044
46045
46046
46047
46048
46049
46050
46051
46052
46053
46054
46055
46056
46057
46058
46059
46060
46061
46062
46063
46064
46065
46066
46067
46068
46069
46070
46071
46072
46073
46074
46075
46076
46077
46078
46079
46080
46081
46082
46083
46084
46085
46086
46087
46088
46089
46090
46091
46092
46093
46094
46095
46096
46097
46098
46099
46100
46101
46102
46103
46104
46105
46106
46107
46108
46109
46110
46111
46112
46113
46114
46115
46116
46117
46118
46119
46120
46121
46122
46123
46124
46125
46126
46127
46128
46129
46130
46131
46132
46133
46134
46135
46136
46137
46138
46139
46140
46141
46142
46143
46144
46145
46146
46147
46148
46149
46150
46151
46152
46153
46154
46155
46156
46157
46158
46159
46160
46161
46162
46163
46164
46165
46166
46167
46168
46169
46170
46171
46172
46173
46174
46175
46176
46177
46178
46179
46180
46181
46182
46183
46184
46185
46186
46187
46188
46189
46190
46191
46192
46193
46194
46195
46196
46197
46198
46199
46200
46201
46202
46203
46204
46205
46206
46207
46208
46209
46210
46211
46212
46213
46214
46215
46216
46217
46218
46219
46220
46221
46222
46223
46224
46225
46226
46227
46228
46229
46230
46231
46232
46233
46234
46235
46236
46237
46238
46239
46240
46241
46242
46243
46244
46245
46246
46247
46248
46249
46250
46251
46252
46253
46254
46255
46256
46257
46258
46259
46260
46261
46262
46263
46264
46265
46266
46267
46268
46269
46270
46271
46272
46273
46274
46275
46276
46277
46278
46279
46280
46281
46282
46283
46284
46285
46286
46287
46288
46289
46290
46291
46292
46293
46294
46295
46296
46297
46298
46299
46300
46301
46302
46303
46304
46305
46306
46307
46308
46309
46310
46311
46312
46313
46314
46315
46316
46317
46318
46319
46320
46321
46322
46323
46324
46325
46326
46327
46328
46329
46330
46331
46332
46333
46334
46335
46336
46337
46338
46339
46340
46341
46342
46343
46344
46345
46346
46347
46348
46349
46350
46351
46352
46353
46354
46355
46356
46357
46358
46359
46360
46361
46362
46363
46364
46365
46366
46367
46368
46369
46370
46371
46372
46373
46374
46375
46376
46377
46378
46379
46380
46381
46382
46383
46384
46385
46386
46387
46388
46389
46390
46391
46392
46393
46394
46395
46396
46397
46398
46399
46400
46401
46402
46403
46404
46405
46406
46407
46408
46409
46410
46411
46412
46413
46414
46415
46416
46417
46418
46419
46420
46421
46422
46423
46424
46425
46426
46427
46428
46429
46430
46431
46432
46433
46434
46435
46436
46437
46438
46439
46440
46441
46442
46443
46444
46445
46446
46447
46448
46449
46450
46451
46452
46453
46454
46455
46456
46457
46458
46459
46460
46461
46462
46463
46464
46465
46466
46467
46468
46469
46470
46471
46472
46473
46474
46475
46476
46477
46478
46479
46480
46481
46482
46483
46484
46485
46486
46487
46488
46489
46490
46491
46492
46493
46494
46495
46496
46497
46498
46499
46500
46501
46502
46503
46504
46505
46506
46507
46508
46509
46510
46511
46512
46513
46514
46515
46516
46517
46518
46519
46520
46521
46522
46523
46524
46525
46526
46527
46528
46529
46530
46531
46532
46533
46534
46535
46536
46537
46538
46539
46540
46541
46542
46543
46544
46545
46546
46547
46548
46549
46550
46551
46552
46553
46554
46555
46556
46557
46558
46559
46560
46561
46562
46563
46564
46565
46566
46567
46568
46569
46570
46571
46572
46573
46574
46575
46576
46577
46578
46579
46580
46581
46582
46583
46584
46585
46586
46587
46588
46589
46590
46591
46592
46593
46594
46595
46596
46597
46598
46599
46600
46601
46602
46603
46604
46605
46606
46607
46608
46609
46610
46611
46612
46613
46614
46615
46616
46617
46618
46619
46620
46621
46622
46623
46624
46625
46626
46627
46628
46629
46630
46631
46632
46633
46634
46635
46636
46637
46638
46639
46640
46641
46642
46643
46644
46645
46646
46647
46648
46649
46650
46651
46652
46653
46654
46655
46656
46657
46658
46659
46660
46661
46662
46663
46664
46665
46666
46667
46668
46669
46670
46671
46672
46673
46674
46675
46676
46677
46678
46679
46680
46681
46682
46683
46684
46685
46686
46687
46688
46689
46690
46691
46692
46693
46694
46695
46696
46697
46698
46699
46700
46701
46702
46703
46704
46705
46706
46707
46708
46709
46710
46711
46712
46713
46714
46715
46716
46717
46718
46719
46720
46721
46722
46723
46724
46725
46726
46727
46728
46729
46730
46731
46732
46733
46734
46735
46736
46737
46738
46739
46740
46741
46742
46743
46744
46745
46746
46747
46748
46749
46750
46751
46752
46753
46754
46755
46756
46757
46758
46759
46760
46761
46762
46763
46764
46765
46766
46767
46768
46769
46770
46771
46772
46773
46774
46775
46776
46777
46778
46779
46780
46781
46782
46783
46784
46785
46786
46787
46788
46789
46790
46791
46792
46793
46794
46795
46796
46797
46798
46799
46800
46801
46802
46803
46804
46805
46806
46807
46808
46809
46810
46811
46812
46813
46814
46815
46816
46817
46818
46819
46820
46821
46822
46823
46824
46825
46826
46827
46828
46829
46830
46831
46832
46833
46834
46835
46836
46837
46838
46839
46840
46841
46842
46843
46844
46845
46846
46847
46848
46849
46850
46851
46852
46853
46854
46855
46856
46857
46858
46859
46860
46861
46862
46863
46864
46865
46866
46867
46868
46869
46870
46871
46872
46873
46874
46875
46876
46877
46878
46879
46880
46881
46882
46883
46884
46885
46886
46887
46888
46889
46890
46891
46892
46893
46894
46895
46896
46897
46898
46899
46900
46901
46902
46903
46904
46905
46906
46907
46908
46909
46910
46911
46912
46913
46914
46915
46916
46917
46918
46919
46920
46921
46922
46923
46924
46925
46926
46927
46928
46929
46930
46931
46932
46933
46934
46935
46936
46937
46938
46939
46940
46941
46942
46943
46944
46945
46946
46947
46948
46949
46950
46951
46952
46953
46954
46955
46956
46957
46958
46959
46960
46961
46962
46963
46964
46965
46966
46967
46968
46969
46970
46971
46972
46973
46974
46975
46976
46977
46978
46979
46980
46981
46982
46983
46984
46985
46986
46987
46988
46989
46990
46991
46992
46993
46994
46995
46996
46997
46998
46999
47000
47001
47002
47003
47004
47005
47006
47007
47008
47009
47010
47011
47012
47013
47014
47015
47016
47017
47018
47019
47020
47021
47022
47023
47024
47025
47026
47027
47028
47029
47030
47031
47032
47033
47034
47035
47036
47037
47038
47039
47040
47041
47042
47043
47044
47045
47046
47047
47048
47049
47050
47051
47052
47053
47054
47055
47056
47057
47058
47059
47060
47061
47062
47063
47064
47065
47066
47067
47068
47069
47070
47071
47072
47073
47074
47075
47076
47077
47078
47079
47080
47081
47082
47083
47084
47085
47086
47087
47088
47089
47090
47091
47092
47093
47094
47095
47096
47097
47098
47099
47100
47101
47102
47103
47104
47105
47106
47107
47108
47109
47110
47111
47112
47113
47114
47115
47116
47117
47118
47119
47120
47121
47122
47123
47124
47125
47126
47127
47128
47129
47130
47131
47132
47133
47134
47135
47136
47137
47138
47139
47140
47141
47142
47143
47144
47145
47146
47147
47148
47149
47150
47151
47152
47153
47154
47155
47156
47157
47158
47159
47160
47161
47162
47163
47164
47165
47166
47167
47168
47169
47170
47171
47172
47173
47174
47175
47176
47177
47178
47179
47180
47181
47182
47183
47184
47185
47186
47187
47188
47189
47190
47191
47192
47193
47194
47195
47196
47197
47198
47199
47200
47201
47202
47203
47204
47205
47206
47207
47208
47209
47210
47211
47212
47213
47214
47215
47216
47217
47218
47219
47220
47221
47222
47223
47224
47225
47226
47227
47228
47229
47230
47231
47232
47233
47234
47235
47236
47237
47238
47239
47240
47241
47242
47243
47244
47245
47246
47247
47248
47249
47250
47251
47252
47253
47254
47255
47256
47257
47258
47259
47260
47261
47262
47263
47264
47265
47266
47267
47268
47269
47270
47271
47272
47273
47274
47275
47276
47277
47278
47279
47280
47281
47282
47283
47284
47285
47286
47287
47288
47289
47290
47291
47292
47293
47294
47295
47296
47297
47298
47299
47300
47301
47302
47303
47304
47305
47306
47307
47308
47309
47310
47311
47312
47313
47314
47315
47316
47317
47318
47319
47320
47321
47322
47323
47324
47325
47326
47327
47328
47329
47330
47331
47332
47333
47334
47335
47336
47337
47338
47339
47340
47341
47342
47343
47344
47345
47346
47347
47348
47349
47350
47351
47352
47353
47354
47355
47356
47357
47358
47359
47360
47361
47362
47363
47364
47365
47366
47367
47368
47369
47370
47371
47372
47373
47374
47375
47376
47377
47378
47379
47380
47381
47382
47383
47384
47385
47386
47387
47388
47389
47390
47391
47392
47393
47394
47395
47396
47397
47398
47399
47400
47401
47402
47403
47404
47405
47406
47407
47408
47409
47410
47411
47412
47413
47414
47415
47416
47417
47418
47419
47420
47421
47422
47423
47424
47425
47426
47427
47428
47429
47430
47431
47432
47433
47434
47435
47436
47437
47438
47439
47440
47441
47442
47443
47444
47445
47446
47447
47448
47449
47450
47451
47452
47453
47454
47455
47456
47457
47458
47459
47460
47461
47462
47463
47464
47465
47466
47467
47468
47469
47470
47471
47472
47473
47474
47475
47476
47477
47478
47479
47480
47481
47482
47483
47484
47485
47486
47487
47488
47489
47490
47491
47492
47493
47494
47495
47496
47497
47498
47499
47500
47501
47502
47503
47504
47505
47506
47507
47508
47509
47510
47511
47512
47513
47514
47515
47516
47517
47518
47519
47520
47521
47522
47523
47524
47525
47526
47527
47528
47529
47530
47531
47532
47533
47534
47535
47536
47537
47538
47539
47540
47541
47542
47543
47544
47545
47546
47547
47548
47549
47550
47551
47552
47553
47554
47555
47556
47557
47558
47559
47560
47561
47562
47563
47564
47565
47566
47567
47568
47569
47570
47571
47572
47573
47574
47575
47576
47577
47578
47579
47580
47581
47582
47583
47584
47585
47586
47587
47588
47589
47590
47591
47592
47593
47594
47595
47596
47597
47598
47599
47600
47601
47602
47603
47604
47605
47606
47607
47608
47609
47610
47611
47612
47613
47614
47615
47616
47617
47618
47619
47620
47621
47622
47623
47624
47625
47626
47627
47628
47629
47630
47631
47632
47633
47634
47635
47636
47637
47638
47639
47640
47641
47642
47643
47644
47645
47646
47647
47648
47649
47650
47651
47652
47653
47654
47655
47656
47657
47658
47659
47660
47661
47662
47663
47664
47665
47666
47667
47668
47669
47670
47671
47672
47673
47674
47675
47676
47677
47678
47679
47680
47681
47682
47683
47684
47685
47686
47687
47688
47689
47690
47691
47692
47693
47694
47695
47696
47697
47698
47699
47700
47701
47702
47703
47704
47705
47706
47707
47708
47709
47710
47711
47712
47713
47714
47715
47716
47717
47718
47719
47720
47721
47722
47723
47724
47725
47726
47727
47728
47729
47730
47731
47732
47733
47734
47735
47736
47737
47738
47739
47740
47741
47742
47743
47744
47745
47746
47747
47748
47749
47750
47751
47752
47753
47754
47755
47756
47757
47758
47759
47760
47761
47762
47763
47764
47765
47766
47767
47768
47769
47770
47771
47772
47773
47774
47775
47776
47777
47778
47779
47780
47781
47782
47783
47784
47785
47786
47787
47788
47789
47790
47791
47792
47793
47794
47795
47796
47797
47798
47799
47800
47801
47802
47803
47804
47805
47806
47807
47808
47809
47810
47811
47812
47813
47814
47815
47816
47817
47818
47819
47820
47821
47822
47823
47824
47825
47826
47827
47828
47829
47830
47831
47832
47833
47834
47835
47836
47837
47838
47839
47840
47841
47842
47843
47844
47845
47846
47847
47848
47849
47850
47851
47852
47853
47854
47855
47856
47857
47858
47859
47860
47861
47862
47863
47864
47865
47866
47867
47868
47869
47870
47871
47872
47873
47874
47875
47876
47877
47878
47879
47880
47881
47882
47883
47884
47885
47886
47887
47888
47889
47890
47891
47892
47893
47894
47895
47896
47897
47898
47899
47900
47901
47902
47903
47904
47905
47906
47907
47908
47909
47910
47911
47912
47913
47914
47915
47916
47917
47918
47919
47920
47921
47922
47923
47924
47925
47926
47927
47928
47929
47930
47931
47932
47933
47934
47935
47936
47937
47938
47939
47940
47941
47942
47943
47944
47945
47946
47947
47948
47949
47950
47951
47952
47953
47954
47955
47956
47957
47958
47959
47960
47961
47962
47963
47964
47965
47966
47967
47968
47969
47970
47971
47972
47973
47974
47975
47976
47977
47978
47979
47980
47981
47982
47983
47984
47985
47986
47987
47988
47989
47990
47991
47992
47993
47994
47995
47996
47997
47998
47999
48000
48001
48002
48003
48004
48005
48006
48007
48008
48009
48010
48011
48012
48013
48014
48015
48016
48017
48018
48019
48020
48021
48022
48023
48024
48025
48026
48027
48028
48029
48030
48031
48032
48033
48034
48035
48036
48037
48038
48039
48040
48041
48042
48043
48044
48045
48046
48047
48048
48049
48050
48051
48052
48053
48054
48055
48056
48057
48058
48059
48060
48061
48062
48063
48064
48065
48066
48067
48068
48069
48070
48071
48072
48073
48074
48075
48076
48077
48078
48079
48080
48081
48082
48083
48084
48085
48086
48087
48088
48089
48090
48091
48092
48093
48094
48095
48096
48097
48098
48099
48100
48101
48102
48103
48104
48105
48106
48107
48108
48109
48110
48111
48112
48113
48114
48115
48116
48117
48118
48119
48120
48121
48122
48123
48124
48125
48126
48127
48128
48129
48130
48131
48132
48133
48134
48135
48136
48137
48138
48139
48140
48141
48142
48143
48144
48145
48146
48147
48148
48149
48150
48151
48152
48153
48154
48155
48156
48157
48158
48159
48160
48161
48162
48163
48164
48165
48166
48167
48168
48169
48170
48171
48172
48173
48174
48175
48176
48177
48178
48179
48180
48181
48182
48183
48184
48185
48186
48187
48188
48189
48190
48191
48192
48193
48194
48195
48196
48197
48198
48199
48200
48201
48202
48203
48204
48205
48206
48207
48208
48209
48210
48211
48212
48213
48214
48215
48216
48217
48218
48219
48220
48221
48222
48223
48224
48225
48226
48227
48228
48229
48230
48231
48232
48233
48234
48235
48236
48237
48238
48239
48240
48241
48242
48243
48244
48245
48246
48247
48248
48249
48250
48251
48252
48253
48254
48255
48256
48257
48258
48259
48260
48261
48262
48263
48264
48265
48266
48267
48268
48269
48270
48271
48272
48273
48274
48275
48276
48277
48278
48279
48280
48281
48282
48283
48284
48285
48286
48287
48288
48289
48290
48291
48292
48293
48294
48295
48296
48297
48298
48299
48300
48301
48302
48303
48304
48305
48306
48307
48308
48309
48310
48311
48312
48313
48314
48315
48316
48317
48318
48319
48320
48321
48322
48323
48324
48325
48326
48327
48328
48329
48330
48331
48332
48333
48334
48335
48336
48337
48338
48339
48340
48341
48342
48343
48344
48345
48346
48347
48348
48349
48350
48351
48352
48353
48354
48355
48356
48357
48358
48359
48360
48361
48362
48363
48364
48365
48366
48367
48368
48369
48370
48371
48372
48373
48374
48375
48376
48377
48378
48379
48380
48381
48382
48383
48384
48385
48386
48387
48388
48389
48390
48391
48392
48393
48394
48395
48396
48397
48398
48399
48400
48401
48402
48403
48404
48405
48406
48407
48408
48409
48410
48411
48412
48413
48414
48415
48416
48417
48418
48419
48420
48421
48422
48423
48424
48425
48426
48427
48428
48429
48430
48431
48432
48433
48434
48435
48436
48437
48438
48439
48440
48441
48442
48443
48444
48445
48446
48447
48448
48449
48450
48451
48452
48453
48454
48455
48456
48457
48458
48459
48460
48461
48462
48463
48464
48465
48466
48467
48468
48469
48470
48471
48472
48473
48474
48475
48476
48477
48478
48479
48480
48481
48482
48483
48484
48485
48486
48487
48488
48489
48490
48491
48492
48493
48494
48495
48496
48497
48498
48499
48500
48501
48502
48503
48504
48505
48506
48507
48508
48509
48510
48511
48512
48513
48514
48515
48516
48517
48518
48519
48520
48521
48522
48523
48524
48525
48526
48527
48528
48529
48530
48531
48532
48533
48534
48535
48536
48537
48538
48539
48540
48541
48542
48543
48544
48545
48546
48547
48548
48549
48550
48551
48552
48553
48554
48555
48556
48557
48558
48559
48560
48561
48562
48563
48564
48565
48566
48567
48568
48569
48570
48571
48572
48573
48574
48575
48576
48577
48578
48579
48580
48581
48582
48583
48584
48585
48586
48587
48588
48589
48590
48591
48592
48593
48594
48595
48596
48597
48598
48599
48600
48601
48602
48603
48604
48605
48606
48607
48608
48609
48610
48611
48612
48613
48614
48615
48616
48617
48618
48619
48620
48621
48622
48623
48624
48625
48626
48627
48628
48629
48630
48631
48632
48633
48634
48635
48636
48637
48638
48639
48640
48641
48642
48643
48644
48645
48646
48647
48648
48649
48650
48651
48652
48653
48654
48655
48656
48657
48658
48659
48660
48661
48662
48663
48664
48665
48666
48667
48668
48669
48670
48671
48672
48673
48674
48675
48676
48677
48678
48679
48680
48681
48682
48683
48684
48685
48686
48687
48688
48689
48690
48691
48692
48693
48694
48695
48696
48697
48698
48699
48700
48701
48702
48703
48704
48705
48706
48707
48708
48709
48710
48711
48712
48713
48714
48715
48716
48717
48718
48719
48720
48721
48722
48723
48724
48725
48726
48727
48728
48729
48730
48731
48732
48733
48734
48735
48736
48737
48738
48739
48740
48741
48742
48743
48744
48745
48746
48747
48748
48749
48750
48751
48752
48753
48754
48755
48756
48757
48758
48759
48760
48761
48762
48763
48764
48765
48766
48767
48768
48769
48770
48771
48772
48773
48774
48775
48776
48777
48778
48779
48780
48781
48782
48783
48784
48785
48786
48787
48788
48789
48790
48791
48792
48793
48794
48795
48796
48797
48798
48799
48800
48801
48802
48803
48804
48805
48806
48807
48808
48809
48810
48811
48812
48813
48814
48815
48816
48817
48818
48819
48820
48821
48822
48823
48824
48825
48826
48827
48828
48829
48830
48831
48832
48833
48834
48835
48836
48837
48838
48839
48840
48841
48842
48843
48844
48845
48846
48847
48848
48849
48850
48851
48852
48853
48854
48855
48856
48857
48858
48859
48860
48861
48862
48863
48864
48865
48866
48867
48868
48869
48870
48871
48872
48873
48874
48875
48876
48877
48878
48879
48880
48881
48882
48883
48884
48885
48886
48887
48888
48889
48890
48891
48892
48893
48894
48895
48896
48897
48898
48899
48900
48901
48902
48903
48904
48905
48906
48907
48908
48909
48910
48911
48912
48913
48914
48915
48916
48917
48918
48919
48920
48921
48922
48923
48924
48925
48926
48927
48928
48929
48930
48931
48932
48933
48934
48935
48936
48937
48938
48939
48940
48941
48942
48943
48944
48945
48946
48947
48948
48949
48950
48951
48952
48953
48954
48955
48956
48957
48958
48959
48960
48961
48962
48963
48964
48965
48966
48967
48968
48969
48970
48971
48972
48973
48974
48975
48976
48977
48978
48979
48980
48981
48982
48983
48984
48985
48986
48987
48988
48989
48990
48991
48992
48993
48994
48995
48996
48997
48998
48999
49000
49001
49002
49003
49004
49005
49006
49007
49008
49009
49010
49011
49012
49013
49014
49015
49016
49017
49018
49019
49020
49021
49022
49023
49024
49025
49026
49027
49028
49029
49030
49031
49032
49033
49034
49035
49036
49037
49038
49039
49040
49041
49042
49043
49044
49045
49046
49047
49048
49049
49050
49051
49052
49053
49054
49055
49056
49057
49058
49059
49060
49061
49062
49063
49064
49065
49066
49067
49068
49069
49070
49071
49072
49073
49074
49075
49076
49077
49078
49079
49080
49081
49082
49083
49084
49085
49086
49087
49088
49089
49090
49091
49092
49093
49094
49095
49096
49097
49098
49099
49100
49101
49102
49103
49104
49105
49106
49107
49108
49109
49110
49111
49112
49113
49114
49115
49116
49117
49118
49119
49120
49121
49122
49123
49124
49125
49126
49127
49128
49129
49130
49131
49132
49133
49134
49135
49136
49137
49138
49139
49140
49141
49142
49143
49144
49145
49146
49147
49148
49149
49150
49151
49152
49153
49154
49155
49156
49157
49158
49159
49160
49161
49162
49163
49164
49165
49166
49167
49168
49169
49170
49171
49172
49173
49174
49175
49176
49177
49178
49179
49180
49181
49182
49183
49184
49185
49186
49187
49188
49189
49190
49191
49192
49193
49194
49195
49196
49197
49198
49199
49200
49201
49202
49203
49204
49205
49206
49207
49208
49209
49210
49211
49212
49213
49214
49215
49216
49217
49218
49219
49220
49221
49222
49223
49224
49225
49226
49227
49228
49229
49230
49231
49232
49233
49234
49235
49236
49237
49238
49239
49240
49241
49242
49243
49244
49245
49246
49247
49248
49249
49250
49251
49252
49253
49254
49255
49256
49257
49258
49259
49260
49261
49262
49263
49264
49265
49266
49267
49268
49269
49270
49271
49272
49273
49274
49275
49276
49277
49278
49279
49280
49281
49282
49283
49284
49285
49286
49287
49288
49289
49290
49291
49292
49293
49294
49295
49296
49297
49298
49299
49300
49301
49302
49303
49304
49305
49306
49307
49308
49309
49310
49311
49312
49313
49314
49315
49316
49317
49318
49319
49320
49321
49322
49323
49324
49325
49326
49327
49328
49329
49330
49331
49332
49333
49334
49335
49336
49337
49338
49339
49340
49341
49342
49343
49344
49345
49346
49347
49348
49349
49350
49351
49352
49353
49354
49355
49356
49357
49358
49359
49360
49361
49362
49363
49364
49365
49366
49367
49368
49369
49370
49371
49372
49373
49374
49375
49376
49377
49378
49379
49380
49381
49382
49383
49384
49385
49386
49387
49388
49389
49390
49391
49392
49393
49394
49395
49396
49397
49398
49399
49400
49401
49402
49403
49404
49405
49406
49407
49408
49409
49410
49411
49412
49413
49414
49415
49416
49417
49418
49419
49420
49421
49422
49423
49424
49425
49426
49427
49428
49429
49430
49431
49432
49433
49434
49435
49436
49437
49438
49439
49440
49441
49442
49443
49444
49445
49446
49447
49448
49449
49450
49451
49452
49453
49454
49455
49456
49457
49458
49459
49460
49461
49462
49463
49464
49465
49466
49467
49468
49469
49470
49471
49472
49473
49474
49475
49476
49477
49478
49479
49480
49481
49482
49483
49484
49485
49486
49487
49488
49489
49490
49491
49492
49493
49494
49495
49496
49497
49498
49499
49500
49501
49502
49503
49504
49505
49506
49507
49508
49509
49510
49511
49512
49513
49514
49515
49516
49517
49518
49519
49520
49521
49522
49523
49524
49525
49526
49527
49528
49529
49530
49531
49532
49533
49534
49535
49536
49537
49538
49539
49540
49541
49542
49543
49544
49545
49546
49547
49548
49549
49550
49551
49552
49553
49554
49555
49556
49557
49558
49559
49560
49561
49562
49563
49564
49565
49566
49567
49568
49569
49570
49571
49572
49573
49574
49575
49576
49577
49578
49579
49580
49581
49582
49583
49584
49585
49586
49587
49588
49589
49590
49591
49592
49593
49594
49595
49596
49597
49598
49599
49600
49601
49602
49603
49604
49605
49606
49607
49608
49609
49610
49611
49612
49613
49614
49615
49616
49617
49618
49619
49620
49621
49622
49623
49624
49625
49626
49627
49628
49629
49630
49631
49632
49633
49634
49635
49636
49637
49638
49639
49640
49641
49642
49643
49644
49645
49646
49647
49648
49649
49650
49651
49652
49653
49654
49655
49656
49657
49658
49659
49660
49661
49662
49663
49664
49665
49666
49667
49668
49669
49670
49671
49672
49673
49674
49675
49676
49677
49678
49679
49680
49681
49682
49683
49684
49685
49686
49687
49688
49689
49690
49691
49692
49693
49694
49695
49696
49697
49698
49699
49700
49701
49702
49703
49704
49705
49706
49707
49708
49709
49710
49711
49712
49713
49714
49715
49716
49717
49718
49719
49720
49721
49722
49723
49724
49725
49726
49727
49728
49729
49730
49731
49732
49733
49734
49735
49736
49737
49738
49739
49740
49741
49742
49743
49744
49745
49746
49747
49748
49749
49750
49751
49752
49753
49754
49755
49756
49757
49758
49759
49760
49761
49762
49763
49764
49765
49766
49767
49768
49769
49770
49771
49772
49773
49774
49775
49776
49777
49778
49779
49780
49781
49782
49783
49784
49785
49786
49787
49788
49789
49790
49791
49792
49793
49794
49795
49796
49797
49798
49799
49800
49801
49802
49803
49804
49805
49806
49807
49808
49809
49810
49811
49812
49813
49814
49815
49816
49817
49818
49819
49820
49821
49822
49823
49824
49825
49826
49827
49828
49829
49830
49831
49832
49833
49834
49835
49836
49837
49838
49839
49840
49841
49842
49843
49844
49845
49846
49847
49848
49849
49850
49851
49852
49853
49854
49855
49856
49857
49858
49859
49860
49861
49862
49863
49864
49865
49866
49867
49868
49869
49870
49871
49872
49873
49874
49875
49876
49877
49878
49879
49880
49881
49882
49883
49884
49885
49886
49887
49888
49889
49890
49891
49892
49893
49894
49895
49896
49897
49898
49899
49900
49901
49902
49903
49904
49905
49906
49907
49908
49909
49910
49911
49912
49913
49914
49915
49916
49917
49918
49919
49920
49921
49922
49923
49924
49925
49926
49927
49928
49929
49930
49931
49932
49933
49934
49935
49936
49937
49938
49939
49940
49941
49942
49943
49944
49945
49946
49947
49948
49949
49950
49951
49952
49953
49954
49955
49956
49957
49958
49959
49960
49961
49962
49963
49964
49965
49966
49967
49968
49969
49970
49971
49972
49973
49974
49975
49976
49977
49978
49979
49980
49981
49982
49983
49984
49985
49986
49987
49988
49989
49990
49991
49992
49993
49994
49995
49996
49997
49998
49999
50000
50001
50002
50003
50004
50005
50006
50007
50008
50009
50010
50011
50012
50013
50014
50015
50016
50017
50018
50019
50020
50021
50022
50023
50024
50025
50026
50027
50028
50029
50030
50031
50032
50033
50034
50035
50036
50037
50038
50039
50040
50041
50042
50043
50044
50045
50046
50047
50048
50049
50050
50051
50052
50053
50054
50055
50056
50057
50058
50059
50060
50061
50062
50063
50064
50065
50066
50067
50068
50069
50070
50071
50072
50073
50074
50075
50076
50077
50078
50079
50080
50081
50082
50083
50084
50085
50086
50087
50088
50089
50090
50091
50092
50093
50094
50095
50096
50097
50098
50099
50100
50101
50102
50103
50104
50105
50106
50107
50108
50109
50110
50111
50112
50113
50114
50115
50116
50117
50118
50119
50120
50121
50122
50123
50124
50125
50126
50127
50128
50129
50130
50131
50132
50133
50134
50135
50136
50137
50138
50139
50140
50141
50142
50143
50144
50145
50146
50147
50148
50149
50150
50151
50152
50153
50154
50155
50156
50157
50158
50159
50160
50161
50162
50163
50164
50165
50166
50167
50168
50169
50170
50171
50172
50173
50174
50175
50176
50177
50178
50179
50180
50181
50182
50183
50184
50185
50186
50187
50188
50189
50190
50191
50192
50193
50194
50195
50196
50197
50198
50199
50200
50201
50202
50203
50204
50205
50206
50207
50208
50209
50210
50211
50212
50213
50214
50215
50216
50217
50218
50219
50220
50221
50222
50223
50224
50225
50226
50227
50228
50229
50230
50231
50232
50233
50234
50235
50236
50237
50238
50239
50240
50241
50242
50243
50244
50245
50246
50247
50248
50249
50250
50251
50252
50253
50254
50255
50256
50257
50258
50259
50260
50261
50262
50263
50264
50265
50266
50267
50268
50269
50270
50271
50272
50273
50274
50275
50276
50277
50278
50279
50280
50281
50282
50283
50284
50285
50286
50287
50288
50289
50290
50291
50292
50293
50294
50295
50296
50297
50298
50299
50300
50301
50302
50303
50304
50305
50306
50307
50308
50309
50310
50311
50312
50313
50314
50315
50316
50317
50318
50319
50320
50321
50322
50323
50324
50325
50326
50327
50328
50329
50330
50331
50332
50333
50334
50335
50336
50337
50338
50339
50340
50341
50342
50343
50344
50345
50346
50347
50348
50349
50350
50351
50352
50353
50354
50355
50356
50357
50358
50359
50360
50361
50362
50363
50364
50365
50366
50367
50368
50369
50370
50371
50372
50373
50374
50375
50376
50377
50378
50379
50380
50381
50382
50383
50384
50385
50386
50387
50388
50389
50390
50391
50392
50393
50394
50395
50396
50397
50398
50399
50400
50401
50402
50403
50404
50405
50406
50407
50408
50409
50410
50411
50412
50413
50414
50415
50416
50417
50418
50419
50420
50421
50422
50423
50424
50425
50426
50427
50428
50429
50430
50431
50432
50433
50434
50435
50436
50437
50438
50439
50440
50441
50442
50443
50444
50445
50446
50447
50448
50449
50450
50451
50452
50453
50454
50455
50456
50457
50458
50459
50460
50461
50462
50463
50464
50465
50466
50467
50468
50469
50470
50471
50472
50473
50474
50475
50476
50477
50478
50479
50480
50481
50482
50483
50484
50485
50486
50487
50488
50489
50490
50491
50492
50493
50494
50495
50496
50497
50498
50499
50500
50501
50502
50503
50504
50505
50506
50507
50508
50509
50510
50511
50512
50513
50514
50515
50516
50517
50518
50519
50520
50521
50522
50523
50524
50525
50526
50527
50528
50529
50530
50531
50532
50533
50534
50535
50536
50537
50538
50539
50540
50541
50542
50543
50544
50545
50546
50547
50548
50549
50550
50551
50552
50553
50554
50555
50556
50557
50558
50559
50560
50561
50562
50563
50564
50565
50566
50567
50568
50569
50570
50571
50572
50573
50574
50575
50576
50577
50578
50579
50580
50581
50582
50583
50584
50585
50586
50587
50588
50589
50590
50591
50592
50593
50594
50595
50596
50597
50598
50599
50600
50601
50602
50603
50604
50605
50606
50607
50608
50609
50610
50611
50612
50613
50614
50615
50616
50617
50618
50619
50620
50621
50622
50623
50624
50625
50626
50627
50628
50629
50630
50631
50632
50633
50634
50635
50636
50637
50638
50639
50640
50641
50642
50643
50644
50645
50646
50647
50648
50649
50650
50651
50652
50653
50654
50655
50656
50657
50658
50659
50660
50661
50662
50663
50664
50665
50666
50667
50668
50669
50670
50671
50672
50673
50674
50675
50676
50677
50678
50679
50680
50681
50682
50683
50684
50685
50686
50687
50688
50689
50690
50691
50692
50693
50694
50695
50696
50697
50698
50699
50700
50701
50702
50703
50704
50705
50706
50707
50708
50709
50710
50711
50712
50713
50714
50715
50716
50717
50718
50719
50720
50721
50722
50723
50724
50725
50726
50727
50728
50729
50730
50731
50732
50733
50734
50735
50736
50737
50738
50739
50740
50741
50742
50743
50744
50745
50746
50747
50748
50749
50750
50751
50752
50753
50754
50755
50756
50757
50758
50759
50760
50761
50762
50763
50764
50765
50766
50767
50768
50769
50770
50771
50772
50773
50774
50775
50776
50777
50778
50779
50780
50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
50794
50795
50796
50797
50798
50799
50800
50801
50802
50803
50804
50805
50806
50807
50808
50809
50810
50811
50812
50813
50814
50815
50816
50817
50818
50819
50820
50821
50822
50823
50824
50825
50826
50827
50828
50829
50830
50831
50832
50833
50834
50835
50836
50837
50838
50839
50840
50841
50842
50843
50844
50845
50846
50847
50848
50849
50850
50851
50852
50853
50854
50855
50856
50857
50858
50859
50860
50861
50862
50863
50864
50865
50866
50867
50868
50869
50870
50871
50872
50873
50874
50875
50876
50877
50878
50879
50880
50881
50882
50883
50884
50885
50886
50887
50888
50889
50890
50891
50892
50893
50894
50895
50896
50897
50898
50899
50900
50901
50902
50903
50904
50905
50906
50907
50908
50909
50910
50911
50912
50913
50914
50915
50916
50917
50918
50919
50920
50921
50922
50923
50924
50925
50926
50927
50928
50929
50930
50931
50932
50933
50934
50935
50936
50937
50938
50939
50940
50941
50942
50943
50944
50945
50946
50947
50948
50949
50950
50951
50952
50953
50954
50955
50956
50957
50958
50959
50960
50961
50962
50963
50964
50965
50966
50967
50968
50969
50970
50971
50972
50973
50974
50975
50976
50977
50978
50979
50980
50981
50982
50983
50984
50985
50986
50987
50988
50989
50990
50991
50992
50993
50994
50995
50996
50997
50998
50999
51000
51001
51002
51003
51004
51005
51006
51007
51008
51009
51010
51011
51012
51013
51014
51015
51016
51017
51018
51019
51020
51021
51022
51023
51024
51025
51026
51027
51028
51029
51030
51031
51032
51033
51034
51035
51036
51037
51038
51039
51040
51041
51042
51043
51044
51045
51046
51047
51048
51049
51050
51051
51052
51053
51054
51055
51056
51057
51058
51059
51060
51061
51062
51063
51064
51065
51066
51067
51068
51069
51070
51071
51072
51073
51074
51075
51076
51077
51078
51079
51080
51081
51082
51083
51084
51085
51086
51087
51088
51089
51090
51091
51092
51093
51094
51095
51096
51097
51098
51099
51100
51101
51102
51103
51104
51105
51106
51107
51108
51109
51110
51111
51112
51113
51114
51115
51116
51117
51118
51119
51120
51121
51122
51123
51124
51125
51126
51127
51128
51129
51130
51131
51132
51133
51134
51135
51136
51137
51138
51139
51140
51141
51142
51143
51144
51145
51146
51147
51148
51149
51150
51151
51152
51153
51154
51155
51156
51157
51158
51159
51160
51161
51162
51163
51164
51165
51166
51167
51168
51169
51170
51171
51172
51173
51174
51175
51176
51177
51178
51179
51180
51181
51182
51183
51184
51185
51186
51187
51188
51189
51190
51191
51192
51193
51194
51195
51196
51197
51198
51199
51200
51201
51202
51203
51204
51205
51206
51207
51208
51209
51210
51211
51212
51213
51214
51215
51216
51217
51218
51219
51220
51221
51222
51223
51224
51225
51226
51227
51228
51229
51230
51231
51232
51233
51234
51235
51236
51237
51238
51239
51240
51241
51242
51243
51244
51245
51246
51247
51248
51249
51250
51251
51252
51253
51254
51255
51256
51257
51258
51259
51260
51261
51262
51263
51264
51265
51266
51267
51268
51269
51270
51271
51272
51273
51274
51275
51276
51277
51278
51279
51280
51281
51282
51283
51284
51285
51286
51287
51288
51289
51290
51291
51292
51293
51294
51295
51296
51297
51298
51299
51300
51301
51302
51303
51304
51305
51306
51307
51308
51309
51310
51311
51312
51313
51314
51315
51316
51317
51318
51319
51320
51321
51322
51323
51324
51325
51326
51327
51328
51329
51330
51331
51332
51333
51334
51335
51336
51337
51338
51339
51340
51341
51342
51343
51344
51345
51346
51347
51348
51349
51350
51351
51352
51353
51354
51355
51356
51357
51358
51359
51360
51361
51362
51363
51364
51365
51366
51367
51368
51369
51370
51371
51372
51373
51374
51375
51376
51377
51378
51379
51380
51381
51382
51383
51384
51385
51386
51387
51388
51389
51390
51391
51392
51393
51394
51395
51396
51397
51398
51399
51400
51401
51402
51403
51404
51405
51406
51407
51408
51409
51410
51411
51412
51413
51414
51415
51416
51417
51418
51419
51420
51421
51422
51423
51424
51425
51426
51427
51428
51429
51430
51431
51432
51433
51434
51435
51436
51437
51438
51439
51440
51441
51442
51443
51444
51445
51446
51447
51448
51449
51450
51451
51452
51453
51454
51455
51456
51457
51458
51459
51460
51461
51462
51463
51464
51465
51466
51467
51468
51469
51470
51471
51472
51473
51474
51475
51476
51477
51478
51479
51480
51481
51482
51483
51484
51485
51486
51487
51488
51489
51490
51491
51492
51493
51494
51495
51496
51497
51498
51499
51500
51501
51502
51503
51504
51505
51506
51507
51508
51509
51510
51511
51512
51513
51514
51515
51516
51517
51518
51519
51520
51521
51522
51523
51524
51525
51526
51527
51528
51529
51530
51531
51532
51533
51534
51535
51536
51537
51538
51539
51540
51541
51542
51543
51544
51545
51546
51547
51548
51549
51550
51551
51552
51553
51554
51555
51556
51557
51558
51559
51560
51561
51562
51563
51564
51565
51566
51567
51568
51569
51570
51571
51572
51573
51574
51575
51576
51577
51578
51579
51580
51581
51582
51583
51584
51585
51586
51587
51588
51589
51590
51591
51592
51593
51594
51595
51596
51597
51598
51599
51600
51601
51602
51603
51604
51605
51606
51607
51608
51609
51610
51611
51612
51613
51614
51615
51616
51617
51618
51619
51620
51621
51622
51623
51624
51625
51626
51627
51628
51629
51630
51631
51632
51633
51634
51635
51636
51637
51638
51639
51640
51641
51642
51643
51644
51645
51646
51647
51648
51649
51650
51651
51652
51653
51654
51655
51656
51657
51658
51659
51660
51661
51662
51663
51664
51665
51666
51667
51668
51669
51670
51671
51672
51673
51674
51675
51676
51677
51678
51679
51680
51681
51682
51683
51684
51685
51686
51687
51688
51689
51690
51691
51692
51693
51694
51695
51696
51697
51698
51699
51700
51701
51702
51703
51704
51705
51706
51707
51708
51709
51710
51711
51712
51713
51714
51715
51716
51717
51718
51719
51720
51721
51722
51723
51724
51725
51726
51727
51728
51729
51730
51731
51732
51733
51734
51735
51736
51737
51738
51739
51740
51741
51742
51743
51744
51745
51746
51747
51748
51749
51750
51751
51752
51753
51754
51755
51756
51757
51758
51759
51760
51761
51762
51763
51764
51765
51766
51767
51768
51769
51770
51771
51772
51773
51774
51775
51776
51777
51778
51779
51780
51781
51782
51783
51784
51785
51786
51787
51788
51789
51790
51791
51792
51793
51794
51795
51796
51797
51798
51799
51800
51801
51802
51803
51804
51805
51806
51807
51808
51809
51810
51811
51812
51813
51814
51815
51816
51817
51818
51819
51820
51821
51822
51823
51824
51825
51826
51827
51828
51829
51830
51831
51832
51833
51834
51835
51836
51837
51838
51839
51840
51841
51842
51843
51844
51845
51846
51847
51848
51849
51850
51851
51852
51853
51854
51855
51856
51857
51858
51859
51860
51861
51862
51863
51864
51865
51866
51867
51868
51869
51870
51871
51872
51873
51874
51875
51876
51877
51878
51879
51880
51881
51882
51883
51884
51885
51886
51887
51888
51889
51890
51891
51892
51893
51894
51895
51896
51897
51898
51899
51900
51901
51902
51903
51904
51905
51906
51907
51908
51909
51910
51911
51912
51913
51914
51915
51916
51917
51918
51919
51920
51921
51922
51923
51924
51925
51926
51927
51928
51929
51930
51931
51932
51933
51934
51935
51936
51937
51938
51939
51940
51941
51942
51943
51944
51945
51946
51947
51948
51949
51950
51951
51952
51953
51954
51955
51956
51957
51958
51959
51960
51961
51962
51963
51964
51965
51966
51967
51968
51969
51970
51971
51972
51973
51974
51975
51976
51977
51978
51979
51980
51981
51982
51983
51984
51985
51986
51987
51988
51989
51990
51991
51992
51993
51994
51995
51996
51997
51998
51999
52000
52001
52002
52003
52004
52005
52006
52007
52008
52009
52010
52011
52012
52013
52014
52015
52016
52017
52018
52019
52020
52021
52022
52023
52024
52025
52026
52027
52028
52029
52030
52031
52032
52033
52034
52035
52036
52037
52038
52039
52040
52041
52042
52043
52044
52045
52046
52047
52048
52049
52050
52051
52052
52053
52054
52055
52056
52057
52058
52059
52060
52061
52062
52063
52064
52065
52066
52067
52068
52069
52070
52071
52072
52073
52074
52075
52076
52077
52078
52079
52080
52081
52082
52083
52084
52085
52086
52087
52088
52089
52090
52091
52092
52093
52094
52095
52096
52097
52098
52099
52100
52101
52102
52103
52104
52105
52106
52107
52108
52109
52110
52111
52112
52113
52114
52115
52116
52117
52118
52119
52120
52121
52122
52123
52124
52125
52126
52127
52128
52129
52130
52131
52132
52133
52134
52135
52136
52137
52138
52139
52140
52141
52142
52143
52144
52145
52146
52147
52148
52149
52150
52151
52152
52153
52154
52155
52156
52157
52158
52159
52160
52161
52162
52163
52164
52165
52166
52167
52168
52169
52170
52171
52172
52173
52174
52175
52176
52177
52178
52179
52180
52181
52182
52183
52184
52185
52186
52187
52188
52189
52190
52191
52192
52193
52194
52195
52196
52197
52198
52199
52200
52201
52202
52203
52204
52205
52206
52207
52208
52209
52210
52211
52212
52213
52214
52215
52216
52217
52218
52219
52220
52221
52222
52223
52224
52225
52226
52227
52228
52229
52230
52231
52232
52233
52234
52235
52236
52237
52238
52239
52240
52241
52242
52243
52244
52245
52246
52247
52248
52249
52250
52251
52252
52253
52254
52255
52256
52257
52258
52259
52260
52261
52262
52263
52264
52265
52266
52267
52268
52269
52270
52271
52272
52273
52274
52275
52276
52277
52278
52279
52280
52281
52282
52283
52284
52285
52286
52287
52288
52289
52290
52291
52292
52293
52294
52295
52296
52297
52298
52299
52300
52301
52302
52303
52304
52305
52306
52307
52308
52309
52310
52311
52312
52313
52314
52315
52316
52317
52318
52319
52320
52321
52322
52323
52324
52325
52326
52327
52328
52329
52330
52331
52332
52333
52334
52335
52336
52337
52338
52339
52340
52341
52342
52343
52344
52345
52346
52347
52348
52349
52350
52351
52352
52353
52354
52355
52356
52357
52358
52359
52360
52361
52362
52363
52364
52365
52366
52367
52368
52369
52370
52371
52372
52373
52374
52375
52376
52377
52378
52379
52380
52381
52382
52383
52384
52385
52386
52387
52388
52389
52390
52391
52392
52393
52394
52395
52396
52397
52398
52399
52400
52401
52402
52403
52404
52405
52406
52407
52408
52409
52410
52411
52412
52413
52414
52415
52416
52417
52418
52419
52420
52421
52422
52423
52424
52425
52426
52427
52428
52429
52430
52431
52432
52433
52434
52435
52436
52437
52438
52439
52440
52441
52442
52443
52444
52445
52446
52447
52448
52449
52450
52451
52452
52453
52454
52455
52456
52457
52458
52459
52460
52461
52462
52463
52464
52465
52466
52467
52468
52469
52470
52471
52472
52473
52474
52475
52476
52477
52478
52479
52480
52481
52482
52483
52484
52485
52486
52487
52488
52489
52490
52491
52492
52493
52494
52495
52496
52497
52498
52499
52500
52501
52502
52503
52504
52505
52506
52507
52508
52509
52510
52511
52512
52513
52514
52515
52516
52517
52518
52519
52520
52521
52522
52523
52524
52525
52526
52527
52528
52529
52530
52531
52532
52533
52534
52535
52536
52537
52538
52539
52540
52541
52542
52543
52544
52545
52546
52547
52548
52549
52550
52551
52552
52553
52554
52555
52556
52557
52558
52559
52560
52561
52562
52563
52564
52565
52566
52567
52568
52569
52570
52571
52572
52573
52574
52575
52576
52577
52578
52579
52580
52581
52582
52583
52584
52585
52586
52587
52588
52589
52590
52591
52592
52593
52594
52595
52596
52597
52598
52599
52600
52601
52602
52603
52604
52605
52606
52607
52608
52609
52610
52611
52612
52613
52614
52615
52616
52617
52618
52619
52620
52621
52622
52623
52624
52625
52626
52627
52628
52629
52630
52631
52632
52633
52634
52635
52636
52637
52638
52639
52640
52641
52642
52643
52644
52645
52646
52647
52648
52649
52650
52651
52652
52653
52654
52655
52656
52657
52658
52659
52660
52661
52662
52663
52664
52665
52666
52667
52668
52669
52670
52671
52672
52673
52674
52675
52676
52677
52678
52679
52680
52681
52682
52683
52684
52685
52686
52687
52688
52689
52690
52691
52692
52693
52694
52695
52696
52697
52698
52699
52700
52701
52702
52703
52704
52705
52706
52707
52708
52709
52710
52711
52712
52713
52714
52715
52716
52717
52718
52719
52720
52721
52722
52723
52724
52725
52726
52727
52728
52729
52730
52731
52732
52733
52734
52735
52736
52737
52738
52739
52740
52741
52742
52743
52744
52745
52746
52747
52748
52749
52750
52751
52752
52753
52754
52755
52756
52757
52758
52759
52760
52761
52762
52763
52764
52765
52766
52767
52768
52769
52770
52771
52772
52773
52774
52775
52776
52777
52778
52779
52780
52781
52782
52783
52784
52785
52786
52787
52788
52789
52790
52791
52792
52793
52794
52795
52796
52797
52798
52799
52800
52801
52802
52803
52804
52805
52806
52807
52808
52809
52810
52811
52812
52813
52814
52815
52816
52817
52818
52819
52820
52821
52822
52823
52824
52825
52826
52827
52828
52829
52830
52831
52832
52833
52834
52835
52836
52837
52838
52839
52840
52841
52842
52843
52844
52845
52846
52847
52848
52849
52850
52851
52852
52853
52854
52855
52856
52857
52858
52859
52860
52861
52862
52863
52864
52865
52866
52867
52868
52869
52870
52871
52872
52873
52874
52875
52876
52877
52878
52879
52880
52881
52882
52883
52884
52885
52886
52887
52888
52889
52890
52891
52892
52893
52894
52895
52896
52897
52898
52899
52900
52901
52902
52903
52904
52905
52906
52907
52908
52909
52910
52911
52912
52913
52914
52915
52916
52917
52918
52919
52920
52921
52922
52923
52924
52925
52926
52927
52928
52929
52930
52931
52932
52933
52934
52935
52936
52937
52938
52939
52940
52941
52942
52943
52944
52945
52946
52947
52948
52949
52950
52951
52952
52953
52954
52955
52956
52957
52958
52959
52960
52961
52962
52963
52964
52965
52966
52967
52968
52969
52970
52971
52972
52973
52974
52975
52976
52977
52978
52979
52980
52981
52982
52983
52984
52985
52986
52987
52988
52989
52990
52991
52992
52993
52994
52995
52996
52997
52998
52999
53000
53001
53002
53003
53004
53005
53006
53007
53008
53009
53010
53011
53012
53013
53014
53015
53016
53017
53018
53019
53020
53021
53022
53023
53024
53025
53026
53027
53028
53029
53030
53031
53032
53033
53034
53035
53036
53037
53038
53039
53040
53041
53042
53043
53044
53045
53046
53047
53048
53049
53050
53051
53052
53053
53054
53055
53056
53057
53058
53059
53060
53061
53062
53063
53064
53065
53066
53067
53068
53069
53070
53071
53072
53073
53074
53075
53076
53077
53078
53079
53080
53081
53082
53083
53084
53085
53086
53087
53088
53089
53090
53091
53092
53093
53094
53095
53096
53097
53098
53099
53100
53101
53102
53103
53104
53105
53106
53107
53108
53109
53110
53111
53112
53113
53114
53115
53116
53117
53118
53119
53120
53121
53122
53123
53124
53125
53126
53127
53128
53129
53130
53131
53132
53133
53134
53135
53136
53137
53138
53139
53140
53141
53142
53143
53144
53145
53146
53147
53148
53149
53150
53151
53152
53153
53154
53155
53156
53157
53158
53159
53160
53161
53162
53163
53164
53165
53166
53167
53168
53169
53170
53171
53172
53173
53174
53175
53176
53177
53178
53179
53180
53181
53182
53183
53184
53185
53186
53187
53188
53189
53190
53191
53192
53193
53194
53195
53196
53197
53198
53199
53200
53201
53202
53203
53204
53205
53206
53207
53208
53209
53210
53211
53212
53213
53214
53215
53216
53217
53218
53219
53220
53221
53222
53223
53224
53225
53226
53227
53228
53229
53230
53231
53232
53233
53234
53235
53236
53237
53238
53239
53240
53241
53242
53243
53244
53245
53246
53247
53248
53249
53250
53251
53252
53253
53254
53255
53256
53257
53258
53259
53260
53261
53262
53263
53264
53265
53266
53267
53268
53269
53270
53271
53272
53273
53274
53275
53276
53277
53278
53279
53280
53281
53282
53283
53284
53285
53286
53287
53288
53289
53290
53291
53292
53293
53294
53295
53296
53297
53298
53299
53300
53301
53302
53303
53304
53305
53306
53307
53308
53309
53310
53311
53312
53313
53314
53315
53316
53317
53318
53319
53320
53321
53322
53323
53324
53325
53326
53327
53328
53329
53330
53331
53332
53333
53334
53335
53336
53337
53338
53339
53340
53341
53342
53343
53344
53345
53346
53347
53348
53349
53350
53351
53352
53353
53354
53355
53356
53357
53358
53359
53360
53361
53362
53363
53364
53365
53366
53367
53368
53369
53370
53371
53372
53373
53374
53375
53376
53377
53378
53379
53380
53381
53382
53383
53384
53385
53386
53387
53388
53389
53390
53391
53392
53393
53394
53395
53396
53397
53398
53399
53400
53401
53402
53403
53404
53405
53406
53407
53408
53409
53410
53411
53412
53413
53414
53415
53416
53417
53418
53419
53420
53421
53422
53423
53424
53425
53426
53427
53428
53429
53430
53431
53432
53433
53434
53435
53436
53437
53438
53439
53440
53441
53442
53443
53444
53445
53446
53447
53448
53449
53450
53451
53452
53453
53454
53455
53456
53457
53458
53459
53460
53461
53462
53463
53464
53465
53466
53467
53468
53469
53470
53471
53472
53473
53474
53475
53476
53477
53478
53479
53480
53481
53482
53483
53484
53485
53486
53487
53488
53489
53490
53491
53492
53493
53494
53495
53496
53497
53498
53499
53500
53501
53502
53503
53504
53505
53506
53507
53508
53509
53510
53511
53512
53513
53514
53515
53516
53517
53518
53519
53520
53521
53522
53523
53524
53525
53526
53527
53528
53529
53530
53531
53532
53533
53534
53535
53536
53537
53538
53539
53540
53541
53542
53543
53544
53545
53546
53547
53548
53549
53550
53551
53552
53553
53554
53555
53556
53557
53558
53559
53560
53561
53562
53563
53564
53565
53566
53567
53568
53569
53570
53571
53572
53573
53574
53575
53576
53577
53578
53579
53580
53581
53582
53583
53584
53585
53586
53587
53588
53589
53590
53591
53592
53593
53594
53595
53596
53597
53598
53599
53600
53601
53602
53603
53604
53605
53606
53607
53608
53609
53610
53611
53612
53613
53614
53615
53616
53617
53618
53619
53620
53621
53622
53623
53624
53625
53626
53627
53628
53629
53630
53631
53632
53633
53634
53635
53636
53637
53638
53639
53640
53641
53642
53643
53644
53645
53646
53647
53648
53649
53650
53651
53652
53653
53654
53655
53656
53657
53658
53659
53660
53661
53662
53663
53664
53665
53666
53667
53668
53669
53670
53671
53672
53673
53674
53675
53676
53677
53678
53679
53680
53681
53682
53683
53684
53685
53686
53687
53688
53689
53690
53691
53692
53693
53694
53695
53696
53697
53698
53699
53700
53701
53702
53703
53704
53705
53706
53707
53708
53709
53710
53711
53712
53713
53714
53715
53716
53717
53718
53719
53720
53721
53722
53723
53724
53725
53726
53727
53728
53729
53730
53731
53732
53733
53734
53735
53736
53737
53738
53739
53740
53741
53742
53743
53744
53745
53746
53747
53748
53749
53750
53751
53752
53753
53754
53755
53756
53757
53758
53759
53760
53761
53762
53763
53764
53765
53766
53767
53768
53769
53770
53771
53772
53773
53774
53775
53776
53777
53778
53779
53780
53781
53782
53783
53784
53785
53786
53787
53788
53789
53790
53791
53792
53793
53794
53795
53796
53797
53798
53799
53800
53801
53802
53803
53804
53805
53806
53807
53808
53809
53810
53811
53812
53813
53814
53815
53816
53817
53818
53819
53820
53821
53822
53823
53824
53825
53826
53827
53828
53829
53830
53831
53832
53833
53834
53835
53836
53837
53838
53839
53840
53841
53842
53843
53844
53845
53846
53847
53848
53849
53850
53851
53852
53853
53854
53855
53856
53857
53858
53859
53860
53861
53862
53863
53864
53865
53866
53867
53868
53869
53870
53871
53872
53873
53874
53875
53876
53877
53878
53879
53880
53881
53882
53883
53884
53885
53886
53887
53888
53889
53890
53891
53892
53893
53894
53895
53896
53897
53898
53899
53900
53901
53902
53903
53904
53905
53906
53907
53908
53909
53910
53911
53912
53913
53914
53915
53916
53917
53918
53919
53920
53921
53922
53923
53924
53925
53926
53927
53928
53929
53930
53931
53932
53933
53934
53935
53936
53937
53938
53939
53940
53941
53942
53943
53944
53945
53946
53947
53948
53949
53950
53951
53952
53953
53954
53955
53956
53957
53958
53959
53960
53961
53962
53963
53964
53965
53966
53967
53968
53969
53970
53971
53972
53973
53974
53975
53976
53977
53978
53979
53980
53981
53982
53983
53984
53985
53986
53987
53988
53989
53990
53991
53992
53993
53994
53995
53996
53997
53998
53999
54000
54001
54002
54003
54004
54005
54006
54007
54008
54009
54010
54011
54012
54013
54014
54015
54016
54017
54018
54019
54020
54021
54022
54023
54024
54025
54026
54027
54028
54029
54030
54031
54032
54033
54034
54035
54036
54037
54038
54039
54040
54041
54042
54043
54044
54045
54046
54047
54048
54049
54050
54051
54052
54053
54054
54055
54056
54057
54058
54059
54060
54061
54062
54063
54064
54065
54066
54067
54068
54069
54070
54071
54072
54073
54074
54075
54076
54077
54078
54079
54080
54081
54082
54083
54084
54085
54086
54087
54088
54089
54090
54091
54092
54093
54094
54095
54096
54097
54098
54099
54100
54101
54102
54103
54104
54105
54106
54107
54108
54109
54110
54111
54112
54113
54114
54115
54116
54117
54118
54119
54120
54121
54122
54123
54124
54125
54126
54127
54128
54129
54130
54131
54132
54133
54134
54135
54136
54137
54138
54139
54140
54141
54142
54143
54144
54145
54146
54147
54148
54149
54150
54151
54152
54153
54154
54155
54156
54157
54158
54159
54160
54161
54162
54163
54164
54165
54166
54167
54168
54169
54170
54171
54172
54173
54174
54175
54176
54177
54178
54179
54180
54181
54182
54183
54184
54185
54186
54187
54188
54189
54190
54191
54192
54193
54194
54195
54196
54197
54198
54199
54200
54201
54202
54203
54204
54205
54206
54207
54208
54209
54210
54211
54212
54213
54214
54215
54216
54217
54218
54219
54220
54221
54222
54223
54224
54225
54226
54227
54228
54229
54230
54231
54232
54233
54234
54235
54236
54237
54238
54239
54240
54241
54242
54243
54244
54245
54246
54247
54248
54249
54250
54251
54252
54253
54254
54255
54256
54257
54258
54259
54260
54261
54262
54263
54264
54265
54266
54267
54268
54269
54270
54271
54272
54273
54274
54275
54276
54277
54278
54279
54280
54281
54282
54283
54284
54285
54286
54287
54288
54289
54290
54291
54292
54293
54294
54295
54296
54297
54298
54299
54300
54301
54302
54303
54304
54305
54306
54307
54308
54309
54310
54311
54312
54313
54314
54315
54316
54317
54318
54319
54320
54321
54322
54323
54324
54325
54326
54327
54328
54329
54330
54331
54332
54333
54334
54335
54336
54337
54338
54339
54340
54341
54342
54343
54344
54345
54346
54347
54348
54349
54350
54351
54352
54353
54354
54355
54356
54357
54358
54359
54360
54361
54362
54363
54364
54365
54366
54367
54368
54369
54370
54371
54372
54373
54374
54375
54376
54377
54378
54379
54380
54381
54382
54383
54384
54385
54386
54387
54388
54389
54390
54391
54392
54393
54394
54395
54396
54397
54398
54399
54400
54401
54402
54403
54404
54405
54406
54407
54408
54409
54410
54411
54412
54413
54414
54415
54416
54417
54418
54419
54420
54421
54422
54423
54424
54425
54426
54427
54428
54429
54430
54431
54432
54433
54434
54435
54436
54437
54438
54439
54440
54441
54442
54443
54444
54445
54446
54447
54448
54449
54450
54451
54452
54453
54454
54455
54456
54457
54458
54459
54460
54461
54462
54463
54464
54465
54466
54467
54468
54469
54470
54471
54472
54473
54474
54475
54476
54477
54478
54479
54480
54481
54482
54483
54484
54485
54486
54487
54488
54489
54490
54491
54492
54493
54494
54495
54496
54497
54498
54499
54500
54501
54502
54503
54504
54505
54506
54507
54508
54509
54510
54511
54512
54513
54514
54515
54516
54517
54518
54519
54520
54521
54522
54523
54524
54525
54526
54527
54528
54529
54530
54531
54532
54533
54534
54535
54536
54537
54538
54539
54540
54541
54542
54543
54544
54545
54546
54547
54548
54549
54550
54551
54552
54553
54554
54555
54556
54557
54558
54559
54560
54561
54562
54563
54564
54565
54566
54567
54568
54569
54570
54571
54572
54573
54574
54575
54576
54577
54578
54579
54580
54581
54582
54583
54584
54585
54586
54587
54588
54589
54590
54591
54592
54593
54594
54595
54596
54597
54598
54599
54600
54601
54602
54603
54604
54605
54606
54607
54608
54609
54610
54611
54612
54613
54614
54615
54616
54617
54618
54619
54620
54621
54622
54623
54624
54625
54626
54627
54628
54629
54630
54631
54632
54633
54634
54635
54636
54637
54638
54639
54640
54641
54642
54643
54644
54645
54646
54647
54648
54649
54650
54651
54652
54653
54654
54655
54656
54657
54658
54659
54660
54661
54662
54663
54664
54665
54666
54667
54668
54669
54670
54671
54672
54673
54674
54675
54676
54677
54678
54679
54680
54681
54682
54683
54684
54685
54686
54687
54688
54689
54690
54691
54692
54693
54694
54695
54696
54697
54698
54699
54700
54701
54702
54703
54704
54705
54706
54707
54708
54709
54710
54711
54712
54713
54714
54715
54716
54717
54718
54719
54720
54721
54722
54723
54724
54725
54726
54727
54728
54729
54730
54731
54732
54733
54734
54735
54736
54737
54738
54739
54740
54741
54742
54743
54744
54745
54746
54747
54748
54749
54750
54751
54752
54753
54754
54755
54756
54757
54758
54759
54760
54761
54762
54763
54764
54765
54766
54767
54768
54769
54770
54771
54772
54773
54774
54775
54776
54777
54778
54779
54780
54781
54782
54783
54784
54785
54786
54787
54788
54789
54790
54791
54792
54793
54794
54795
54796
54797
54798
54799
54800
54801
54802
54803
54804
54805
54806
54807
54808
54809
54810
54811
54812
54813
54814
54815
54816
54817
54818
54819
54820
54821
54822
54823
54824
54825
54826
54827
54828
54829
54830
54831
54832
54833
54834
54835
54836
54837
54838
54839
54840
54841
54842
54843
54844
54845
54846
54847
54848
54849
54850
54851
54852
54853
54854
54855
54856
54857
54858
54859
54860
54861
54862
54863
54864
54865
54866
54867
54868
54869
54870
54871
54872
54873
54874
54875
54876
54877
54878
54879
54880
54881
54882
54883
54884
54885
54886
54887
54888
54889
54890
54891
54892
54893
54894
54895
54896
54897
54898
54899
54900
54901
54902
54903
54904
54905
54906
54907
54908
54909
54910
54911
54912
54913
54914
54915
54916
54917
54918
54919
54920
54921
54922
54923
54924
54925
54926
54927
54928
54929
54930
54931
54932
54933
54934
54935
54936
54937
54938
54939
54940
54941
54942
54943
54944
54945
54946
54947
54948
54949
54950
54951
54952
54953
54954
54955
54956
54957
54958
54959
54960
54961
54962
54963
54964
54965
54966
54967
54968
54969
54970
54971
54972
54973
54974
54975
54976
54977
54978
54979
54980
54981
54982
54983
54984
54985
54986
54987
54988
54989
54990
54991
54992
54993
54994
54995
54996
54997
54998
54999
55000
55001
55002
55003
55004
55005
55006
55007
55008
55009
55010
55011
55012
55013
55014
55015
55016
55017
55018
55019
55020
55021
55022
55023
55024
55025
55026
55027
55028
55029
55030
55031
55032
55033
55034
55035
55036
55037
55038
55039
55040
55041
55042
55043
55044
55045
55046
55047
55048
55049
55050
55051
55052
55053
55054
55055
55056
55057
55058
55059
55060
55061
55062
55063
55064
55065
55066
55067
55068
55069
55070
55071
55072
55073
55074
55075
55076
55077
55078
55079
55080
55081
55082
55083
55084
55085
55086
55087
55088
55089
55090
55091
55092
55093
55094
55095
55096
55097
55098
55099
55100
55101
55102
55103
55104
55105
55106
55107
55108
55109
55110
55111
55112
55113
55114
55115
55116
55117
55118
55119
55120
55121
55122
55123
55124
55125
55126
55127
55128
55129
55130
55131
55132
55133
55134
55135
55136
55137
55138
55139
55140
55141
55142
55143
55144
55145
55146
55147
55148
55149
55150
55151
55152
55153
55154
55155
55156
55157
55158
55159
55160
55161
55162
55163
55164
55165
55166
55167
55168
55169
55170
55171
55172
55173
55174
55175
55176
55177
55178
55179
55180
55181
55182
55183
55184
55185
55186
55187
55188
55189
55190
55191
55192
55193
55194
55195
55196
55197
55198
55199
55200
55201
55202
55203
55204
55205
55206
55207
55208
55209
55210
55211
55212
55213
55214
55215
55216
55217
55218
55219
55220
55221
55222
55223
55224
55225
55226
55227
55228
55229
55230
55231
55232
55233
55234
55235
55236
55237
55238
55239
55240
55241
55242
55243
55244
55245
55246
55247
55248
55249
55250
55251
55252
55253
55254
55255
55256
55257
55258
55259
55260
55261
55262
55263
55264
55265
55266
55267
55268
55269
55270
55271
55272
55273
55274
55275
55276
55277
55278
55279
55280
55281
55282
55283
55284
55285
55286
55287
55288
55289
55290
55291
55292
55293
55294
55295
55296
55297
55298
55299
55300
55301
55302
55303
55304
55305
55306
55307
55308
55309
55310
55311
55312
55313
55314
55315
55316
55317
55318
55319
55320
55321
55322
55323
55324
55325
55326
55327
55328
55329
55330
55331
55332
55333
55334
55335
55336
55337
55338
55339
55340
55341
55342
55343
55344
55345
55346
55347
55348
55349
55350
55351
55352
55353
55354
55355
55356
55357
55358
55359
55360
55361
55362
55363
55364
55365
55366
55367
55368
55369
55370
55371
55372
55373
55374
55375
55376
55377
55378
55379
55380
55381
55382
55383
55384
55385
55386
55387
55388
55389
55390
55391
55392
55393
55394
55395
55396
55397
55398
55399
55400
55401
55402
55403
55404
55405
55406
55407
55408
55409
55410
55411
55412
55413
55414
55415
55416
55417
55418
55419
55420
55421
55422
55423
55424
55425
55426
55427
55428
55429
55430
55431
55432
55433
55434
55435
55436
55437
55438
55439
55440
55441
55442
55443
55444
55445
55446
55447
55448
55449
55450
55451
55452
55453
55454
55455
55456
55457
55458
55459
55460
55461
55462
55463
55464
55465
55466
55467
55468
55469
55470
55471
55472
55473
55474
55475
55476
55477
55478
55479
55480
55481
55482
55483
55484
55485
55486
55487
55488
55489
55490
55491
55492
55493
55494
55495
55496
55497
55498
55499
55500
55501
55502
55503
55504
55505
55506
55507
55508
55509
55510
55511
55512
55513
55514
55515
55516
55517
55518
55519
55520
55521
55522
55523
55524
55525
55526
55527
55528
55529
55530
55531
55532
55533
55534
55535
55536
55537
55538
55539
55540
55541
55542
55543
55544
55545
55546
55547
55548
55549
55550
55551
55552
55553
55554
55555
55556
55557
55558
55559
55560
55561
55562
55563
55564
55565
55566
55567
55568
55569
55570
55571
55572
55573
55574
55575
55576
55577
55578
55579
55580
55581
55582
55583
55584
55585
55586
55587
55588
55589
55590
55591
55592
55593
55594
55595
55596
55597
55598
55599
55600
55601
55602
55603
55604
55605
55606
55607
55608
55609
55610
55611
55612
55613
55614
55615
55616
55617
55618
55619
55620
55621
55622
55623
55624
55625
55626
55627
55628
55629
55630
55631
55632
55633
55634
55635
55636
55637
55638
55639
55640
55641
55642
55643
55644
55645
55646
55647
55648
55649
55650
55651
55652
55653
55654
55655
55656
55657
55658
55659
55660
55661
55662
55663
55664
55665
55666
55667
55668
55669
55670
55671
55672
55673
55674
55675
55676
55677
55678
55679
55680
55681
55682
55683
55684
55685
55686
55687
55688
55689
55690
55691
55692
55693
55694
55695
55696
55697
55698
55699
55700
55701
55702
55703
55704
55705
55706
55707
55708
55709
55710
55711
55712
55713
55714
55715
55716
55717
55718
55719
55720
55721
55722
55723
55724
55725
55726
55727
55728
55729
55730
55731
55732
55733
55734
55735
55736
55737
55738
55739
55740
55741
55742
55743
55744
55745
55746
55747
55748
55749
55750
55751
55752
55753
55754
55755
55756
55757
55758
55759
55760
55761
55762
55763
55764
55765
55766
55767
55768
55769
55770
55771
55772
55773
55774
55775
55776
55777
55778
55779
55780
55781
55782
55783
55784
55785
55786
55787
55788
55789
55790
55791
55792
55793
55794
55795
55796
55797
55798
55799
55800
55801
55802
55803
55804
55805
55806
55807
55808
55809
55810
55811
55812
55813
55814
55815
55816
55817
55818
55819
55820
55821
55822
55823
55824
55825
55826
55827
55828
55829
55830
55831
55832
55833
55834
55835
55836
55837
55838
55839
55840
55841
55842
55843
55844
55845
55846
55847
55848
55849
55850
55851
55852
55853
55854
55855
55856
55857
55858
55859
55860
55861
55862
55863
55864
55865
55866
55867
55868
55869
55870
55871
55872
55873
55874
55875
55876
55877
55878
55879
55880
55881
55882
55883
55884
55885
55886
55887
55888
55889
55890
55891
55892
55893
55894
55895
55896
55897
55898
55899
55900
55901
55902
55903
55904
55905
55906
55907
55908
55909
55910
55911
55912
55913
55914
55915
55916
55917
55918
55919
55920
55921
55922
55923
55924
55925
55926
55927
55928
55929
55930
55931
55932
55933
55934
55935
55936
55937
55938
55939
55940
55941
55942
55943
55944
55945
55946
55947
55948
55949
55950
55951
55952
55953
55954
55955
55956
55957
55958
55959
55960
55961
55962
55963
55964
55965
55966
55967
55968
55969
55970
55971
55972
55973
55974
55975
55976
55977
55978
55979
55980
55981
55982
55983
55984
55985
55986
55987
55988
55989
55990
55991
55992
55993
55994
55995
55996
55997
55998
55999
56000
56001
56002
56003
56004
56005
56006
56007
56008
56009
56010
56011
56012
56013
56014
56015
56016
56017
56018
56019
56020
56021
56022
56023
56024
56025
56026
56027
56028
56029
56030
56031
56032
56033
56034
56035
56036
56037
56038
56039
56040
56041
56042
56043
56044
56045
56046
56047
56048
56049
56050
56051
56052
56053
56054
56055
56056
56057
56058
56059
56060
56061
56062
56063
56064
56065
56066
56067
56068
56069
56070
56071
56072
56073
56074
56075
56076
56077
56078
56079
56080
56081
56082
56083
56084
56085
56086
56087
56088
56089
56090
56091
56092
56093
56094
56095
56096
56097
56098
56099
56100
56101
56102
56103
56104
56105
56106
56107
56108
56109
56110
56111
56112
56113
56114
56115
56116
56117
56118
56119
56120
56121
56122
56123
56124
56125
56126
56127
56128
56129
56130
56131
56132
56133
56134
56135
56136
56137
56138
56139
56140
56141
56142
56143
56144
56145
56146
56147
56148
56149
56150
56151
56152
56153
56154
56155
56156
56157
56158
56159
56160
56161
56162
56163
56164
56165
56166
56167
56168
56169
56170
56171
56172
56173
56174
56175
56176
56177
56178
56179
56180
56181
56182
56183
56184
56185
56186
56187
56188
56189
56190
56191
56192
56193
56194
56195
56196
56197
56198
56199
56200
56201
56202
56203
56204
56205
56206
56207
56208
56209
56210
56211
56212
56213
56214
56215
56216
56217
56218
56219
56220
56221
56222
56223
56224
56225
56226
56227
56228
56229
56230
56231
56232
56233
56234
56235
56236
56237
56238
56239
56240
56241
56242
56243
56244
56245
56246
56247
56248
56249
56250
56251
56252
56253
56254
56255
56256
56257
56258
56259
56260
56261
56262
56263
56264
56265
56266
56267
56268
56269
56270
56271
56272
56273
56274
56275
56276
56277
56278
56279
56280
56281
56282
56283
56284
56285
56286
56287
56288
56289
56290
56291
56292
56293
56294
56295
56296
56297
56298
56299
56300
56301
56302
56303
56304
56305
56306
56307
56308
56309
56310
56311
56312
56313
56314
56315
56316
56317
56318
56319
56320
56321
56322
56323
56324
56325
56326
56327
56328
56329
56330
56331
56332
56333
56334
56335
56336
56337
56338
56339
56340
56341
56342
56343
56344
56345
56346
56347
56348
56349
56350
56351
56352
56353
56354
56355
56356
56357
56358
56359
56360
56361
56362
56363
56364
56365
56366
56367
56368
56369
56370
56371
56372
56373
56374
56375
56376
56377
56378
56379
56380
56381
56382
56383
56384
56385
56386
56387
56388
56389
56390
56391
56392
56393
56394
56395
56396
56397
56398
56399
56400
56401
56402
56403
56404
56405
56406
56407
56408
56409
56410
56411
56412
56413
56414
56415
56416
56417
56418
56419
56420
56421
56422
56423
56424
56425
56426
56427
56428
56429
56430
56431
56432
56433
56434
56435
56436
56437
56438
56439
56440
56441
56442
56443
56444
56445
56446
56447
56448
56449
56450
56451
56452
56453
56454
56455
56456
56457
56458
56459
56460
56461
56462
56463
56464
56465
56466
56467
56468
56469
56470
56471
56472
56473
56474
56475
56476
56477
56478
56479
56480
56481
56482
56483
56484
56485
56486
56487
56488
56489
56490
56491
56492
56493
56494
56495
56496
56497
56498
56499
56500
56501
56502
56503
56504
56505
56506
56507
56508
56509
56510
56511
56512
56513
56514
56515
56516
56517
56518
56519
56520
56521
56522
56523
56524
56525
56526
56527
56528
56529
56530
56531
56532
56533
56534
56535
56536
56537
56538
56539
56540
56541
56542
56543
56544
56545
56546
56547
56548
56549
56550
56551
56552
56553
56554
56555
56556
56557
56558
56559
56560
56561
56562
56563
56564
56565
56566
56567
56568
56569
56570
56571
56572
56573
56574
56575
56576
56577
56578
56579
56580
56581
56582
56583
56584
56585
56586
56587
56588
56589
56590
56591
56592
56593
56594
56595
56596
56597
56598
56599
56600
56601
56602
56603
56604
56605
56606
56607
56608
56609
56610
56611
56612
56613
56614
56615
56616
56617
56618
56619
56620
56621
56622
56623
56624
56625
56626
56627
56628
56629
56630
56631
56632
56633
56634
56635
56636
56637
56638
56639
56640
56641
56642
56643
56644
56645
56646
56647
56648
56649
56650
56651
56652
56653
56654
56655
56656
56657
56658
56659
56660
56661
56662
56663
56664
56665
56666
56667
56668
56669
56670
56671
56672
56673
56674
56675
56676
56677
56678
56679
56680
56681
56682
56683
56684
56685
56686
56687
56688
56689
56690
56691
56692
56693
56694
56695
56696
56697
56698
56699
56700
56701
56702
56703
56704
56705
56706
56707
56708
56709
56710
56711
56712
56713
56714
56715
56716
56717
56718
56719
56720
56721
56722
56723
56724
56725
56726
56727
56728
56729
56730
56731
56732
56733
56734
56735
56736
56737
56738
56739
56740
56741
56742
56743
56744
56745
56746
56747
56748
56749
56750
56751
56752
56753
56754
56755
56756
56757
56758
56759
56760
56761
56762
56763
56764
56765
56766
56767
56768
56769
56770
56771
56772
56773
56774
56775
56776
56777
56778
56779
56780
56781
56782
56783
56784
56785
56786
56787
56788
56789
56790
56791
56792
56793
56794
56795
56796
56797
56798
56799
56800
56801
56802
56803
56804
56805
56806
56807
56808
56809
56810
56811
56812
56813
56814
56815
56816
56817
56818
56819
56820
56821
56822
56823
56824
56825
56826
56827
56828
56829
56830
56831
56832
56833
56834
56835
56836
56837
56838
56839
56840
56841
56842
56843
56844
56845
56846
56847
56848
56849
56850
56851
56852
56853
56854
56855
56856
56857
56858
56859
56860
56861
56862
56863
56864
56865
56866
56867
56868
56869
56870
56871
56872
56873
56874
56875
56876
56877
56878
56879
56880
56881
56882
56883
56884
56885
56886
56887
56888
56889
56890
56891
56892
56893
56894
56895
56896
56897
56898
56899
56900
56901
56902
56903
56904
56905
56906
56907
56908
56909
56910
56911
56912
56913
56914
56915
56916
56917
56918
56919
56920
56921
56922
56923
56924
56925
56926
56927
56928
56929
56930
56931
56932
56933
56934
56935
56936
56937
56938
56939
56940
56941
56942
56943
56944
56945
56946
56947
56948
56949
56950
56951
56952
56953
56954
56955
56956
56957
56958
56959
56960
56961
56962
56963
56964
56965
56966
56967
56968
56969
56970
56971
56972
56973
56974
56975
56976
56977
56978
56979
56980
56981
56982
56983
56984
56985
56986
56987
56988
56989
56990
56991
56992
56993
56994
56995
56996
56997
56998
56999
57000
57001
57002
57003
57004
57005
57006
57007
57008
57009
57010
57011
57012
57013
57014
57015
57016
57017
57018
57019
57020
57021
57022
57023
57024
57025
57026
57027
57028
57029
57030
57031
57032
57033
57034
57035
57036
57037
57038
57039
57040
57041
57042
57043
57044
57045
57046
57047
57048
57049
57050
57051
57052
57053
57054
57055
57056
57057
57058
57059
57060
57061
57062
57063
57064
57065
57066
57067
57068
57069
57070
57071
57072
57073
57074
57075
57076
57077
57078
57079
57080
57081
57082
57083
57084
57085
57086
57087
57088
57089
57090
57091
57092
57093
57094
57095
57096
57097
57098
57099
57100
57101
57102
57103
57104
57105
57106
57107
57108
57109
57110
57111
57112
57113
57114
57115
57116
57117
57118
57119
57120
57121
57122
57123
57124
57125
57126
57127
57128
57129
57130
57131
57132
57133
57134
57135
57136
57137
57138
57139
57140
57141
57142
57143
57144
57145
57146
57147
57148
57149
57150
57151
57152
57153
57154
57155
57156
57157
57158
57159
57160
57161
57162
57163
57164
57165
57166
57167
57168
57169
57170
57171
57172
57173
57174
57175
57176
57177
57178
57179
57180
57181
57182
57183
57184
57185
57186
57187
57188
57189
57190
57191
57192
57193
57194
57195
57196
57197
57198
57199
57200
57201
57202
57203
57204
57205
57206
57207
57208
57209
57210
57211
57212
57213
57214
57215
57216
57217
57218
57219
57220
57221
57222
57223
57224
57225
57226
57227
57228
57229
57230
57231
57232
57233
57234
57235
57236
57237
57238
57239
57240
57241
57242
57243
57244
57245
57246
57247
57248
57249
57250
57251
57252
57253
57254
57255
57256
57257
57258
57259
57260
57261
57262
57263
57264
57265
57266
57267
57268
57269
57270
57271
57272
57273
57274
57275
57276
57277
57278
57279
57280
57281
57282
57283
57284
57285
57286
57287
57288
57289
57290
57291
57292
57293
57294
57295
57296
57297
57298
57299
57300
57301
57302
57303
57304
57305
57306
57307
57308
57309
57310
57311
57312
57313
57314
57315
57316
57317
57318
57319
57320
57321
57322
57323
57324
57325
57326
57327
57328
57329
57330
57331
57332
57333
57334
57335
57336
57337
57338
57339
57340
57341
57342
57343
57344
57345
57346
57347
57348
57349
57350
57351
57352
57353
57354
57355
57356
57357
57358
57359
57360
57361
57362
57363
57364
57365
57366
57367
57368
57369
57370
57371
57372
57373
57374
57375
57376
57377
57378
57379
57380
57381
57382
57383
57384
57385
57386
57387
57388
57389
57390
57391
57392
57393
57394
57395
57396
57397
57398
57399
57400
57401
57402
57403
57404
57405
57406
57407
57408
57409
57410
57411
57412
57413
57414
57415
57416
57417
57418
57419
57420
57421
57422
57423
57424
57425
57426
57427
57428
57429
57430
57431
57432
57433
57434
57435
57436
57437
57438
57439
57440
57441
57442
57443
57444
57445
57446
57447
57448
57449
57450
57451
57452
57453
57454
57455
57456
57457
57458
57459
57460
57461
57462
57463
57464
57465
57466
57467
57468
57469
57470
57471
57472
57473
57474
57475
57476
57477
57478
57479
57480
57481
57482
57483
57484
57485
57486
57487
57488
57489
57490
57491
57492
57493
57494
57495
57496
57497
57498
57499
57500
57501
57502
57503
57504
57505
57506
57507
57508
57509
57510
57511
57512
57513
57514
57515
57516
57517
57518
57519
57520
57521
57522
57523
57524
57525
57526
57527
57528
57529
57530
57531
57532
57533
57534
57535
57536
57537
57538
57539
57540
57541
57542
57543
57544
57545
57546
57547
57548
57549
57550
57551
57552
57553
57554
57555
57556
57557
57558
57559
57560
57561
57562
57563
57564
57565
57566
57567
57568
57569
57570
57571
57572
57573
57574
57575
57576
57577
57578
57579
57580
57581
57582
57583
57584
57585
57586
57587
57588
57589
57590
57591
57592
57593
57594
57595
57596
57597
57598
57599
57600
57601
57602
57603
57604
57605
57606
57607
57608
57609
57610
57611
57612
57613
57614
57615
57616
57617
57618
57619
57620
57621
57622
57623
57624
57625
57626
57627
57628
57629
57630
57631
57632
57633
57634
57635
57636
57637
57638
57639
57640
57641
57642
57643
57644
57645
57646
57647
57648
57649
57650
57651
57652
57653
57654
57655
57656
57657
57658
57659
57660
57661
57662
57663
57664
57665
57666
57667
57668
57669
57670
57671
57672
57673
57674
57675
57676
57677
57678
57679
57680
57681
57682
57683
57684
57685
57686
57687
57688
57689
57690
57691
57692
57693
57694
57695
57696
57697
57698
57699
57700
57701
57702
57703
57704
57705
57706
57707
57708
57709
57710
57711
57712
57713
57714
57715
57716
57717
57718
57719
57720
57721
57722
57723
57724
57725
57726
57727
57728
57729
57730
57731
57732
57733
57734
57735
57736
57737
57738
57739
57740
57741
57742
57743
57744
57745
57746
57747
57748
57749
57750
57751
57752
57753
57754
57755
57756
57757
57758
57759
57760
57761
57762
57763
57764
57765
57766
57767
57768
57769
57770
57771
57772
57773
57774
57775
57776
57777
57778
57779
57780
57781
57782
57783
57784
57785
57786
57787
57788
57789
57790
57791
57792
57793
57794
57795
57796
57797
57798
57799
57800
57801
57802
57803
57804
57805
57806
57807
57808
57809
57810
57811
57812
57813
57814
57815
57816
57817
57818
57819
57820
57821
57822
57823
57824
57825
57826
57827
57828
57829
57830
57831
57832
57833
57834
57835
57836
57837
57838
57839
57840
57841
57842
57843
57844
57845
57846
57847
57848
57849
57850
57851
57852
57853
57854
57855
57856
57857
57858
57859
57860
57861
57862
57863
57864
57865
57866
57867
57868
57869
57870
57871
57872
57873
57874
57875
57876
57877
57878
57879
57880
57881
57882
57883
57884
57885
57886
57887
57888
57889
57890
57891
57892
57893
57894
57895
57896
57897
57898
57899
57900
57901
57902
57903
57904
57905
57906
57907
57908
57909
57910
57911
57912
57913
57914
57915
57916
57917
57918
57919
57920
57921
57922
57923
57924
57925
57926
57927
57928
57929
57930
57931
57932
57933
57934
57935
57936
57937
57938
57939
57940
57941
57942
57943
57944
57945
57946
57947
57948
57949
57950
57951
57952
57953
57954
57955
57956
57957
57958
57959
57960
57961
57962
57963
57964
57965
57966
57967
57968
57969
57970
57971
57972
57973
57974
57975
57976
57977
57978
57979
57980
57981
57982
57983
57984
57985
57986
57987
57988
57989
57990
57991
57992
57993
57994
57995
57996
57997
57998
57999
58000
58001
58002
58003
58004
58005
58006
58007
58008
58009
58010
58011
58012
58013
58014
58015
58016
58017
58018
58019
58020
58021
58022
58023
58024
58025
58026
58027
58028
58029
58030
58031
58032
58033
58034
58035
58036
58037
58038
58039
58040
58041
58042
58043
58044
58045
58046
58047
58048
58049
58050
58051
58052
58053
58054
58055
58056
58057
58058
58059
58060
58061
58062
58063
58064
58065
58066
58067
58068
58069
58070
58071
58072
58073
58074
58075
58076
58077
58078
58079
58080
58081
58082
58083
58084
58085
58086
58087
58088
58089
58090
58091
58092
58093
58094
58095
58096
58097
58098
58099
58100
58101
58102
58103
58104
58105
58106
58107
58108
58109
58110
58111
58112
58113
58114
58115
58116
58117
58118
58119
58120
58121
58122
58123
58124
58125
58126
58127
58128
58129
58130
58131
58132
58133
58134
58135
58136
58137
58138
58139
58140
58141
58142
58143
58144
58145
58146
58147
58148
58149
58150
58151
58152
58153
58154
58155
58156
58157
58158
58159
58160
58161
58162
58163
58164
58165
58166
58167
58168
58169
58170
58171
58172
58173
58174
58175
58176
58177
58178
58179
58180
58181
58182
58183
58184
58185
58186
58187
58188
58189
58190
58191
58192
58193
58194
58195
58196
58197
58198
58199
58200
58201
58202
58203
58204
58205
58206
58207
58208
58209
58210
58211
58212
58213
58214
58215
58216
58217
58218
58219
58220
58221
58222
58223
58224
58225
58226
58227
58228
58229
58230
58231
58232
58233
58234
58235
58236
58237
58238
58239
58240
58241
58242
58243
58244
58245
58246
58247
58248
58249
58250
58251
58252
58253
58254
58255
58256
58257
58258
58259
58260
58261
58262
58263
58264
58265
58266
58267
58268
58269
58270
58271
58272
58273
58274
58275
58276
58277
58278
58279
58280
58281
58282
58283
58284
58285
58286
58287
58288
58289
58290
58291
58292
58293
58294
58295
58296
58297
58298
58299
58300
58301
58302
58303
58304
58305
58306
58307
58308
58309
58310
58311
58312
58313
58314
58315
58316
58317
58318
58319
58320
58321
58322
58323
58324
58325
58326
58327
58328
58329
58330
58331
58332
58333
58334
58335
58336
58337
58338
58339
58340
58341
58342
58343
58344
58345
58346
58347
58348
58349
58350
58351
58352
58353
58354
58355
58356
58357
58358
58359
58360
58361
58362
58363
58364
58365
58366
58367
58368
58369
58370
58371
58372
58373
58374
58375
58376
58377
58378
58379
58380
58381
58382
58383
58384
58385
58386
58387
58388
58389
58390
58391
58392
58393
58394
58395
58396
58397
58398
58399
58400
58401
58402
58403
58404
58405
58406
58407
58408
58409
58410
58411
58412
58413
58414
58415
58416
58417
58418
58419
58420
58421
58422
58423
58424
58425
58426
58427
58428
58429
58430
58431
58432
58433
58434
58435
58436
58437
58438
58439
58440
58441
58442
58443
58444
58445
58446
58447
58448
58449
58450
58451
58452
58453
58454
58455
58456
58457
58458
58459
58460
58461
58462
58463
58464
58465
58466
58467
58468
58469
58470
58471
58472
58473
58474
58475
58476
58477
58478
58479
58480
58481
58482
58483
58484
58485
58486
58487
58488
58489
58490
58491
58492
58493
58494
58495
58496
58497
58498
58499
58500
58501
58502
58503
58504
58505
58506
58507
58508
58509
58510
58511
58512
58513
58514
58515
58516
58517
58518
58519
58520
58521
58522
58523
58524
58525
58526
58527
58528
58529
58530
58531
58532
58533
58534
58535
58536
58537
58538
58539
58540
58541
58542
58543
58544
58545
58546
58547
58548
58549
58550
58551
58552
58553
58554
58555
58556
58557
58558
58559
58560
58561
58562
58563
58564
58565
58566
58567
58568
58569
58570
58571
58572
58573
58574
58575
58576
58577
58578
58579
58580
58581
58582
58583
58584
58585
58586
58587
58588
58589
58590
58591
58592
58593
58594
58595
58596
58597
58598
58599
58600
58601
58602
58603
58604
58605
58606
58607
58608
58609
58610
58611
58612
58613
58614
58615
58616
58617
58618
58619
58620
58621
58622
58623
58624
58625
58626
58627
58628
58629
58630
58631
58632
58633
58634
58635
58636
58637
58638
58639
58640
58641
58642
58643
58644
58645
58646
58647
58648
58649
58650
58651
58652
58653
58654
58655
58656
58657
58658
58659
58660
58661
58662
58663
58664
58665
58666
58667
58668
58669
58670
58671
58672
58673
58674
58675
58676
58677
58678
58679
58680
58681
58682
58683
58684
58685
58686
58687
58688
58689
58690
58691
58692
58693
58694
58695
58696
58697
58698
58699
58700
58701
58702
58703
58704
58705
58706
58707
58708
58709
58710
58711
58712
58713
58714
58715
58716
58717
58718
58719
58720
58721
58722
58723
58724
58725
58726
58727
58728
58729
58730
58731
58732
58733
58734
58735
58736
58737
58738
58739
58740
58741
58742
58743
58744
58745
58746
58747
58748
58749
58750
58751
58752
58753
58754
58755
58756
58757
58758
58759
58760
58761
58762
58763
58764
58765
58766
58767
58768
58769
58770
58771
58772
58773
58774
58775
58776
58777
58778
58779
58780
58781
58782
58783
58784
58785
58786
58787
58788
58789
58790
58791
58792
58793
58794
58795
58796
58797
58798
58799
58800
58801
58802
58803
58804
58805
58806
58807
58808
58809
58810
58811
58812
58813
58814
58815
58816
58817
58818
58819
58820
58821
58822
58823
58824
58825
58826
58827
58828
58829
58830
58831
58832
58833
58834
58835
58836
58837
58838
58839
58840
58841
58842
58843
58844
58845
58846
58847
58848
58849
58850
58851
58852
58853
58854
58855
58856
58857
58858
58859
58860
58861
58862
58863
58864
58865
58866
58867
58868
58869
58870
58871
58872
58873
58874
58875
58876
58877
58878
58879
58880
58881
58882
58883
58884
58885
58886
58887
58888
58889
58890
58891
58892
58893
58894
58895
58896
58897
58898
58899
58900
58901
58902
58903
58904
58905
58906
58907
58908
58909
58910
58911
58912
58913
58914
58915
58916
58917
58918
58919
58920
58921
58922
58923
58924
58925
58926
58927
58928
58929
58930
58931
58932
58933
58934
58935
58936
58937
58938
58939
58940
58941
58942
58943
58944
58945
58946
58947
58948
58949
58950
58951
58952
58953
58954
58955
58956
58957
58958
58959
58960
58961
58962
58963
58964
58965
58966
58967
58968
58969
58970
58971
58972
58973
58974
58975
58976
58977
58978
58979
58980
58981
58982
58983
58984
58985
58986
58987
58988
58989
58990
58991
58992
58993
58994
58995
58996
58997
58998
58999
59000
59001
59002
59003
59004
59005
59006
59007
59008
59009
59010
59011
59012
59013
59014
59015
59016
59017
59018
59019
59020
59021
59022
59023
59024
59025
59026
59027
59028
59029
59030
59031
59032
59033
59034
59035
59036
59037
59038
59039
59040
59041
59042
59043
59044
59045
59046
59047
59048
59049
59050
59051
59052
59053
59054
59055
59056
59057
59058
59059
59060
59061
59062
59063
59064
59065
59066
59067
59068
59069
59070
59071
59072
59073
59074
59075
59076
59077
59078
59079
59080
59081
59082
59083
59084
59085
59086
59087
59088
59089
59090
59091
59092
59093
59094
59095
59096
59097
59098
59099
59100
59101
59102
59103
59104
59105
59106
59107
59108
59109
59110
59111
59112
59113
59114
59115
59116
59117
59118
59119
59120
59121
59122
59123
59124
59125
59126
59127
59128
59129
59130
59131
59132
59133
59134
59135
59136
59137
59138
59139
59140
59141
59142
59143
59144
59145
59146
59147
59148
59149
59150
59151
59152
59153
59154
59155
59156
59157
59158
59159
59160
59161
59162
59163
59164
59165
59166
59167
59168
59169
59170
59171
59172
59173
59174
59175
59176
59177
59178
59179
59180
59181
59182
59183
59184
59185
59186
59187
59188
59189
59190
59191
59192
59193
59194
59195
59196
59197
59198
59199
59200
59201
59202
59203
59204
59205
59206
59207
59208
59209
59210
59211
59212
59213
59214
59215
59216
59217
59218
59219
59220
59221
59222
59223
59224
59225
59226
59227
59228
59229
59230
59231
59232
59233
59234
59235
59236
59237
59238
59239
59240
59241
59242
59243
59244
59245
59246
59247
59248
59249
59250
59251
59252
59253
59254
59255
59256
59257
59258
59259
59260
59261
59262
59263
59264
59265
59266
59267
59268
59269
59270
59271
59272
59273
59274
59275
59276
59277
59278
59279
59280
59281
59282
59283
59284
59285
59286
59287
59288
59289
59290
59291
59292
59293
59294
59295
59296
59297
59298
59299
59300
59301
59302
59303
59304
59305
59306
59307
59308
59309
59310
59311
59312
59313
59314
59315
59316
59317
59318
59319
59320
59321
59322
59323
59324
59325
59326
59327
59328
59329
59330
59331
59332
59333
59334
59335
59336
59337
59338
59339
59340
59341
59342
59343
59344
59345
59346
59347
59348
59349
59350
59351
59352
59353
59354
59355
59356
59357
59358
59359
59360
59361
59362
59363
59364
59365
59366
59367
59368
59369
59370
59371
59372
59373
59374
59375
59376
59377
59378
59379
59380
59381
59382
59383
59384
59385
59386
59387
59388
59389
59390
59391
59392
59393
59394
59395
59396
59397
59398
59399
59400
59401
59402
59403
59404
59405
59406
59407
59408
59409
59410
59411
59412
59413
59414
59415
59416
59417
59418
59419
59420
59421
59422
59423
59424
59425
59426
59427
59428
59429
59430
59431
59432
59433
59434
59435
59436
59437
59438
59439
59440
59441
59442
59443
59444
59445
59446
59447
59448
59449
59450
59451
59452
59453
59454
59455
59456
59457
59458
59459
59460
59461
59462
59463
59464
59465
59466
59467
59468
59469
59470
59471
59472
59473
59474
59475
59476
59477
59478
59479
59480
59481
59482
59483
59484
59485
59486
59487
59488
59489
59490
59491
59492
59493
59494
59495
59496
59497
59498
59499
59500
59501
59502
59503
59504
59505
59506
59507
59508
59509
59510
59511
59512
59513
59514
59515
59516
59517
59518
59519
59520
59521
59522
59523
59524
59525
59526
59527
59528
59529
59530
59531
59532
59533
59534
59535
59536
59537
59538
59539
59540
59541
59542
59543
59544
59545
59546
59547
59548
59549
59550
59551
59552
59553
59554
59555
59556
59557
59558
59559
59560
59561
59562
59563
59564
59565
59566
59567
59568
59569
59570
59571
59572
59573
59574
59575
59576
59577
59578
59579
59580
59581
59582
59583
59584
59585
59586
59587
59588
59589
59590
59591
59592
59593
59594
59595
59596
59597
59598
59599
59600
59601
59602
59603
59604
59605
59606
59607
59608
59609
59610
59611
59612
59613
59614
59615
59616
59617
59618
59619
59620
59621
59622
59623
59624
59625
59626
59627
59628
59629
59630
59631
59632
59633
59634
59635
59636
59637
59638
59639
59640
59641
59642
59643
59644
59645
59646
59647
59648
59649
59650
59651
59652
59653
59654
59655
59656
59657
59658
59659
59660
59661
59662
59663
59664
59665
59666
59667
59668
59669
59670
59671
59672
59673
59674
59675
59676
59677
59678
59679
59680
59681
59682
59683
59684
59685
59686
59687
59688
59689
59690
59691
59692
59693
59694
59695
59696
59697
59698
59699
59700
59701
59702
59703
59704
59705
59706
59707
59708
59709
59710
59711
59712
59713
59714
59715
59716
59717
59718
59719
59720
59721
59722
59723
59724
59725
59726
59727
59728
59729
59730
59731
59732
59733
59734
59735
59736
59737
59738
59739
59740
59741
59742
59743
59744
59745
59746
59747
59748
59749
59750
59751
59752
59753
59754
59755
59756
59757
59758
59759
59760
59761
59762
59763
59764
59765
59766
59767
59768
59769
59770
59771
59772
59773
59774
59775
59776
59777
59778
59779
59780
59781
59782
59783
59784
59785
59786
59787
59788
59789
59790
59791
59792
59793
59794
59795
59796
59797
59798
59799
59800
59801
59802
59803
59804
59805
59806
59807
59808
59809
59810
59811
59812
59813
59814
59815
59816
59817
59818
59819
59820
59821
59822
59823
59824
59825
59826
59827
59828
59829
59830
59831
59832
59833
59834
59835
59836
59837
59838
59839
59840
59841
59842
59843
59844
59845
59846
59847
59848
59849
59850
59851
59852
59853
59854
59855
59856
59857
59858
59859
59860
59861
59862
59863
59864
59865
59866
59867
59868
59869
59870
59871
59872
59873
59874
59875
59876
59877
59878
59879
59880
59881
59882
59883
59884
59885
59886
59887
59888
59889
59890
59891
59892
59893
59894
59895
59896
59897
59898
59899
59900
59901
59902
59903
59904
59905
59906
59907
59908
59909
59910
59911
59912
59913
59914
59915
59916
59917
59918
59919
59920
59921
59922
59923
59924
59925
59926
59927
59928
59929
59930
59931
59932
59933
59934
59935
59936
59937
59938
59939
59940
59941
59942
59943
59944
59945
59946
59947
59948
59949
59950
59951
59952
59953
59954
59955
59956
59957
59958
59959
59960
59961
59962
59963
59964
59965
59966
59967
59968
59969
59970
59971
59972
59973
59974
59975
59976
59977
59978
59979
59980
59981
59982
59983
59984
59985
59986
59987
59988
59989
59990
59991
59992
59993
59994
59995
59996
59997
59998
59999
60000
60001
60002
60003
60004
60005
60006
60007
60008
60009
60010
60011
60012
60013
60014
60015
60016
60017
60018
60019
60020
60021
60022
60023
60024
60025
60026
60027
60028
60029
60030
60031
60032
60033
60034
60035
60036
60037
60038
60039
60040
60041
60042
60043
60044
60045
60046
60047
60048
60049
60050
60051
60052
60053
60054
60055
60056
60057
60058
60059
60060
60061
60062
60063
60064
60065
60066
60067
60068
60069
60070
60071
60072
60073
60074
60075
60076
60077
60078
60079
60080
60081
60082
60083
60084
60085
60086
60087
60088
60089
60090
60091
60092
60093
60094
60095
60096
60097
60098
60099
60100
60101
60102
60103
60104
60105
60106
60107
60108
60109
60110
60111
60112
60113
60114
60115
60116
60117
60118
60119
60120
60121
60122
60123
60124
60125
60126
60127
60128
60129
60130
60131
60132
60133
60134
60135
60136
60137
60138
60139
60140
60141
60142
60143
60144
60145
60146
60147
60148
60149
60150
60151
60152
60153
60154
60155
60156
60157
60158
60159
60160
60161
60162
60163
60164
60165
60166
60167
60168
60169
60170
60171
60172
60173
60174
60175
60176
60177
60178
60179
60180
60181
60182
60183
60184
60185
60186
60187
60188
60189
60190
60191
60192
60193
60194
60195
60196
60197
60198
60199
60200
60201
60202
60203
60204
60205
60206
60207
60208
60209
60210
60211
60212
60213
60214
60215
60216
60217
60218
60219
60220
60221
60222
60223
60224
60225
60226
60227
60228
60229
60230
60231
60232
60233
60234
60235
60236
60237
60238
60239
60240
60241
60242
60243
60244
60245
60246
60247
60248
60249
60250
60251
60252
60253
60254
60255
60256
60257
60258
60259
60260
60261
60262
60263
60264
60265
60266
60267
60268
60269
60270
60271
60272
60273
60274
60275
60276
60277
60278
60279
60280
60281
60282
60283
60284
60285
60286
60287
60288
60289
60290
60291
60292
60293
60294
60295
60296
60297
60298
60299
60300
60301
60302
60303
60304
60305
60306
60307
60308
60309
60310
60311
60312
60313
60314
60315
60316
60317
60318
60319
60320
60321
60322
60323
60324
60325
60326
60327
60328
60329
60330
60331
60332
60333
60334
60335
60336
60337
60338
60339
60340
60341
60342
60343
60344
60345
60346
60347
60348
60349
60350
60351
60352
60353
60354
60355
60356
60357
60358
60359
60360
60361
60362
60363
60364
60365
60366
60367
60368
60369
60370
60371
60372
60373
60374
60375
60376
60377
60378
60379
60380
60381
60382
60383
60384
60385
60386
60387
60388
60389
60390
60391
60392
60393
60394
60395
60396
60397
60398
60399
60400
60401
60402
60403
60404
60405
60406
60407
60408
60409
60410
60411
60412
60413
60414
60415
60416
60417
60418
60419
60420
60421
60422
60423
60424
60425
60426
60427
60428
60429
60430
60431
60432
60433
60434
60435
60436
60437
60438
60439
60440
60441
60442
60443
60444
60445
60446
60447
60448
60449
60450
60451
60452
60453
60454
60455
60456
60457
60458
60459
60460
60461
60462
60463
60464
60465
60466
60467
60468
60469
60470
60471
60472
60473
60474
60475
60476
60477
60478
60479
60480
60481
60482
60483
60484
60485
60486
60487
60488
60489
60490
60491
60492
60493
60494
60495
60496
60497
60498
60499
60500
60501
60502
60503
60504
60505
60506
60507
60508
60509
60510
60511
60512
60513
60514
60515
60516
60517
60518
60519
60520
60521
60522
60523
60524
60525
60526
60527
60528
60529
60530
60531
60532
60533
60534
60535
60536
60537
60538
60539
60540
60541
60542
60543
60544
60545
60546
60547
60548
60549
60550
60551
60552
60553
60554
60555
60556
60557
60558
60559
60560
60561
60562
60563
60564
60565
60566
60567
60568
60569
60570
60571
60572
60573
60574
60575
60576
60577
60578
60579
60580
60581
60582
60583
60584
60585
60586
60587
60588
60589
60590
60591
60592
60593
60594
60595
60596
60597
60598
60599
60600
60601
60602
60603
60604
60605
60606
60607
60608
60609
60610
60611
60612
60613
60614
60615
60616
60617
60618
60619
60620
60621
60622
60623
60624
60625
60626
60627
60628
60629
60630
60631
60632
60633
60634
60635
60636
60637
60638
60639
60640
60641
60642
60643
60644
60645
60646
60647
60648
60649
60650
60651
60652
60653
60654
60655
60656
60657
60658
60659
60660
60661
60662
60663
60664
60665
60666
60667
60668
60669
60670
60671
60672
60673
60674
60675
60676
60677
60678
60679
60680
60681
60682
60683
60684
60685
60686
60687
60688
60689
60690
60691
60692
60693
60694
60695
60696
60697
60698
60699
60700
60701
60702
60703
60704
60705
60706
60707
60708
60709
60710
60711
60712
60713
60714
60715
60716
60717
60718
60719
60720
60721
60722
60723
60724
60725
60726
60727
60728
60729
60730
60731
60732
60733
60734
60735
60736
60737
60738
60739
60740
60741
60742
60743
60744
60745
60746
60747
60748
60749
60750
60751
60752
60753
60754
60755
60756
60757
60758
60759
60760
60761
60762
60763
60764
60765
60766
60767
60768
60769
60770
60771
60772
60773
60774
60775
60776
60777
60778
60779
60780
60781
60782
60783
60784
60785
60786
60787
60788
60789
60790
60791
60792
60793
60794
60795
60796
60797
60798
60799
60800
60801
60802
60803
60804
60805
60806
60807
60808
60809
60810
60811
60812
60813
60814
60815
60816
60817
60818
60819
60820
60821
60822
60823
60824
60825
60826
60827
60828
60829
60830
60831
60832
60833
60834
60835
60836
60837
60838
60839
60840
60841
60842
60843
60844
60845
60846
60847
60848
60849
60850
60851
60852
60853
60854
60855
60856
60857
60858
60859
60860
60861
60862
60863
60864
60865
60866
60867
60868
60869
60870
60871
60872
60873
60874
60875
60876
60877
60878
60879
60880
60881
60882
60883
60884
60885
60886
60887
60888
60889
60890
60891
60892
60893
60894
60895
60896
60897
60898
60899
60900
60901
60902
60903
60904
60905
60906
60907
60908
60909
60910
60911
60912
60913
60914
60915
60916
60917
60918
60919
60920
60921
60922
60923
60924
60925
60926
60927
60928
60929
60930
60931
60932
60933
60934
60935
60936
60937
60938
60939
60940
60941
60942
60943
60944
60945
60946
60947
60948
60949
60950
60951
60952
60953
60954
60955
60956
60957
60958
60959
60960
60961
60962
60963
60964
60965
60966
60967
60968
60969
60970
60971
60972
60973
60974
60975
60976
60977
60978
60979
60980
60981
60982
60983
60984
60985
60986
60987
60988
60989
60990
60991
60992
60993
60994
60995
60996
60997
60998
60999
61000
61001
61002
61003
61004
61005
61006
61007
61008
61009
61010
61011
61012
61013
61014
61015
61016
61017
61018
61019
61020
61021
61022
61023
61024
61025
61026
61027
61028
61029
61030
61031
61032
61033
61034
61035
61036
61037
61038
61039
61040
61041
61042
61043
61044
61045
61046
61047
61048
61049
61050
61051
61052
61053
61054
61055
61056
61057
61058
61059
61060
61061
61062
61063
61064
61065
61066
61067
61068
61069
61070
61071
61072
61073
61074
61075
61076
61077
61078
61079
61080
61081
61082
61083
61084
61085
61086
61087
61088
61089
61090
61091
61092
61093
61094
61095
61096
61097
61098
61099
61100
61101
61102
61103
61104
61105
61106
61107
61108
61109
61110
61111
61112
61113
61114
61115
61116
61117
61118
61119
61120
61121
61122
61123
61124
61125
61126
61127
61128
61129
61130
61131
61132
61133
61134
61135
61136
61137
61138
61139
61140
61141
61142
61143
61144
61145
61146
61147
61148
61149
61150
61151
61152
61153
61154
61155
61156
61157
61158
61159
61160
61161
61162
61163
61164
61165
61166
61167
61168
61169
61170
61171
61172
61173
61174
61175
61176
61177
61178
61179
61180
61181
61182
61183
61184
61185
61186
61187
61188
61189
61190
61191
61192
61193
61194
61195
61196
61197
61198
61199
61200
61201
61202
61203
61204
61205
61206
61207
61208
61209
61210
61211
61212
61213
61214
61215
61216
61217
61218
61219
61220
61221
61222
61223
61224
61225
61226
61227
61228
61229
61230
61231
61232
61233
61234
61235
61236
61237
61238
61239
61240
61241
61242
61243
61244
61245
61246
61247
61248
61249
61250
61251
61252
61253
61254
61255
61256
61257
61258
61259
61260
61261
61262
61263
61264
61265
61266
61267
61268
61269
61270
61271
61272
61273
61274
61275
61276
61277
61278
61279
61280
61281
61282
61283
61284
61285
61286
61287
61288
61289
61290
61291
61292
61293
61294
61295
61296
61297
61298
61299
61300
61301
61302
61303
61304
61305
61306
61307
61308
61309
61310
61311
61312
61313
61314
61315
61316
61317
61318
61319
61320
61321
61322
61323
61324
61325
61326
61327
61328
61329
61330
61331
61332
61333
61334
61335
61336
61337
61338
61339
61340
61341
61342
61343
61344
61345
61346
61347
61348
61349
61350
61351
61352
61353
61354
61355
61356
61357
61358
61359
61360
61361
61362
61363
61364
61365
61366
61367
61368
61369
61370
61371
61372
61373
61374
61375
61376
61377
61378
61379
61380
61381
61382
61383
61384
61385
61386
61387
61388
61389
61390
61391
61392
61393
61394
61395
61396
61397
61398
61399
61400
61401
61402
61403
61404
61405
61406
61407
61408
61409
61410
61411
61412
61413
61414
61415
61416
61417
61418
61419
61420
61421
61422
61423
61424
61425
61426
61427
61428
61429
61430
61431
61432
61433
61434
61435
61436
61437
61438
61439
61440
61441
61442
61443
61444
61445
61446
61447
61448
61449
61450
61451
61452
61453
61454
61455
61456
61457
61458
61459
61460
61461
61462
61463
61464
61465
61466
61467
61468
61469
61470
61471
61472
61473
61474
61475
61476
61477
61478
61479
61480
61481
61482
61483
61484
61485
61486
61487
61488
61489
61490
61491
61492
61493
61494
61495
61496
61497
61498
61499
61500
61501
61502
61503
61504
61505
61506
61507
61508
61509
61510
61511
61512
61513
61514
61515
61516
61517
61518
61519
61520
61521
61522
61523
61524
61525
61526
61527
61528
61529
61530
61531
61532
61533
61534
61535
61536
61537
61538
61539
61540
61541
61542
61543
61544
61545
61546
61547
61548
61549
61550
61551
61552
61553
61554
61555
61556
61557
61558
61559
61560
61561
61562
61563
61564
61565
61566
61567
61568
61569
61570
61571
61572
61573
61574
61575
61576
61577
61578
61579
61580
61581
61582
61583
61584
61585
61586
61587
61588
61589
61590
61591
61592
61593
61594
61595
61596
61597
61598
61599
61600
61601
61602
61603
61604
61605
61606
61607
61608
61609
61610
61611
61612
61613
61614
61615
61616
61617
61618
61619
61620
61621
61622
61623
61624
61625
61626
61627
61628
61629
61630
61631
61632
61633
61634
61635
61636
61637
61638
61639
61640
61641
61642
61643
61644
61645
61646
61647
61648
61649
61650
61651
61652
61653
61654
61655
61656
61657
61658
61659
61660
61661
61662
61663
61664
61665
61666
61667
61668
61669
61670
61671
61672
61673
61674
61675
61676
61677
61678
61679
61680
61681
61682
61683
61684
61685
61686
61687
61688
61689
61690
61691
61692
61693
61694
61695
61696
61697
61698
61699
61700
61701
61702
61703
61704
61705
61706
61707
61708
61709
61710
61711
61712
61713
61714
61715
61716
61717
61718
61719
61720
61721
61722
61723
61724
61725
61726
61727
61728
61729
61730
61731
61732
61733
61734
61735
61736
61737
61738
61739
61740
61741
61742
61743
61744
61745
61746
61747
61748
61749
61750
61751
61752
61753
61754
61755
61756
61757
61758
61759
61760
61761
61762
61763
61764
61765
61766
61767
61768
61769
61770
61771
61772
61773
61774
61775
61776
61777
61778
61779
61780
61781
61782
61783
61784
61785
61786
61787
61788
61789
61790
61791
61792
61793
61794
61795
61796
61797
61798
61799
61800
61801
61802
61803
61804
61805
61806
61807
61808
61809
61810
61811
61812
61813
61814
61815
61816
61817
61818
61819
61820
61821
61822
61823
61824
61825
61826
61827
61828
61829
61830
61831
61832
61833
61834
61835
61836
61837
61838
61839
61840
61841
61842
61843
61844
61845
61846
61847
61848
61849
61850
61851
61852
61853
61854
61855
61856
61857
61858
61859
61860
61861
61862
61863
61864
61865
61866
61867
61868
61869
61870
61871
61872
61873
61874
61875
61876
61877
61878
61879
61880
61881
61882
61883
61884
61885
61886
61887
61888
61889
61890
61891
61892
61893
61894
61895
61896
61897
61898
61899
61900
61901
61902
61903
61904
61905
61906
61907
61908
61909
61910
61911
61912
61913
61914
61915
61916
61917
61918
61919
61920
61921
61922
61923
61924
61925
61926
61927
61928
61929
61930
61931
61932
61933
61934
61935
61936
61937
61938
61939
61940
61941
61942
61943
61944
61945
61946
61947
61948
61949
61950
61951
61952
61953
61954
61955
61956
61957
61958
61959
61960
61961
61962
61963
61964
61965
61966
61967
61968
61969
61970
61971
61972
61973
61974
61975
61976
61977
61978
61979
61980
61981
61982
61983
61984
61985
61986
61987
61988
61989
61990
61991
61992
61993
61994
61995
61996
61997
61998
61999
62000
62001
62002
62003
62004
62005
62006
62007
62008
62009
62010
62011
62012
62013
62014
62015
62016
62017
62018
62019
62020
62021
62022
62023
62024
62025
62026
62027
62028
62029
62030
62031
62032
62033
62034
62035
62036
62037
62038
62039
62040
62041
62042
62043
62044
62045
62046
62047
62048
62049
62050
62051
62052
62053
62054
62055
62056
62057
62058
62059
62060
62061
62062
62063
62064
62065
62066
62067
62068
62069
62070
62071
62072
62073
62074
62075
62076
62077
62078
62079
62080
62081
62082
62083
62084
62085
62086
62087
62088
62089
62090
62091
62092
62093
62094
62095
62096
62097
62098
62099
62100
62101
62102
62103
62104
62105
62106
62107
62108
62109
62110
62111
62112
62113
62114
62115
62116
62117
62118
62119
62120
62121
62122
62123
62124
62125
62126
62127
62128
62129
62130
62131
62132
62133
62134
62135
62136
62137
62138
62139
62140
62141
62142
62143
62144
62145
62146
62147
62148
62149
62150
62151
62152
62153
62154
62155
62156
62157
62158
62159
62160
62161
62162
62163
62164
62165
62166
62167
62168
62169
62170
62171
62172
62173
62174
62175
62176
62177
62178
62179
62180
62181
62182
62183
62184
62185
62186
62187
62188
62189
62190
62191
62192
62193
62194
62195
62196
62197
62198
62199
62200
62201
62202
62203
62204
62205
62206
62207
62208
62209
62210
62211
62212
62213
62214
62215
62216
62217
62218
62219
62220
62221
62222
62223
62224
62225
62226
62227
62228
62229
62230
62231
62232
62233
62234
62235
62236
62237
62238
62239
62240
62241
62242
62243
62244
62245
62246
62247
62248
62249
62250
62251
62252
62253
62254
62255
62256
62257
62258
62259
62260
62261
62262
62263
62264
62265
62266
62267
62268
62269
62270
62271
62272
62273
62274
62275
62276
62277
62278
62279
62280
62281
62282
62283
62284
62285
62286
62287
62288
62289
62290
62291
62292
62293
62294
62295
62296
62297
62298
62299
62300
62301
62302
62303
62304
62305
62306
62307
62308
62309
62310
62311
62312
62313
62314
62315
62316
62317
62318
62319
62320
62321
62322
62323
62324
62325
62326
62327
62328
62329
62330
62331
62332
62333
62334
62335
62336
62337
62338
62339
62340
62341
62342
62343
62344
62345
62346
62347
62348
62349
62350
62351
62352
62353
62354
62355
62356
62357
62358
62359
62360
62361
62362
62363
62364
62365
62366
62367
62368
62369
62370
62371
62372
62373
62374
62375
62376
62377
62378
62379
62380
62381
62382
62383
62384
62385
62386
62387
62388
62389
62390
62391
62392
62393
62394
62395
62396
62397
62398
62399
62400
62401
62402
62403
62404
62405
62406
62407
62408
62409
62410
62411
62412
62413
62414
62415
62416
62417
62418
62419
62420
62421
62422
62423
62424
62425
62426
62427
62428
62429
62430
62431
62432
62433
62434
62435
62436
62437
62438
62439
62440
62441
62442
62443
62444
62445
62446
62447
62448
62449
62450
62451
62452
62453
62454
62455
62456
62457
62458
62459
62460
62461
62462
62463
62464
62465
62466
62467
62468
62469
62470
62471
62472
62473
62474
62475
62476
62477
62478
62479
62480
62481
62482
62483
62484
62485
62486
62487
62488
62489
62490
62491
62492
62493
62494
62495
62496
62497
62498
62499
62500
62501
62502
62503
62504
62505
62506
62507
62508
62509
62510
62511
62512
62513
62514
62515
62516
62517
62518
62519
62520
62521
62522
62523
62524
62525
62526
62527
62528
62529
62530
62531
62532
62533
62534
62535
62536
62537
62538
62539
62540
62541
62542
62543
62544
62545
62546
62547
62548
62549
62550
62551
62552
62553
62554
62555
62556
62557
62558
62559
62560
62561
62562
62563
62564
62565
62566
62567
62568
62569
62570
62571
62572
62573
62574
62575
62576
62577
62578
62579
62580
62581
62582
62583
62584
62585
62586
62587
62588
62589
62590
62591
62592
62593
62594
62595
62596
62597
62598
62599
62600
62601
62602
62603
62604
62605
62606
62607
62608
62609
62610
62611
62612
62613
62614
62615
62616
62617
62618
62619
62620
62621
62622
62623
62624
62625
62626
62627
62628
62629
62630
62631
62632
62633
62634
62635
62636
62637
62638
62639
62640
62641
62642
62643
62644
62645
62646
62647
62648
62649
62650
62651
62652
62653
62654
62655
62656
62657
62658
62659
62660
62661
62662
62663
62664
62665
62666
62667
62668
62669
62670
62671
62672
62673
62674
62675
62676
62677
62678
62679
62680
62681
62682
62683
62684
62685
62686
62687
62688
62689
62690
62691
62692
62693
62694
62695
62696
62697
62698
62699
62700
62701
62702
62703
62704
62705
62706
62707
62708
62709
62710
62711
62712
62713
62714
62715
62716
62717
62718
62719
62720
62721
62722
62723
62724
62725
62726
62727
62728
62729
62730
62731
62732
62733
62734
62735
62736
62737
62738
62739
62740
62741
62742
62743
62744
62745
62746
62747
62748
62749
62750
62751
62752
62753
62754
62755
62756
62757
62758
62759
62760
62761
62762
62763
62764
62765
62766
62767
62768
62769
62770
62771
62772
62773
62774
62775
62776
62777
62778
62779
62780
62781
62782
62783
62784
62785
62786
62787
62788
62789
62790
62791
62792
62793
62794
62795
62796
62797
62798
62799
62800
62801
62802
62803
62804
62805
62806
62807
62808
62809
62810
62811
62812
62813
62814
62815
62816
62817
62818
62819
62820
62821
62822
62823
62824
62825
62826
62827
62828
62829
62830
62831
62832
62833
62834
62835
62836
62837
62838
62839
62840
62841
62842
62843
62844
62845
62846
62847
62848
62849
62850
62851
62852
62853
62854
62855
62856
62857
62858
62859
62860
62861
62862
62863
62864
62865
62866
62867
62868
62869
62870
62871
62872
62873
62874
62875
62876
62877
62878
62879
62880
62881
62882
62883
62884
62885
62886
62887
62888
62889
62890
62891
62892
62893
62894
62895
62896
62897
62898
62899
62900
62901
62902
62903
62904
62905
62906
62907
62908
62909
62910
62911
62912
62913
62914
62915
62916
62917
62918
62919
62920
62921
62922
62923
62924
62925
62926
62927
62928
62929
62930
62931
62932
62933
62934
62935
62936
62937
62938
62939
62940
62941
62942
62943
62944
62945
62946
62947
62948
62949
62950
62951
62952
62953
62954
62955
62956
62957
62958
62959
62960
62961
62962
62963
62964
62965
62966
62967
62968
62969
62970
62971
62972
62973
62974
62975
62976
62977
62978
62979
62980
62981
62982
62983
62984
62985
62986
62987
62988
62989
62990
62991
62992
62993
62994
62995
62996
62997
62998
62999
63000
63001
63002
63003
63004
63005
63006
63007
63008
63009
63010
63011
63012
63013
63014
63015
63016
63017
63018
63019
63020
63021
63022
63023
63024
63025
63026
63027
63028
63029
63030
63031
63032
63033
63034
63035
63036
63037
63038
63039
63040
63041
63042
63043
63044
63045
63046
63047
63048
63049
63050
63051
63052
63053
63054
63055
63056
63057
63058
63059
63060
63061
63062
63063
63064
63065
63066
63067
63068
63069
63070
63071
63072
63073
63074
63075
63076
63077
63078
63079
63080
63081
63082
63083
63084
63085
63086
63087
63088
63089
63090
63091
63092
63093
63094
63095
63096
63097
63098
63099
63100
63101
63102
63103
63104
63105
63106
63107
63108
63109
63110
63111
63112
63113
63114
63115
63116
63117
63118
63119
63120
63121
63122
63123
63124
63125
63126
63127
63128
63129
63130
63131
63132
63133
63134
63135
63136
63137
63138
63139
63140
63141
63142
63143
63144
63145
63146
63147
63148
63149
63150
63151
63152
63153
63154
63155
63156
63157
63158
63159
63160
63161
63162
63163
63164
63165
63166
63167
63168
63169
63170
63171
63172
63173
63174
63175
63176
63177
63178
63179
63180
63181
63182
63183
63184
63185
63186
63187
63188
63189
63190
63191
63192
63193
63194
63195
63196
63197
63198
63199
63200
63201
63202
63203
63204
63205
63206
63207
63208
63209
63210
63211
63212
63213
63214
63215
63216
63217
63218
63219
63220
63221
63222
63223
63224
63225
63226
63227
63228
63229
63230
63231
63232
63233
63234
63235
63236
63237
63238
63239
63240
63241
63242
63243
63244
63245
63246
63247
63248
63249
63250
63251
63252
63253
63254
63255
63256
63257
63258
63259
63260
63261
63262
63263
63264
63265
63266
63267
63268
63269
63270
63271
63272
63273
63274
63275
63276
63277
63278
63279
63280
63281
63282
63283
63284
63285
63286
63287
63288
63289
63290
63291
63292
63293
63294
63295
63296
63297
63298
63299
63300
63301
63302
63303
63304
63305
63306
63307
63308
63309
63310
63311
63312
63313
63314
63315
63316
63317
63318
63319
63320
63321
63322
63323
63324
63325
63326
63327
63328
63329
63330
63331
63332
63333
63334
63335
63336
63337
63338
63339
63340
63341
63342
63343
63344
63345
63346
63347
63348
63349
63350
63351
63352
63353
63354
63355
63356
63357
63358
63359
63360
63361
63362
63363
63364
63365
63366
63367
63368
63369
63370
63371
63372
63373
63374
63375
63376
63377
63378
63379
63380
63381
63382
63383
63384
63385
63386
63387
63388
63389
63390
63391
63392
63393
63394
63395
63396
63397
63398
63399
63400
63401
63402
63403
63404
63405
63406
63407
63408
63409
63410
63411
63412
63413
63414
63415
63416
63417
63418
63419
63420
63421
63422
63423
63424
63425
63426
63427
63428
63429
63430
63431
63432
63433
63434
63435
63436
63437
63438
63439
63440
63441
63442
63443
63444
63445
63446
63447
63448
63449
63450
63451
63452
63453
63454
63455
63456
63457
63458
63459
63460
63461
63462
63463
63464
63465
63466
63467
63468
63469
63470
63471
63472
63473
63474
63475
63476
63477
63478
63479
63480
63481
63482
63483
63484
63485
63486
63487
63488
63489
63490
63491
63492
63493
63494
63495
63496
63497
63498
63499
63500
63501
63502
63503
63504
63505
63506
63507
63508
63509
63510
63511
63512
63513
63514
63515
63516
63517
63518
63519
63520
63521
63522
63523
63524
63525
63526
63527
63528
63529
63530
63531
63532
63533
63534
63535
63536
63537
63538
63539
63540
63541
63542
63543
63544
63545
63546
63547
63548
63549
63550
63551
63552
63553
63554
63555
63556
63557
63558
63559
63560
63561
63562
63563
63564
63565
63566
63567
63568
63569
63570
63571
63572
63573
63574
63575
63576
63577
63578
63579
63580
63581
63582
63583
63584
63585
63586
63587
63588
63589
63590
63591
63592
63593
63594
63595
63596
63597
63598
63599
63600
63601
63602
63603
63604
63605
63606
63607
63608
63609
63610
63611
63612
63613
63614
63615
63616
63617
63618
63619
63620
63621
63622
63623
63624
63625
63626
63627
63628
63629
63630
63631
63632
63633
63634
63635
63636
63637
63638
63639
63640
63641
63642
63643
63644
63645
63646
63647
63648
63649
63650
63651
63652
63653
63654
63655
63656
63657
63658
63659
63660
63661
63662
63663
63664
63665
63666
63667
63668
63669
63670
63671
63672
63673
63674
63675
63676
63677
63678
63679
63680
63681
63682
63683
63684
63685
63686
63687
63688
63689
63690
63691
63692
63693
63694
63695
63696
63697
63698
63699
63700
63701
63702
63703
63704
63705
63706
63707
63708
63709
63710
63711
63712
63713
63714
63715
63716
63717
63718
63719
63720
63721
63722
63723
63724
63725
63726
63727
63728
63729
63730
63731
63732
63733
63734
63735
63736
63737
63738
63739
63740
63741
63742
63743
63744
63745
63746
63747
63748
63749
63750
63751
63752
63753
63754
63755
63756
63757
63758
63759
63760
63761
63762
63763
63764
63765
63766
63767
63768
63769
63770
63771
63772
63773
63774
63775
63776
63777
63778
63779
63780
63781
63782
63783
63784
63785
63786
63787
63788
63789
63790
63791
63792
63793
63794
63795
63796
63797
63798
63799
63800
63801
63802
63803
63804
63805
63806
63807
63808
63809
63810
63811
63812
63813
63814
63815
63816
63817
63818
63819
63820
63821
63822
63823
63824
63825
63826
63827
63828
63829
63830
63831
63832
63833
63834
63835
63836
63837
63838
63839
63840
63841
63842
63843
63844
63845
63846
63847
63848
63849
63850
63851
63852
63853
63854
63855
63856
63857
63858
63859
63860
63861
63862
63863
63864
63865
63866
63867
63868
63869
63870
63871
63872
63873
63874
63875
63876
63877
63878
63879
63880
63881
63882
63883
63884
63885
63886
63887
63888
63889
63890
63891
63892
63893
63894
63895
63896
63897
63898
63899
63900
63901
63902
63903
63904
63905
63906
63907
63908
63909
63910
63911
63912
63913
63914
63915
63916
63917
63918
63919
63920
63921
63922
63923
63924
63925
63926
63927
63928
63929
63930
63931
63932
63933
63934
63935
63936
63937
63938
63939
63940
63941
63942
63943
63944
63945
63946
63947
63948
63949
63950
63951
63952
63953
63954
63955
63956
63957
63958
63959
63960
63961
63962
63963
63964
63965
63966
63967
63968
63969
63970
63971
63972
63973
63974
63975
63976
63977
63978
63979
63980
63981
63982
63983
63984
63985
63986
63987
63988
63989
63990
63991
63992
63993
63994
63995
63996
63997
63998
63999
64000
64001
64002
64003
64004
64005
64006
64007
64008
64009
64010
64011
64012
64013
64014
64015
64016
64017
64018
64019
64020
64021
64022
64023
64024
64025
64026
64027
64028
64029
64030
64031
64032
64033
64034
64035
64036
64037
64038
64039
64040
64041
64042
64043
64044
64045
64046
64047
64048
64049
64050
64051
64052
64053
64054
64055
64056
64057
64058
64059
64060
64061
64062
64063
64064
64065
64066
64067
64068
64069
64070
64071
64072
64073
64074
64075
64076
64077
64078
64079
64080
64081
64082
64083
64084
64085
64086
64087
64088
64089
64090
64091
64092
64093
64094
64095
64096
64097
64098
64099
64100
64101
64102
64103
64104
64105
64106
64107
64108
64109
64110
64111
64112
64113
64114
64115
64116
64117
64118
64119
64120
64121
64122
64123
64124
64125
64126
64127
64128
64129
64130
64131
64132
64133
64134
64135
64136
64137
64138
64139
64140
64141
64142
64143
64144
64145
64146
64147
64148
64149
64150
64151
64152
64153
64154
64155
64156
64157
64158
64159
64160
64161
64162
64163
64164
64165
64166
64167
64168
64169
64170
64171
64172
64173
64174
64175
64176
64177
64178
64179
64180
64181
64182
64183
64184
64185
64186
64187
64188
64189
64190
64191
64192
64193
64194
64195
64196
64197
64198
64199
64200
64201
64202
64203
64204
64205
64206
64207
64208
64209
64210
64211
64212
64213
64214
64215
64216
64217
64218
64219
64220
64221
64222
64223
64224
64225
64226
64227
64228
64229
64230
64231
64232
64233
64234
64235
64236
64237
64238
64239
64240
64241
64242
64243
64244
64245
64246
64247
64248
64249
64250
64251
64252
64253
64254
64255
64256
64257
64258
64259
64260
64261
64262
64263
64264
64265
64266
64267
64268
64269
64270
64271
64272
64273
64274
64275
64276
64277
64278
64279
64280
64281
64282
64283
64284
64285
64286
64287
64288
64289
64290
64291
64292
64293
64294
64295
64296
64297
64298
64299
64300
64301
64302
64303
64304
64305
64306
64307
64308
64309
64310
64311
64312
64313
64314
64315
64316
64317
64318
64319
64320
64321
64322
64323
64324
64325
64326
64327
64328
64329
64330
64331
64332
64333
64334
64335
64336
64337
64338
64339
64340
64341
64342
64343
64344
64345
64346
64347
64348
64349
64350
64351
64352
64353
64354
64355
64356
64357
64358
64359
64360
64361
64362
64363
64364
64365
64366
64367
64368
64369
64370
64371
64372
64373
64374
64375
64376
64377
64378
64379
64380
64381
64382
64383
64384
64385
64386
64387
64388
64389
64390
64391
64392
64393
64394
64395
64396
64397
64398
64399
64400
64401
64402
64403
64404
64405
64406
64407
64408
64409
64410
64411
64412
64413
64414
64415
64416
64417
64418
64419
64420
64421
64422
64423
64424
64425
64426
64427
64428
64429
64430
64431
64432
64433
64434
64435
64436
64437
64438
64439
64440
64441
64442
64443
64444
64445
64446
64447
64448
64449
64450
64451
64452
64453
64454
64455
64456
64457
64458
64459
64460
64461
64462
64463
64464
64465
64466
64467
64468
64469
64470
64471
64472
64473
64474
64475
64476
64477
64478
64479
64480
64481
64482
64483
64484
64485
64486
64487
64488
64489
64490
64491
64492
64493
64494
64495
64496
64497
64498
64499
64500
64501
64502
64503
64504
64505
64506
64507
64508
64509
64510
64511
64512
64513
64514
64515
64516
64517
64518
64519
64520
64521
64522
64523
64524
64525
64526
64527
64528
64529
64530
64531
64532
64533
64534
64535
64536
64537
64538
64539
64540
64541
64542
64543
64544
64545
64546
64547
64548
64549
64550
64551
64552
64553
64554
64555
64556
64557
64558
64559
64560
64561
64562
64563
64564
64565
64566
64567
64568
64569
64570
64571
64572
64573
64574
64575
64576
64577
64578
64579
64580
64581
64582
64583
64584
64585
64586
64587
64588
64589
64590
64591
64592
64593
64594
64595
64596
64597
64598
64599
64600
64601
64602
64603
64604
64605
64606
64607
64608
64609
64610
64611
64612
64613
64614
64615
64616
64617
64618
64619
64620
64621
64622
64623
64624
64625
64626
64627
64628
64629
64630
64631
64632
64633
64634
64635
64636
64637
64638
64639
64640
64641
64642
64643
64644
64645
64646
64647
64648
64649
64650
64651
64652
64653
64654
64655
64656
64657
64658
64659
64660
64661
64662
64663
64664
64665
64666
64667
64668
64669
64670
64671
64672
64673
64674
64675
64676
64677
64678
64679
64680
64681
64682
64683
64684
64685
64686
64687
64688
64689
64690
64691
64692
64693
64694
64695
64696
64697
64698
64699
64700
64701
64702
64703
64704
64705
64706
64707
64708
64709
64710
64711
64712
64713
64714
64715
64716
64717
64718
64719
64720
64721
64722
64723
64724
64725
64726
64727
64728
64729
64730
64731
64732
64733
64734
64735
64736
64737
64738
64739
64740
64741
64742
64743
64744
64745
64746
64747
64748
64749
64750
64751
64752
64753
64754
64755
64756
64757
64758
64759
64760
64761
64762
64763
64764
64765
64766
64767
64768
64769
64770
64771
64772
64773
64774
64775
64776
64777
64778
64779
64780
64781
64782
64783
64784
64785
64786
64787
64788
64789
64790
64791
64792
64793
64794
64795
64796
64797
64798
64799
64800
64801
64802
64803
64804
64805
64806
64807
64808
64809
64810
64811
64812
64813
64814
64815
64816
64817
64818
64819
64820
64821
64822
64823
64824
64825
64826
64827
64828
64829
64830
64831
64832
64833
64834
64835
64836
64837
64838
64839
64840
64841
64842
64843
64844
64845
64846
64847
64848
64849
64850
64851
64852
64853
64854
64855
64856
64857
64858
64859
64860
64861
64862
64863
64864
64865
64866
64867
64868
64869
64870
64871
64872
64873
64874
64875
64876
64877
64878
64879
64880
64881
64882
64883
64884
64885
64886
64887
64888
64889
64890
64891
64892
64893
64894
64895
64896
64897
64898
64899
64900
64901
64902
64903
64904
64905
64906
64907
64908
64909
64910
64911
64912
64913
64914
64915
64916
64917
64918
64919
64920
64921
64922
64923
64924
64925
64926
64927
64928
64929
64930
64931
64932
64933
64934
64935
64936
64937
64938
64939
64940
64941
64942
64943
64944
64945
64946
64947
64948
64949
64950
64951
64952
64953
64954
64955
64956
64957
64958
64959
64960
64961
64962
64963
64964
64965
64966
64967
64968
64969
64970
64971
64972
64973
64974
64975
64976
64977
64978
64979
64980
64981
64982
64983
64984
64985
64986
64987
64988
64989
64990
64991
64992
64993
64994
64995
64996
64997
64998
64999
65000
65001
65002
65003
65004
65005
65006
65007
65008
65009
65010
65011
65012
65013
65014
65015
65016
65017
65018
65019
65020
65021
65022
65023
65024
65025
65026
65027
65028
65029
65030
65031
65032
65033
65034
65035
65036
65037
65038
65039
65040
65041
65042
65043
65044
65045
65046
65047
65048
65049
65050
65051
65052
65053
65054
65055
65056
65057
65058
65059
65060
65061
65062
65063
65064
65065
65066
65067
65068
65069
65070
65071
65072
65073
65074
65075
65076
65077
65078
65079
65080
65081
65082
65083
65084
65085
65086
65087
65088
65089
65090
65091
65092
65093
65094
65095
65096
65097
65098
65099
65100
65101
65102
65103
65104
65105
65106
65107
65108
65109
65110
65111
65112
65113
65114
65115
65116
65117
65118
65119
65120
65121
65122
65123
65124
65125
65126
65127
65128
65129
65130
65131
65132
65133
65134
65135
65136
65137
65138
65139
65140
65141
65142
65143
65144
65145
65146
65147
65148
65149
65150
65151
65152
65153
65154
65155
65156
65157
65158
65159
65160
65161
65162
65163
65164
65165
65166
65167
65168
65169
65170
65171
65172
65173
65174
65175
65176
65177
65178
65179
65180
65181
65182
65183
65184
65185
65186
65187
65188
65189
65190
65191
65192
65193
65194
65195
65196
65197
65198
65199
65200
65201
65202
65203
65204
65205
65206
65207
65208
65209
65210
65211
65212
65213
65214
65215
65216
65217
65218
65219
65220
65221
65222
65223
65224
65225
65226
65227
65228
65229
65230
65231
65232
65233
65234
65235
65236
65237
65238
65239
65240
65241
65242
65243
65244
65245
65246
65247
65248
65249
65250
65251
65252
65253
65254
65255
65256
65257
65258
65259
65260
65261
65262
65263
65264
65265
65266
65267
65268
65269
65270
65271
65272
65273
65274
65275
65276
65277
65278
65279
65280
65281
65282
65283
65284
65285
65286
65287
65288
65289
65290
65291
65292
65293
65294
65295
65296
65297
65298
65299
65300
65301
65302
65303
65304
65305
65306
65307
65308
65309
65310
65311
65312
65313
65314
65315
65316
65317
65318
65319
65320
65321
65322
65323
65324
65325
65326
65327
65328
65329
65330
65331
65332
65333
65334
65335
65336
65337
65338
65339
65340
65341
65342
65343
65344
65345
65346
65347
65348
65349
65350
65351
65352
65353
65354
65355
65356
65357
65358
65359
65360
65361
65362
65363
65364
65365
65366
65367
65368
65369
65370
65371
65372
65373
65374
65375
65376
65377
65378
65379
65380
65381
65382
65383
65384
65385
65386
65387
65388
65389
65390
65391
65392
65393
65394
65395
65396
65397
65398
65399
65400
65401
65402
65403
65404
65405
65406
65407
65408
65409
65410
65411
65412
65413
65414
65415
65416
65417
65418
65419
65420
65421
65422
65423
65424
65425
65426
65427
65428
65429
65430
65431
65432
65433
65434
65435
65436
65437
65438
65439
65440
65441
65442
65443
65444
65445
65446
65447
65448
65449
65450
65451
65452
65453
65454
65455
65456
65457
65458
65459
65460
65461
65462
65463
65464
65465
65466
65467
65468
65469
65470
65471
65472
65473
65474
65475
65476
65477
65478
65479
65480
65481
65482
65483
65484
65485
65486
65487
65488
65489
65490
65491
65492
65493
65494
65495
65496
65497
65498
65499
65500
65501
65502
65503
65504
65505
65506
65507
65508
65509
65510
65511
65512
65513
65514
65515
65516
65517
65518
65519
65520
65521
65522
65523
65524
65525
65526
65527
65528
65529
65530
65531
65532
65533
65534
65535
65536
65537
65538
65539
65540
65541
65542
65543
65544
65545
65546
65547
65548
65549
65550
65551
65552
65553
65554
65555
65556
65557
65558
65559
65560
65561
65562
65563
65564
65565
65566
65567
65568
65569
65570
65571
65572
65573
65574
65575
65576
65577
65578
65579
65580
65581
65582
65583
65584
65585
65586
65587
65588
65589
65590
65591
65592
65593
65594
65595
65596
65597
65598
65599
65600
65601
65602
65603
65604
65605
65606
65607
65608
65609
65610
65611
65612
65613
65614
65615
65616
65617
65618
65619
65620
65621
65622
65623
65624
65625
65626
65627
65628
65629
65630
65631
65632
65633
65634
65635
65636
65637
65638
65639
65640
65641
65642
65643
65644
65645
65646
65647
65648
65649
65650
65651
65652
65653
65654
65655
65656
65657
65658
65659
65660
65661
65662
65663
65664
65665
65666
65667
65668
65669
65670
65671
65672
65673
65674
65675
65676
65677
65678
65679
65680
65681
65682
65683
65684
65685
65686
65687
65688
65689
65690
65691
65692
65693
65694
65695
65696
65697
65698
65699
65700
65701
65702
65703
65704
65705
65706
65707
65708
65709
65710
65711
65712
65713
65714
65715
65716
65717
65718
65719
65720
65721
65722
65723
65724
65725
65726
65727
65728
65729
65730
65731
65732
65733
65734
65735
65736
65737
65738
65739
65740
65741
65742
65743
65744
65745
65746
65747
65748
65749
65750
65751
65752
65753
65754
65755
65756
65757
65758
65759
65760
65761
65762
65763
65764
65765
65766
65767
65768
65769
65770
65771
65772
65773
65774
65775
65776
65777
65778
65779
65780
65781
65782
65783
65784
65785
65786
65787
65788
65789
65790
65791
65792
65793
65794
65795
65796
65797
65798
65799
65800
65801
65802
65803
65804
65805
65806
65807
65808
65809
65810
65811
65812
65813
65814
65815
65816
65817
65818
65819
65820
65821
65822
65823
65824
65825
65826
65827
65828
65829
65830
65831
65832
65833
65834
65835
65836
65837
65838
65839
65840
65841
65842
65843
65844
65845
65846
65847
65848
65849
65850
65851
65852
65853
65854
65855
65856
65857
65858
65859
65860
65861
65862
65863
65864
65865
65866
65867
65868
65869
65870
65871
65872
65873
65874
65875
65876
65877
65878
65879
65880
65881
65882
65883
65884
65885
65886
65887
65888
65889
65890
65891
65892
65893
65894
65895
65896
65897
65898
65899
65900
65901
65902
65903
65904
65905
65906
65907
65908
65909
65910
65911
65912
65913
65914
65915
65916
65917
65918
65919
65920
65921
65922
65923
65924
65925
65926
65927
65928
65929
65930
65931
65932
65933
65934
65935
65936
65937
65938
65939
65940
65941
65942
65943
65944
65945
65946
65947
65948
65949
65950
65951
65952
65953
65954
65955
65956
65957
65958
65959
65960
65961
65962
65963
65964
65965
65966
65967
65968
65969
65970
65971
65972
65973
65974
65975
65976
65977
65978
65979
65980
65981
65982
65983
65984
65985
65986
65987
65988
65989
65990
65991
65992
65993
65994
65995
65996
65997
65998
65999
66000
66001
66002
66003
66004
66005
66006
66007
66008
66009
66010
66011
66012
66013
66014
66015
66016
66017
66018
66019
66020
66021
66022
66023
66024
66025
66026
66027
66028
66029
66030
66031
66032
66033
66034
66035
66036
66037
66038
66039
66040
66041
66042
66043
66044
66045
66046
66047
66048
66049
66050
66051
66052
66053
66054
66055
66056
66057
66058
66059
66060
66061
66062
66063
66064
66065
66066
66067
66068
66069
66070
66071
66072
66073
66074
66075
66076
66077
66078
66079
66080
66081
66082
66083
66084
66085
66086
66087
66088
66089
66090
66091
66092
66093
66094
66095
66096
66097
66098
66099
66100
66101
66102
66103
66104
66105
66106
66107
66108
66109
66110
66111
66112
66113
66114
66115
66116
66117
66118
66119
66120
66121
66122
66123
66124
66125
66126
66127
66128
66129
66130
66131
66132
66133
66134
66135
66136
66137
66138
66139
66140
66141
66142
66143
66144
66145
66146
66147
66148
66149
66150
66151
66152
66153
66154
66155
66156
66157
66158
66159
66160
66161
66162
66163
66164
66165
66166
66167
66168
66169
66170
66171
66172
66173
66174
66175
66176
66177
66178
66179
66180
66181
66182
66183
66184
66185
66186
66187
66188
66189
66190
66191
66192
66193
66194
66195
66196
66197
66198
66199
66200
66201
66202
66203
66204
66205
66206
66207
66208
66209
66210
66211
66212
66213
66214
66215
66216
66217
66218
66219
66220
66221
66222
66223
66224
66225
66226
66227
66228
66229
66230
66231
66232
66233
66234
66235
66236
66237
66238
66239
66240
66241
66242
66243
66244
66245
66246
66247
66248
66249
66250
66251
66252
66253
66254
66255
66256
66257
66258
66259
66260
66261
66262
66263
66264
66265
66266
66267
66268
66269
66270
66271
66272
66273
66274
66275
66276
66277
66278
66279
66280
66281
66282
66283
66284
66285
66286
66287
66288
66289
66290
66291
66292
66293
66294
66295
66296
66297
66298
66299
66300
66301
66302
66303
66304
66305
66306
66307
66308
66309
66310
66311
66312
66313
66314
66315
66316
66317
66318
66319
66320
66321
66322
66323
66324
66325
66326
66327
66328
66329
66330
66331
66332
66333
66334
66335
66336
66337
66338
66339
66340
66341
66342
66343
66344
66345
66346
66347
66348
66349
66350
66351
66352
66353
66354
66355
66356
66357
66358
66359
66360
66361
66362
66363
66364
66365
66366
66367
66368
66369
66370
66371
66372
66373
66374
66375
66376
66377
66378
66379
66380
66381
66382
66383
66384
66385
66386
66387
66388
66389
66390
66391
66392
66393
66394
66395
66396
66397
66398
66399
66400
66401
66402
66403
66404
66405
66406
66407
66408
66409
66410
66411
66412
66413
66414
66415
66416
66417
66418
66419
66420
66421
66422
66423
66424
66425
66426
66427
66428
66429
66430
66431
66432
66433
66434
66435
66436
66437
66438
66439
66440
66441
66442
66443
66444
66445
66446
66447
66448
66449
66450
66451
66452
66453
66454
66455
66456
66457
66458
66459
66460
66461
66462
66463
66464
66465
66466
66467
66468
66469
66470
66471
66472
66473
66474
66475
66476
66477
66478
66479
66480
66481
66482
66483
66484
66485
66486
66487
66488
66489
66490
66491
66492
66493
66494
66495
66496
66497
66498
66499
66500
66501
66502
66503
66504
66505
66506
66507
66508
66509
66510
66511
66512
66513
66514
66515
66516
66517
66518
66519
66520
66521
66522
66523
66524
66525
66526
66527
66528
66529
66530
66531
66532
66533
66534
66535
66536
66537
66538
66539
66540
66541
66542
66543
66544
66545
66546
66547
66548
66549
66550
66551
66552
66553
66554
66555
66556
66557
66558
66559
66560
66561
66562
66563
66564
66565
66566
66567
66568
66569
66570
66571
66572
66573
66574
66575
66576
66577
66578
66579
66580
66581
66582
66583
66584
66585
66586
66587
66588
66589
66590
66591
66592
66593
66594
66595
66596
66597
66598
66599
66600
66601
66602
66603
66604
66605
66606
66607
66608
66609
66610
66611
66612
66613
66614
66615
66616
66617
66618
66619
66620
66621
66622
66623
66624
66625
66626
66627
66628
66629
66630
66631
66632
66633
66634
66635
66636
66637
66638
66639
66640
66641
66642
66643
66644
66645
66646
66647
66648
66649
66650
66651
66652
66653
66654
66655
66656
66657
66658
66659
66660
66661
66662
66663
66664
66665
66666
66667
66668
66669
66670
66671
66672
66673
66674
66675
66676
66677
66678
66679
66680
66681
66682
66683
66684
66685
66686
66687
66688
66689
66690
66691
66692
66693
66694
66695
66696
66697
66698
66699
66700
66701
66702
66703
66704
66705
66706
66707
66708
66709
66710
66711
66712
66713
66714
66715
66716
66717
66718
66719
66720
66721
66722
66723
66724
66725
66726
66727
66728
66729
66730
66731
66732
66733
66734
66735
66736
66737
66738
66739
66740
66741
66742
66743
66744
66745
66746
66747
66748
66749
66750
66751
66752
66753
66754
66755
66756
66757
66758
66759
66760
66761
66762
66763
66764
66765
66766
66767
66768
66769
66770
66771
66772
66773
66774
66775
66776
66777
66778
66779
66780
66781
66782
66783
66784
66785
66786
66787
66788
66789
66790
66791
66792
66793
66794
66795
66796
66797
66798
66799
66800
66801
66802
66803
66804
66805
66806
66807
66808
66809
66810
66811
66812
66813
66814
66815
66816
66817
66818
66819
66820
66821
66822
66823
66824
66825
66826
66827
66828
66829
66830
66831
66832
66833
66834
66835
66836
66837
66838
66839
66840
66841
66842
66843
66844
66845
66846
66847
66848
66849
66850
66851
66852
66853
66854
66855
66856
66857
66858
66859
66860
66861
66862
66863
66864
66865
66866
66867
66868
66869
66870
66871
66872
66873
66874
66875
66876
66877
66878
66879
66880
66881
66882
66883
66884
66885
66886
66887
66888
66889
66890
66891
66892
66893
66894
66895
66896
66897
66898
66899
66900
66901
66902
66903
66904
66905
66906
66907
66908
66909
66910
66911
66912
66913
66914
66915
66916
66917
66918
66919
66920
66921
66922
66923
66924
66925
66926
66927
66928
66929
66930
66931
66932
66933
66934
66935
66936
66937
66938
66939
66940
66941
66942
66943
66944
66945
66946
66947
66948
66949
66950
66951
66952
66953
66954
66955
66956
66957
66958
66959
66960
66961
66962
66963
66964
66965
66966
66967
66968
66969
66970
66971
66972
66973
66974
66975
66976
66977
66978
66979
66980
66981
66982
66983
66984
66985
66986
66987
66988
66989
66990
66991
66992
66993
66994
66995
66996
66997
66998
66999
67000
67001
67002
67003
67004
67005
67006
67007
67008
67009
67010
67011
67012
67013
67014
67015
67016
67017
67018
67019
67020
67021
67022
67023
67024
67025
67026
67027
67028
67029
67030
67031
67032
67033
67034
67035
67036
67037
67038
67039
67040
67041
67042
67043
67044
67045
67046
67047
67048
67049
67050
67051
67052
67053
67054
67055
67056
67057
67058
67059
67060
67061
67062
67063
67064
67065
67066
67067
67068
67069
67070
67071
67072
67073
67074
67075
67076
67077
67078
67079
67080
67081
67082
67083
67084
67085
67086
67087
67088
67089
67090
67091
67092
67093
67094
67095
67096
67097
67098
67099
67100
67101
67102
67103
67104
67105
67106
67107
67108
67109
67110
67111
67112
67113
67114
67115
67116
67117
67118
67119
67120
67121
67122
67123
67124
67125
67126
67127
67128
67129
67130
67131
67132
67133
67134
67135
67136
67137
67138
67139
67140
67141
67142
67143
67144
67145
67146
67147
67148
67149
67150
67151
67152
67153
67154
67155
67156
67157
67158
67159
67160
67161
67162
67163
67164
67165
67166
67167
67168
67169
67170
67171
67172
67173
67174
67175
67176
67177
67178
67179
67180
67181
67182
67183
67184
67185
67186
67187
67188
67189
67190
67191
67192
67193
67194
67195
67196
67197
67198
67199
67200
67201
67202
67203
67204
67205
67206
67207
67208
67209
67210
67211
67212
67213
67214
67215
67216
67217
67218
67219
67220
67221
67222
67223
67224
67225
67226
67227
67228
67229
67230
67231
67232
67233
67234
67235
67236
67237
67238
67239
67240
67241
67242
67243
67244
67245
67246
67247
67248
67249
67250
67251
67252
67253
67254
67255
67256
67257
67258
67259
67260
67261
67262
67263
67264
67265
67266
67267
67268
67269
67270
67271
67272
67273
67274
67275
67276
67277
67278
67279
67280
67281
67282
67283
67284
67285
67286
67287
67288
67289
67290
67291
67292
67293
67294
67295
67296
67297
67298
67299
67300
67301
67302
67303
67304
67305
67306
67307
67308
67309
67310
67311
67312
67313
67314
67315
67316
67317
67318
67319
67320
67321
67322
67323
67324
67325
67326
67327
67328
67329
67330
67331
67332
67333
67334
67335
67336
67337
67338
67339
67340
67341
67342
67343
67344
67345
67346
67347
67348
67349
67350
67351
67352
67353
67354
67355
67356
67357
67358
67359
67360
67361
67362
67363
67364
67365
67366
67367
67368
67369
67370
67371
67372
67373
67374
67375
67376
67377
67378
67379
67380
67381
67382
67383
67384
67385
67386
67387
67388
67389
67390
67391
67392
67393
67394
67395
67396
67397
67398
67399
67400
67401
67402
67403
67404
67405
67406
67407
67408
67409
67410
67411
67412
67413
67414
67415
67416
67417
67418
67419
67420
67421
67422
67423
67424
67425
67426
67427
67428
67429
67430
67431
67432
67433
67434
67435
67436
67437
67438
67439
67440
67441
67442
67443
67444
67445
67446
67447
67448
67449
67450
67451
67452
67453
67454
67455
67456
67457
67458
67459
67460
67461
67462
67463
67464
67465
67466
67467
67468
67469
67470
67471
67472
67473
67474
67475
67476
67477
67478
67479
67480
67481
67482
67483
67484
67485
67486
67487
67488
67489
67490
67491
67492
67493
67494
67495
67496
67497
67498
67499
67500
67501
67502
67503
67504
67505
67506
67507
67508
67509
67510
67511
67512
67513
67514
67515
67516
67517
67518
67519
67520
67521
67522
67523
67524
67525
67526
67527
67528
67529
67530
67531
67532
67533
67534
67535
67536
67537
67538
67539
67540
67541
67542
67543
67544
67545
67546
67547
67548
67549
67550
67551
67552
67553
67554
67555
67556
67557
67558
67559
67560
67561
67562
67563
67564
67565
67566
67567
67568
67569
67570
67571
67572
67573
67574
67575
67576
67577
67578
67579
67580
67581
67582
67583
67584
67585
67586
67587
67588
67589
67590
67591
67592
67593
67594
67595
67596
67597
67598
67599
67600
67601
67602
67603
67604
67605
67606
67607
67608
67609
67610
67611
67612
67613
67614
67615
67616
67617
67618
67619
67620
67621
67622
67623
67624
67625
67626
67627
67628
67629
67630
67631
67632
67633
67634
67635
67636
67637
67638
67639
67640
67641
67642
67643
67644
67645
67646
67647
67648
67649
67650
67651
67652
67653
67654
67655
67656
67657
67658
67659
67660
67661
67662
67663
67664
67665
67666
67667
67668
67669
67670
67671
67672
67673
67674
67675
67676
67677
67678
67679
67680
67681
67682
67683
67684
67685
67686
67687
67688
67689
67690
67691
67692
67693
67694
67695
67696
67697
67698
67699
67700
67701
67702
67703
67704
67705
67706
67707
67708
67709
67710
67711
67712
67713
67714
67715
67716
67717
67718
67719
67720
67721
67722
67723
67724
67725
67726
67727
67728
67729
67730
67731
67732
67733
67734
67735
67736
67737
67738
67739
67740
67741
67742
67743
67744
67745
67746
67747
67748
67749
67750
67751
67752
67753
67754
67755
67756
67757
67758
67759
67760
67761
67762
67763
67764
67765
67766
67767
67768
67769
67770
67771
67772
67773
67774
67775
67776
67777
67778
67779
67780
67781
67782
67783
67784
67785
67786
67787
67788
67789
67790
67791
67792
67793
67794
67795
67796
67797
67798
67799
67800
67801
67802
67803
67804
67805
67806
67807
67808
67809
67810
67811
67812
67813
67814
67815
67816
67817
67818
67819
67820
67821
67822
67823
67824
67825
67826
67827
67828
67829
67830
67831
67832
67833
67834
67835
67836
67837
67838
67839
67840
67841
67842
67843
67844
67845
67846
67847
67848
67849
67850
67851
67852
67853
67854
67855
67856
67857
67858
67859
67860
67861
67862
67863
67864
67865
67866
67867
67868
67869
67870
67871
67872
67873
67874
67875
67876
67877
67878
67879
67880
67881
67882
67883
67884
67885
67886
67887
67888
67889
67890
67891
67892
67893
67894
67895
67896
67897
67898
67899
67900
67901
67902
67903
67904
67905
67906
67907
67908
67909
67910
67911
67912
67913
67914
67915
67916
67917
67918
67919
67920
67921
67922
67923
67924
67925
67926
67927
67928
67929
67930
67931
67932
67933
67934
67935
67936
67937
67938
67939
67940
67941
67942
67943
67944
67945
67946
67947
67948
67949
67950
67951
67952
67953
67954
67955
67956
67957
67958
67959
67960
67961
67962
67963
67964
67965
67966
67967
67968
67969
67970
67971
67972
67973
67974
67975
67976
67977
67978
67979
67980
67981
67982
67983
67984
67985
67986
67987
67988
67989
67990
67991
67992
67993
67994
67995
67996
67997
67998
67999
68000
68001
68002
68003
68004
68005
68006
68007
68008
68009
68010
68011
68012
68013
68014
68015
68016
68017
68018
68019
68020
68021
68022
68023
68024
68025
68026
68027
68028
68029
68030
68031
68032
68033
68034
68035
68036
68037
68038
68039
68040
68041
68042
68043
68044
68045
68046
68047
68048
68049
68050
68051
68052
68053
68054
68055
68056
68057
68058
68059
68060
68061
68062
68063
68064
68065
68066
68067
68068
68069
68070
68071
68072
68073
68074
68075
68076
68077
68078
68079
68080
68081
68082
68083
68084
68085
68086
68087
68088
68089
68090
68091
68092
68093
68094
68095
68096
68097
68098
68099
68100
68101
68102
68103
68104
68105
68106
68107
68108
68109
68110
68111
68112
68113
68114
68115
68116
68117
68118
68119
68120
68121
68122
68123
68124
68125
68126
68127
68128
68129
68130
68131
68132
68133
68134
68135
68136
68137
68138
68139
68140
68141
68142
68143
68144
68145
68146
68147
68148
68149
68150
68151
68152
68153
68154
68155
68156
68157
68158
68159
68160
68161
68162
68163
68164
68165
68166
68167
68168
68169
68170
68171
68172
68173
68174
68175
68176
68177
68178
68179
68180
68181
68182
68183
68184
68185
68186
68187
68188
68189
68190
68191
68192
68193
68194
68195
68196
68197
68198
68199
68200
68201
68202
68203
68204
68205
68206
68207
68208
68209
68210
68211
68212
68213
68214
68215
68216
68217
68218
68219
68220
68221
68222
68223
68224
68225
68226
68227
68228
68229
68230
68231
68232
68233
68234
68235
68236
68237
68238
68239
68240
68241
68242
68243
68244
68245
68246
68247
68248
68249
68250
68251
68252
68253
68254
68255
68256
68257
68258
68259
68260
68261
68262
68263
68264
68265
68266
68267
68268
68269
68270
68271
68272
68273
68274
68275
68276
68277
68278
68279
68280
68281
68282
68283
68284
68285
68286
68287
68288
68289
68290
68291
68292
68293
68294
68295
68296
68297
68298
68299
68300
68301
68302
68303
68304
68305
68306
68307
68308
68309
68310
68311
68312
68313
68314
68315
68316
68317
68318
68319
68320
68321
68322
68323
68324
68325
68326
68327
68328
68329
68330
68331
68332
68333
68334
68335
68336
68337
68338
68339
68340
68341
68342
68343
68344
68345
68346
68347
68348
68349
68350
68351
68352
68353
68354
68355
68356
68357
68358
68359
68360
68361
68362
68363
68364
68365
68366
68367
68368
68369
68370
68371
68372
68373
68374
68375
68376
68377
68378
68379
68380
68381
68382
68383
68384
68385
68386
68387
68388
68389
68390
68391
68392
68393
68394
68395
68396
68397
68398
68399
68400
68401
68402
68403
68404
68405
68406
68407
68408
68409
68410
68411
68412
68413
68414
68415
68416
68417
68418
68419
68420
68421
68422
68423
68424
68425
68426
68427
68428
68429
68430
68431
68432
68433
68434
68435
68436
68437
68438
68439
68440
68441
68442
68443
68444
68445
68446
68447
68448
68449
68450
68451
68452
68453
68454
68455
68456
68457
68458
68459
68460
68461
68462
68463
68464
68465
68466
68467
68468
68469
68470
68471
68472
68473
68474
68475
68476
68477
68478
68479
68480
68481
68482
68483
68484
68485
68486
68487
68488
68489
68490
68491
68492
68493
68494
68495
68496
68497
68498
68499
68500
68501
68502
68503
68504
68505
68506
68507
68508
68509
68510
68511
68512
68513
68514
68515
68516
68517
68518
68519
68520
68521
68522
68523
68524
68525
68526
68527
68528
68529
68530
68531
68532
68533
68534
68535
68536
68537
68538
68539
68540
68541
68542
68543
68544
68545
68546
68547
68548
68549
68550
68551
68552
68553
68554
68555
68556
68557
68558
68559
68560
68561
68562
68563
68564
68565
68566
68567
68568
68569
68570
68571
68572
68573
68574
68575
68576
68577
68578
68579
68580
68581
68582
68583
68584
68585
68586
68587
68588
68589
68590
68591
68592
68593
68594
68595
68596
68597
68598
68599
68600
68601
68602
68603
68604
68605
68606
68607
68608
68609
68610
68611
68612
68613
68614
68615
68616
68617
68618
68619
68620
68621
68622
68623
68624
68625
68626
68627
68628
68629
68630
68631
68632
68633
68634
68635
68636
68637
68638
68639
68640
68641
68642
68643
68644
68645
68646
68647
68648
68649
68650
68651
68652
68653
68654
68655
68656
68657
68658
68659
68660
68661
68662
68663
68664
68665
68666
68667
68668
68669
68670
68671
68672
68673
68674
68675
68676
68677
68678
68679
68680
68681
68682
68683
68684
68685
68686
68687
68688
68689
68690
68691
68692
68693
68694
68695
68696
68697
68698
68699
68700
68701
68702
68703
68704
68705
68706
68707
68708
68709
68710
68711
68712
68713
68714
68715
68716
68717
68718
68719
68720
68721
68722
68723
68724
68725
68726
68727
68728
68729
68730
68731
68732
68733
68734
68735
68736
68737
68738
68739
68740
68741
68742
68743
68744
68745
68746
68747
68748
68749
68750
68751
68752
68753
68754
68755
68756
68757
68758
68759
68760
68761
68762
68763
68764
68765
68766
68767
68768
68769
68770
68771
68772
68773
68774
68775
68776
68777
68778
68779
68780
68781
68782
68783
68784
68785
68786
68787
68788
68789
68790
68791
68792
68793
68794
68795
68796
68797
68798
68799
68800
68801
68802
68803
68804
68805
68806
68807
68808
68809
68810
68811
68812
68813
68814
68815
68816
68817
68818
68819
68820
68821
68822
68823
68824
68825
68826
68827
68828
68829
68830
68831
68832
68833
68834
68835
68836
68837
68838
68839
68840
68841
68842
68843
68844
68845
68846
68847
68848
68849
68850
68851
68852
68853
68854
68855
68856
68857
68858
68859
68860
68861
68862
68863
68864
68865
68866
68867
68868
68869
68870
68871
68872
68873
68874
68875
68876
68877
68878
68879
68880
68881
68882
68883
68884
68885
68886
68887
68888
68889
68890
68891
68892
68893
68894
68895
68896
68897
68898
68899
68900
68901
68902
68903
68904
68905
68906
68907
68908
68909
68910
68911
68912
68913
68914
68915
68916
68917
68918
68919
68920
68921
68922
68923
68924
68925
68926
68927
68928
68929
68930
68931
68932
68933
68934
68935
68936
68937
68938
68939
68940
68941
68942
68943
68944
68945
68946
68947
68948
68949
68950
68951
68952
68953
68954
68955
68956
68957
68958
68959
68960
68961
68962
68963
68964
68965
68966
68967
68968
68969
68970
68971
68972
68973
68974
68975
68976
68977
68978
68979
68980
68981
68982
68983
68984
68985
68986
68987
68988
68989
68990
68991
68992
68993
68994
68995
68996
68997
68998
68999
69000
69001
69002
69003
69004
69005
69006
69007
69008
69009
69010
69011
69012
69013
69014
69015
69016
69017
69018
69019
69020
69021
69022
69023
69024
69025
69026
69027
69028
69029
69030
69031
69032
69033
69034
69035
69036
69037
69038
69039
69040
69041
69042
69043
69044
69045
69046
69047
69048
69049
69050
69051
69052
69053
69054
69055
69056
69057
69058
69059
69060
69061
69062
69063
69064
69065
69066
69067
69068
69069
69070
69071
69072
69073
69074
69075
69076
69077
69078
69079
69080
69081
69082
69083
69084
69085
69086
69087
69088
69089
69090
69091
69092
69093
69094
69095
69096
69097
69098
69099
69100
69101
69102
69103
69104
69105
69106
69107
69108
69109
69110
69111
69112
69113
69114
69115
69116
69117
69118
69119
69120
69121
69122
69123
69124
69125
69126
69127
69128
69129
69130
69131
69132
69133
69134
69135
69136
69137
69138
69139
69140
69141
69142
69143
69144
69145
69146
69147
69148
69149
69150
69151
69152
69153
69154
69155
69156
69157
69158
69159
69160
69161
69162
69163
69164
69165
69166
69167
69168
69169
69170
69171
69172
69173
69174
69175
69176
69177
69178
69179
69180
69181
69182
69183
69184
69185
69186
69187
69188
69189
69190
69191
69192
69193
69194
69195
69196
69197
69198
69199
69200
69201
69202
69203
69204
69205
69206
69207
69208
69209
69210
69211
69212
69213
69214
69215
69216
69217
69218
69219
69220
69221
69222
69223
69224
69225
69226
69227
69228
69229
69230
69231
69232
69233
69234
69235
69236
69237
69238
69239
69240
69241
69242
69243
69244
69245
69246
69247
69248
69249
69250
69251
69252
69253
69254
69255
69256
69257
69258
69259
69260
69261
69262
69263
69264
69265
69266
69267
69268
69269
69270
69271
69272
69273
69274
69275
69276
69277
69278
69279
69280
69281
69282
69283
69284
69285
69286
69287
69288
69289
69290
69291
69292
69293
69294
69295
69296
69297
69298
69299
69300
69301
69302
69303
69304
69305
69306
69307
69308
69309
69310
69311
69312
69313
69314
69315
69316
69317
69318
69319
69320
69321
69322
69323
69324
69325
69326
69327
69328
69329
69330
69331
69332
69333
69334
69335
69336
69337
69338
69339
69340
69341
69342
69343
69344
69345
69346
69347
69348
69349
69350
69351
69352
69353
69354
69355
69356
69357
69358
69359
69360
69361
69362
69363
69364
69365
69366
69367
69368
69369
69370
69371
69372
69373
69374
69375
69376
69377
69378
69379
69380
69381
69382
69383
69384
69385
69386
69387
69388
69389
69390
69391
69392
69393
69394
69395
69396
69397
69398
69399
69400
69401
69402
69403
69404
69405
69406
69407
69408
69409
69410
69411
69412
69413
69414
69415
69416
69417
69418
69419
69420
69421
69422
69423
69424
69425
69426
69427
69428
69429
69430
69431
69432
69433
69434
69435
69436
69437
69438
69439
69440
69441
69442
69443
69444
69445
69446
69447
69448
69449
69450
69451
69452
69453
69454
69455
69456
69457
69458
69459
69460
69461
69462
69463
69464
69465
69466
69467
69468
69469
69470
69471
69472
69473
69474
69475
69476
69477
69478
69479
69480
69481
69482
69483
69484
69485
69486
69487
69488
69489
69490
69491
69492
69493
69494
69495
69496
69497
69498
69499
69500
69501
69502
69503
69504
69505
69506
69507
69508
69509
69510
69511
69512
69513
69514
69515
69516
69517
69518
69519
69520
69521
69522
69523
69524
69525
69526
69527
69528
69529
69530
69531
69532
69533
69534
69535
69536
69537
69538
69539
69540
69541
69542
69543
69544
69545
69546
69547
69548
69549
69550
69551
69552
69553
69554
69555
69556
69557
69558
69559
69560
69561
69562
69563
69564
69565
69566
69567
69568
69569
69570
69571
69572
69573
69574
69575
69576
69577
69578
69579
69580
69581
69582
69583
69584
69585
69586
69587
69588
69589
69590
69591
69592
69593
69594
69595
69596
69597
69598
69599
69600
69601
69602
69603
69604
69605
69606
69607
69608
69609
69610
69611
69612
69613
69614
69615
69616
69617
69618
69619
69620
69621
69622
69623
69624
69625
69626
69627
69628
69629
69630
69631
69632
69633
69634
69635
69636
69637
69638
69639
69640
69641
69642
69643
69644
69645
69646
69647
69648
69649
69650
69651
69652
69653
69654
69655
69656
69657
69658
69659
69660
69661
69662
69663
69664
69665
69666
69667
69668
69669
69670
69671
69672
69673
69674
69675
69676
69677
69678
69679
69680
69681
69682
69683
69684
69685
69686
69687
69688
69689
69690
69691
69692
69693
69694
69695
69696
69697
69698
69699
69700
69701
69702
69703
69704
69705
69706
69707
69708
69709
69710
69711
69712
69713
69714
69715
69716
69717
69718
69719
69720
69721
69722
69723
69724
69725
69726
69727
69728
69729
69730
69731
69732
69733
69734
69735
69736
69737
69738
69739
69740
69741
69742
69743
69744
69745
69746
69747
69748
69749
69750
69751
69752
69753
69754
69755
69756
69757
69758
69759
69760
69761
69762
69763
69764
69765
69766
69767
69768
69769
69770
69771
69772
69773
69774
69775
69776
69777
69778
69779
69780
69781
69782
69783
69784
69785
69786
69787
69788
69789
69790
69791
69792
69793
69794
69795
69796
69797
69798
69799
69800
69801
69802
69803
69804
69805
69806
69807
69808
69809
69810
69811
69812
69813
69814
69815
69816
69817
69818
69819
69820
69821
69822
69823
69824
69825
69826
69827
69828
69829
69830
69831
69832
69833
69834
69835
69836
69837
69838
69839
69840
69841
69842
69843
69844
69845
69846
69847
69848
69849
69850
69851
69852
69853
69854
69855
69856
69857
69858
69859
69860
69861
69862
69863
69864
69865
69866
69867
69868
69869
69870
69871
69872
69873
69874
69875
69876
69877
69878
69879
69880
69881
69882
69883
69884
69885
69886
69887
69888
69889
69890
69891
69892
69893
69894
69895
69896
69897
69898
69899
69900
69901
69902
69903
69904
69905
69906
69907
69908
69909
69910
69911
69912
69913
69914
69915
69916
69917
69918
69919
69920
69921
69922
69923
69924
69925
69926
69927
69928
69929
69930
69931
69932
69933
69934
69935
69936
69937
69938
69939
69940
69941
69942
69943
69944
69945
69946
69947
69948
69949
69950
69951
69952
69953
69954
69955
69956
69957
69958
69959
69960
69961
69962
69963
69964
69965
69966
69967
69968
69969
69970
69971
69972
69973
69974
69975
69976
69977
69978
69979
69980
69981
69982
69983
69984
69985
69986
69987
69988
69989
69990
69991
69992
69993
69994
69995
69996
69997
69998
69999
70000
70001
70002
70003
70004
70005
70006
70007
70008
70009
70010
70011
70012
70013
70014
70015
70016
70017
70018
70019
70020
70021
70022
70023
70024
70025
70026
70027
70028
70029
70030
70031
70032
70033
70034
70035
70036
70037
70038
70039
70040
70041
70042
70043
70044
70045
70046
70047
70048
70049
70050
70051
70052
70053
70054
70055
70056
70057
70058
70059
70060
70061
70062
70063
70064
70065
70066
70067
70068
70069
70070
70071
70072
70073
70074
70075
70076
70077
70078
70079
70080
70081
70082
70083
70084
70085
70086
70087
70088
70089
70090
70091
70092
70093
70094
70095
70096
70097
70098
70099
70100
70101
70102
70103
70104
70105
70106
70107
70108
70109
70110
70111
70112
70113
70114
70115
70116
70117
70118
70119
70120
70121
70122
70123
70124
70125
70126
70127
70128
70129
70130
70131
70132
70133
70134
70135
70136
70137
70138
70139
70140
70141
70142
70143
70144
70145
70146
70147
70148
70149
70150
70151
70152
70153
70154
70155
70156
70157
70158
70159
70160
70161
70162
70163
70164
70165
70166
70167
70168
70169
70170
70171
70172
70173
70174
70175
70176
70177
70178
70179
70180
70181
70182
70183
70184
70185
70186
70187
70188
70189
70190
70191
70192
70193
70194
70195
70196
70197
70198
70199
70200
70201
70202
70203
70204
70205
70206
70207
70208
70209
70210
70211
70212
70213
70214
70215
70216
70217
70218
70219
70220
70221
70222
70223
70224
70225
70226
70227
70228
70229
70230
70231
70232
70233
70234
70235
70236
70237
70238
70239
70240
70241
70242
70243
70244
70245
70246
70247
70248
70249
70250
70251
70252
70253
70254
70255
70256
70257
70258
70259
70260
70261
70262
70263
70264
70265
70266
70267
70268
70269
70270
70271
70272
70273
70274
70275
70276
70277
70278
70279
70280
70281
70282
70283
70284
70285
70286
70287
70288
70289
70290
70291
70292
70293
70294
70295
70296
70297
70298
70299
70300
70301
70302
70303
70304
70305
70306
70307
70308
70309
70310
70311
70312
70313
70314
70315
70316
70317
70318
70319
70320
70321
70322
70323
70324
70325
70326
70327
70328
70329
70330
70331
70332
70333
70334
70335
70336
70337
70338
70339
70340
70341
70342
70343
70344
70345
70346
70347
70348
70349
70350
70351
70352
70353
70354
70355
70356
70357
70358
70359
70360
70361
70362
70363
70364
70365
70366
70367
70368
70369
70370
70371
70372
70373
70374
70375
70376
70377
70378
70379
70380
70381
70382
70383
70384
70385
70386
70387
70388
70389
70390
70391
70392
70393
70394
70395
70396
70397
70398
70399
70400
70401
70402
70403
70404
70405
70406
70407
70408
70409
70410
70411
70412
70413
70414
70415
70416
70417
70418
70419
70420
70421
70422
70423
70424
70425
70426
70427
70428
70429
70430
70431
70432
70433
70434
70435
70436
70437
70438
70439
70440
70441
70442
70443
70444
70445
70446
70447
70448
70449
70450
70451
70452
70453
70454
70455
70456
70457
70458
70459
70460
70461
70462
70463
70464
70465
70466
70467
70468
70469
70470
70471
70472
70473
70474
70475
70476
70477
70478
70479
70480
70481
70482
70483
70484
70485
70486
70487
70488
70489
70490
70491
70492
70493
70494
70495
70496
70497
70498
70499
70500
70501
70502
70503
70504
70505
70506
70507
70508
70509
70510
70511
70512
70513
70514
70515
70516
70517
70518
70519
70520
70521
70522
70523
70524
70525
70526
70527
70528
70529
70530
70531
70532
70533
70534
70535
70536
70537
70538
70539
70540
70541
70542
70543
70544
70545
70546
70547
70548
70549
70550
70551
70552
70553
70554
70555
70556
70557
70558
70559
70560
70561
70562
70563
70564
70565
70566
70567
70568
70569
70570
70571
70572
70573
70574
70575
70576
70577
70578
70579
70580
70581
70582
70583
70584
70585
70586
70587
70588
70589
70590
70591
70592
70593
70594
70595
70596
70597
70598
70599
70600
70601
70602
70603
70604
70605
70606
70607
70608
70609
70610
70611
70612
70613
70614
70615
70616
70617
70618
70619
70620
70621
70622
70623
70624
70625
70626
70627
70628
70629
70630
70631
70632
70633
70634
70635
70636
70637
70638
70639
70640
70641
70642
70643
70644
70645
70646
70647
70648
70649
70650
70651
70652
70653
70654
70655
70656
70657
70658
70659
70660
70661
70662
70663
70664
70665
70666
70667
70668
70669
70670
70671
70672
70673
70674
70675
70676
70677
70678
70679
70680
70681
70682
70683
70684
70685
70686
70687
70688
70689
70690
70691
70692
70693
70694
70695
70696
70697
70698
70699
70700
70701
70702
70703
70704
70705
70706
70707
70708
70709
70710
70711
70712
70713
70714
70715
70716
70717
70718
70719
70720
70721
70722
70723
70724
70725
70726
70727
70728
70729
70730
70731
70732
70733
70734
70735
70736
70737
70738
70739
70740
70741
70742
70743
70744
70745
70746
70747
70748
70749
70750
70751
70752
70753
70754
70755
70756
70757
70758
70759
70760
70761
70762
70763
70764
70765
70766
70767
70768
70769
70770
70771
70772
70773
70774
70775
70776
70777
70778
70779
70780
70781
70782
70783
70784
70785
70786
70787
70788
70789
70790
70791
70792
70793
70794
70795
70796
70797
70798
70799
70800
70801
70802
70803
70804
70805
70806
70807
70808
70809
70810
70811
70812
70813
70814
70815
70816
70817
70818
70819
70820
70821
70822
70823
70824
70825
70826
70827
70828
70829
70830
70831
70832
70833
70834
70835
70836
70837
70838
70839
70840
70841
70842
70843
70844
70845
70846
70847
70848
70849
70850
70851
70852
70853
70854
70855
70856
70857
70858
70859
70860
70861
70862
70863
70864
70865
70866
70867
70868
70869
70870
70871
70872
70873
70874
70875
70876
70877
70878
70879
70880
70881
70882
70883
70884
70885
70886
70887
70888
70889
70890
70891
70892
70893
70894
70895
70896
70897
70898
70899
70900
70901
70902
70903
70904
70905
70906
70907
70908
70909
70910
70911
70912
70913
70914
70915
70916
70917
70918
70919
70920
70921
70922
70923
70924
70925
70926
70927
70928
70929
70930
70931
70932
70933
70934
70935
70936
70937
70938
70939
70940
70941
70942
70943
70944
70945
70946
70947
70948
70949
70950
70951
70952
70953
70954
70955
70956
70957
70958
70959
70960
70961
70962
70963
70964
70965
70966
70967
70968
70969
70970
70971
70972
70973
70974
70975
70976
70977
70978
70979
70980
70981
70982
70983
70984
70985
70986
70987
70988
70989
70990
70991
70992
70993
70994
70995
70996
70997
70998
70999
71000
71001
71002
71003
71004
71005
71006
71007
71008
71009
71010
71011
71012
71013
71014
71015
71016
71017
71018
71019
71020
71021
71022
71023
71024
71025
71026
71027
71028
71029
71030
71031
71032
71033
71034
71035
71036
71037
71038
71039
71040
71041
71042
71043
71044
71045
71046
71047
71048
71049
71050
71051
71052
71053
71054
71055
71056
71057
71058
71059
71060
71061
71062
71063
71064
71065
71066
71067
71068
71069
71070
71071
71072
71073
71074
71075
71076
71077
71078
71079
71080
71081
71082
71083
71084
71085
71086
71087
71088
71089
71090
71091
71092
71093
71094
71095
71096
71097
71098
71099
71100
71101
71102
71103
71104
71105
71106
71107
71108
71109
71110
71111
71112
71113
71114
71115
71116
71117
71118
71119
71120
71121
71122
71123
71124
71125
71126
71127
71128
71129
71130
71131
71132
71133
71134
71135
71136
71137
71138
71139
71140
71141
71142
71143
71144
71145
71146
71147
71148
71149
71150
71151
71152
71153
71154
71155
71156
71157
71158
71159
71160
71161
71162
71163
71164
71165
71166
71167
71168
71169
71170
71171
71172
71173
71174
71175
71176
71177
71178
71179
71180
71181
71182
71183
71184
71185
71186
71187
71188
71189
71190
71191
71192
71193
71194
71195
71196
71197
71198
71199
71200
71201
71202
71203
71204
71205
71206
71207
71208
71209
71210
71211
71212
71213
71214
71215
71216
71217
71218
71219
71220
71221
71222
71223
71224
71225
71226
71227
71228
71229
71230
71231
71232
71233
71234
71235
71236
71237
71238
71239
71240
71241
71242
71243
71244
71245
71246
71247
71248
71249
71250
71251
71252
71253
71254
71255
71256
71257
71258
71259
71260
71261
71262
71263
71264
71265
71266
71267
71268
71269
71270
71271
71272
71273
71274
71275
71276
71277
71278
71279
71280
71281
71282
71283
71284
71285
71286
71287
71288
71289
71290
71291
71292
71293
71294
71295
71296
71297
71298
71299
71300
71301
71302
71303
71304
71305
71306
71307
71308
71309
71310
71311
71312
71313
71314
71315
71316
71317
71318
71319
71320
71321
71322
71323
71324
71325
71326
71327
71328
71329
71330
71331
71332
71333
71334
71335
71336
71337
71338
71339
71340
71341
71342
71343
71344
71345
71346
71347
71348
71349
71350
71351
71352
71353
71354
71355
71356
71357
71358
71359
71360
71361
71362
71363
71364
71365
71366
71367
71368
71369
71370
71371
71372
71373
71374
71375
71376
71377
71378
71379
71380
71381
71382
71383
71384
71385
71386
71387
71388
71389
71390
71391
71392
71393
71394
71395
71396
71397
71398
71399
71400
71401
71402
71403
71404
71405
71406
71407
71408
71409
71410
71411
71412
71413
71414
71415
71416
71417
71418
71419
71420
71421
71422
71423
71424
71425
71426
71427
71428
71429
71430
71431
71432
71433
71434
71435
71436
71437
71438
71439
71440
71441
71442
71443
71444
71445
71446
71447
71448
71449
71450
71451
71452
71453
71454
71455
71456
71457
71458
71459
71460
71461
71462
71463
71464
71465
71466
71467
71468
71469
71470
71471
71472
71473
71474
71475
71476
71477
71478
71479
71480
71481
71482
71483
71484
71485
71486
71487
71488
71489
71490
71491
71492
71493
71494
71495
71496
71497
71498
71499
71500
71501
71502
71503
71504
71505
71506
71507
71508
71509
71510
71511
71512
71513
71514
71515
71516
71517
71518
71519
71520
71521
71522
71523
71524
71525
71526
71527
71528
71529
71530
71531
71532
71533
71534
71535
71536
71537
71538
71539
71540
71541
71542
71543
71544
71545
71546
71547
71548
71549
71550
71551
71552
71553
71554
71555
71556
71557
71558
71559
71560
71561
71562
71563
71564
71565
71566
71567
71568
71569
71570
71571
71572
71573
71574
71575
71576
71577
71578
71579
71580
71581
71582
71583
71584
71585
71586
71587
71588
71589
71590
71591
71592
71593
71594
71595
71596
71597
71598
71599
71600
71601
71602
71603
71604
71605
71606
71607
71608
71609
71610
71611
71612
71613
71614
71615
71616
71617
71618
71619
71620
71621
71622
71623
71624
71625
71626
71627
71628
71629
71630
71631
71632
71633
71634
71635
71636
71637
71638
71639
71640
71641
71642
71643
71644
71645
71646
71647
71648
71649
71650
71651
71652
71653
71654
71655
71656
71657
71658
71659
71660
71661
71662
71663
71664
71665
71666
71667
71668
71669
71670
71671
71672
71673
71674
71675
71676
71677
71678
71679
71680
71681
71682
71683
71684
71685
71686
71687
71688
71689
71690
71691
71692
71693
71694
71695
71696
71697
71698
71699
71700
71701
71702
71703
71704
71705
71706
71707
71708
71709
71710
71711
71712
71713
71714
71715
71716
71717
71718
71719
71720
71721
71722
71723
71724
71725
71726
71727
71728
71729
71730
71731
71732
71733
71734
71735
71736
71737
71738
71739
71740
71741
71742
71743
71744
71745
71746
71747
71748
71749
71750
71751
71752
71753
71754
71755
71756
71757
71758
71759
71760
71761
71762
71763
71764
71765
71766
71767
71768
71769
71770
71771
71772
71773
71774
71775
71776
71777
71778
71779
71780
71781
71782
71783
71784
71785
71786
71787
71788
71789
71790
71791
71792
71793
71794
71795
71796
71797
71798
71799
71800
71801
71802
71803
71804
71805
71806
71807
71808
71809
71810
71811
71812
71813
71814
71815
71816
71817
71818
71819
71820
71821
71822
71823
71824
71825
71826
71827
71828
71829
71830
71831
71832
71833
71834
71835
71836
71837
71838
71839
71840
71841
71842
71843
71844
71845
71846
71847
71848
71849
71850
71851
71852
71853
71854
71855
71856
71857
71858
71859
71860
71861
71862
71863
71864
71865
71866
71867
71868
71869
71870
71871
71872
71873
71874
71875
71876
71877
71878
71879
71880
71881
71882
71883
71884
71885
71886
71887
71888
71889
71890
71891
71892
71893
71894
71895
71896
71897
71898
71899
71900
71901
71902
71903
71904
71905
71906
71907
71908
71909
71910
71911
71912
71913
71914
71915
71916
71917
71918
71919
71920
71921
71922
71923
71924
71925
71926
71927
71928
71929
71930
71931
71932
71933
71934
71935
71936
71937
71938
71939
71940
71941
71942
71943
71944
71945
71946
71947
71948
71949
71950
71951
71952
71953
71954
71955
71956
71957
71958
71959
71960
71961
71962
71963
71964
71965
71966
71967
71968
71969
71970
71971
71972
71973
71974
71975
71976
71977
71978
71979
71980
71981
71982
71983
71984
71985
71986
71987
71988
71989
71990
71991
71992
71993
71994
71995
71996
71997
71998
71999
72000
72001
72002
72003
72004
72005
72006
72007
72008
72009
72010
72011
72012
72013
72014
72015
72016
72017
72018
72019
72020
72021
72022
72023
72024
72025
72026
72027
72028
72029
72030
72031
72032
72033
72034
72035
72036
72037
72038
72039
72040
72041
72042
72043
72044
72045
72046
72047
72048
72049
72050
72051
72052
72053
72054
72055
72056
72057
72058
72059
72060
72061
72062
72063
72064
72065
72066
72067
72068
72069
72070
72071
72072
72073
72074
72075
72076
72077
72078
72079
72080
72081
72082
72083
72084
72085
72086
72087
72088
72089
72090
72091
72092
72093
72094
72095
72096
72097
72098
72099
72100
72101
72102
72103
72104
72105
72106
72107
72108
72109
72110
72111
72112
72113
72114
72115
72116
72117
72118
72119
72120
72121
72122
72123
72124
72125
72126
72127
72128
72129
72130
72131
72132
72133
72134
72135
72136
72137
72138
72139
72140
72141
72142
72143
72144
72145
72146
72147
72148
72149
72150
72151
72152
72153
72154
72155
72156
72157
72158
72159
72160
72161
72162
72163
72164
72165
72166
72167
72168
72169
72170
72171
72172
72173
72174
72175
72176
72177
72178
72179
72180
72181
72182
72183
72184
72185
72186
72187
72188
72189
72190
72191
72192
72193
72194
72195
72196
72197
72198
72199
72200
72201
72202
72203
72204
72205
72206
72207
72208
72209
72210
72211
72212
72213
72214
72215
72216
72217
72218
72219
72220
72221
72222
72223
72224
72225
72226
72227
72228
72229
72230
72231
72232
72233
72234
72235
72236
72237
72238
72239
72240
72241
72242
72243
72244
72245
72246
72247
72248
72249
72250
72251
72252
72253
72254
72255
72256
72257
72258
72259
72260
72261
72262
72263
72264
72265
72266
72267
72268
72269
72270
72271
72272
72273
72274
72275
72276
72277
72278
72279
72280
72281
72282
72283
72284
72285
72286
72287
72288
72289
72290
72291
72292
72293
72294
72295
72296
72297
72298
72299
72300
72301
72302
72303
72304
72305
72306
72307
72308
72309
72310
72311
72312
72313
72314
72315
72316
72317
72318
72319
72320
72321
72322
72323
72324
72325
72326
72327
72328
72329
72330
72331
72332
72333
72334
72335
72336
72337
72338
72339
72340
72341
72342
72343
72344
72345
72346
72347
72348
72349
72350
72351
72352
72353
72354
72355
72356
72357
72358
72359
72360
72361
72362
72363
72364
72365
72366
72367
72368
72369
72370
72371
72372
72373
72374
72375
72376
72377
72378
72379
72380
72381
72382
72383
72384
72385
72386
72387
72388
72389
72390
72391
72392
72393
72394
72395
72396
72397
72398
72399
72400
72401
72402
72403
72404
72405
72406
72407
72408
72409
72410
72411
72412
72413
72414
72415
72416
72417
72418
72419
72420
72421
72422
72423
72424
72425
72426
72427
72428
72429
72430
72431
72432
72433
72434
72435
72436
72437
72438
72439
72440
72441
72442
72443
72444
72445
72446
72447
72448
72449
72450
72451
72452
72453
72454
72455
72456
72457
72458
72459
72460
72461
72462
72463
72464
72465
72466
72467
72468
72469
72470
72471
72472
72473
72474
72475
72476
72477
72478
72479
72480
72481
72482
72483
72484
72485
72486
72487
72488
72489
72490
72491
72492
72493
72494
72495
72496
72497
72498
72499
72500
72501
72502
72503
72504
72505
72506
72507
72508
72509
72510
72511
72512
72513
72514
72515
72516
72517
72518
72519
72520
72521
72522
72523
72524
72525
72526
72527
72528
72529
72530
72531
72532
72533
72534
72535
72536
72537
72538
72539
72540
72541
72542
72543
72544
72545
72546
72547
72548
72549
72550
72551
72552
72553
72554
72555
72556
72557
72558
72559
72560
72561
72562
72563
72564
72565
72566
72567
72568
72569
72570
72571
72572
72573
72574
72575
72576
72577
72578
72579
72580
72581
72582
72583
72584
72585
72586
72587
72588
72589
72590
72591
72592
72593
72594
72595
72596
72597
72598
72599
72600
72601
72602
72603
72604
72605
72606
72607
72608
72609
72610
72611
72612
72613
72614
72615
72616
72617
72618
72619
72620
72621
72622
72623
72624
72625
72626
72627
72628
72629
72630
72631
72632
72633
72634
72635
72636
72637
72638
72639
72640
72641
72642
72643
72644
72645
72646
72647
72648
72649
72650
72651
72652
72653
72654
72655
72656
72657
72658
72659
72660
72661
72662
72663
72664
72665
72666
72667
72668
72669
72670
72671
72672
72673
72674
72675
72676
72677
72678
72679
72680
72681
72682
72683
72684
72685
72686
72687
72688
72689
72690
72691
72692
72693
72694
72695
72696
72697
72698
72699
72700
72701
72702
72703
72704
72705
72706
72707
72708
72709
72710
72711
72712
72713
72714
72715
72716
72717
72718
72719
72720
72721
72722
72723
72724
72725
72726
72727
72728
72729
72730
72731
72732
72733
72734
72735
72736
72737
72738
72739
72740
72741
72742
72743
72744
72745
72746
72747
72748
72749
72750
72751
72752
72753
72754
72755
72756
72757
72758
72759
72760
72761
72762
72763
72764
72765
72766
72767
72768
72769
72770
72771
72772
72773
72774
72775
72776
72777
72778
72779
72780
72781
72782
72783
72784
72785
72786
72787
72788
72789
72790
72791
72792
72793
72794
72795
72796
72797
72798
72799
72800
72801
72802
72803
72804
72805
72806
72807
72808
72809
72810
72811
72812
72813
72814
72815
72816
72817
72818
72819
72820
72821
72822
72823
72824
72825
72826
72827
72828
72829
72830
72831
72832
72833
72834
72835
72836
72837
72838
72839
72840
72841
72842
72843
72844
72845
72846
72847
72848
72849
72850
72851
72852
72853
72854
72855
72856
72857
72858
72859
72860
72861
72862
72863
72864
72865
72866
72867
72868
72869
72870
72871
72872
72873
72874
72875
72876
72877
72878
72879
72880
72881
72882
72883
72884
72885
72886
72887
72888
72889
72890
72891
72892
72893
72894
72895
72896
72897
72898
72899
72900
72901
72902
72903
72904
72905
72906
72907
72908
72909
72910
72911
72912
72913
72914
72915
72916
72917
72918
72919
72920
72921
72922
72923
72924
72925
72926
72927
72928
72929
72930
72931
72932
72933
72934
72935
72936
72937
72938
72939
72940
72941
72942
72943
72944
72945
72946
72947
72948
72949
72950
72951
72952
72953
72954
72955
72956
72957
72958
72959
72960
72961
72962
72963
72964
72965
72966
72967
72968
72969
72970
72971
72972
72973
72974
72975
72976
72977
72978
72979
72980
72981
72982
72983
72984
72985
72986
72987
72988
72989
72990
72991
72992
72993
72994
72995
72996
72997
72998
72999
73000
73001
73002
73003
73004
73005
73006
73007
73008
73009
73010
73011
73012
73013
73014
73015
73016
73017
73018
73019
73020
73021
73022
73023
73024
73025
73026
73027
73028
73029
73030
73031
73032
73033
73034
73035
73036
73037
73038
73039
73040
73041
73042
73043
73044
73045
73046
73047
73048
73049
73050
73051
73052
73053
73054
73055
73056
73057
73058
73059
73060
73061
73062
73063
73064
73065
73066
73067
73068
73069
73070
73071
73072
73073
73074
73075
73076
73077
73078
73079
73080
73081
73082
73083
73084
73085
73086
73087
73088
73089
73090
73091
73092
73093
73094
73095
73096
73097
73098
73099
73100
73101
73102
73103
73104
73105
73106
73107
73108
73109
73110
73111
73112
73113
73114
73115
73116
73117
73118
73119
73120
73121
73122
73123
73124
73125
73126
73127
73128
73129
73130
73131
73132
73133
73134
73135
73136
73137
73138
73139
73140
73141
73142
73143
73144
73145
73146
73147
73148
73149
73150
73151
73152
73153
73154
73155
73156
73157
73158
73159
73160
73161
73162
73163
73164
73165
73166
73167
73168
73169
73170
73171
73172
73173
73174
73175
73176
73177
73178
73179
73180
73181
73182
73183
73184
73185
73186
73187
73188
73189
73190
73191
73192
73193
73194
73195
73196
73197
73198
73199
73200
73201
73202
73203
73204
73205
73206
73207
73208
73209
73210
73211
73212
73213
73214
73215
73216
73217
73218
73219
73220
73221
73222
73223
73224
73225
73226
73227
73228
73229
73230
73231
73232
73233
73234
73235
73236
73237
73238
73239
73240
73241
73242
73243
73244
73245
73246
73247
73248
73249
73250
73251
73252
73253
73254
73255
73256
73257
73258
73259
73260
73261
73262
73263
73264
73265
73266
73267
73268
73269
73270
73271
73272
73273
73274
73275
73276
73277
73278
73279
73280
73281
73282
73283
73284
73285
73286
73287
73288
73289
73290
73291
73292
73293
73294
73295
73296
73297
73298
73299
73300
73301
73302
73303
73304
73305
73306
73307
73308
73309
73310
73311
73312
73313
73314
73315
73316
73317
73318
73319
73320
73321
73322
73323
73324
73325
73326
73327
73328
73329
73330
73331
73332
73333
73334
73335
73336
73337
73338
73339
73340
73341
73342
73343
73344
73345
73346
73347
73348
73349
73350
73351
73352
73353
73354
73355
73356
73357
73358
73359
73360
73361
73362
73363
73364
73365
73366
73367
73368
73369
73370
73371
73372
73373
73374
73375
73376
73377
73378
73379
73380
73381
73382
73383
73384
73385
73386
73387
73388
73389
73390
73391
73392
73393
73394
73395
73396
73397
73398
73399
73400
73401
73402
73403
73404
73405
73406
73407
73408
73409
73410
73411
73412
73413
73414
73415
73416
73417
73418
73419
73420
73421
73422
73423
73424
73425
73426
73427
73428
73429
73430
73431
73432
73433
73434
73435
73436
73437
73438
73439
73440
73441
73442
73443
73444
73445
73446
73447
73448
73449
73450
73451
73452
73453
73454
73455
73456
73457
73458
73459
73460
73461
73462
73463
73464
73465
73466
73467
73468
73469
73470
73471
73472
73473
73474
73475
73476
73477
73478
73479
73480
73481
73482
73483
73484
73485
73486
73487
73488
73489
73490
73491
73492
73493
73494
73495
73496
73497
73498
73499
73500
73501
73502
73503
73504
73505
73506
73507
73508
73509
73510
73511
73512
73513
73514
73515
73516
73517
73518
73519
73520
73521
73522
73523
73524
73525
73526
73527
73528
73529
73530
73531
73532
73533
73534
73535
73536
73537
73538
73539
73540
73541
73542
73543
73544
73545
73546
73547
73548
73549
73550
73551
73552
73553
73554
73555
73556
73557
73558
73559
73560
73561
73562
73563
73564
73565
73566
73567
73568
73569
73570
73571
73572
73573
73574
73575
73576
73577
73578
73579
73580
73581
73582
73583
73584
73585
73586
73587
73588
73589
73590
73591
73592
73593
73594
73595
73596
73597
73598
73599
73600
73601
73602
73603
73604
73605
73606
73607
73608
73609
73610
73611
73612
73613
73614
73615
73616
73617
73618
73619
73620
73621
73622
73623
73624
73625
73626
73627
73628
73629
73630
73631
73632
73633
73634
73635
73636
73637
73638
73639
73640
73641
73642
73643
73644
73645
73646
73647
73648
73649
73650
73651
73652
73653
73654
73655
73656
73657
73658
73659
73660
73661
73662
73663
73664
73665
73666
73667
73668
73669
73670
73671
73672
73673
73674
73675
73676
73677
73678
73679
73680
73681
73682
73683
73684
73685
73686
73687
73688
73689
73690
73691
73692
73693
73694
73695
73696
73697
73698
73699
73700
73701
73702
73703
73704
73705
73706
73707
73708
73709
73710
73711
73712
73713
73714
73715
73716
73717
73718
73719
73720
73721
73722
73723
73724
73725
73726
73727
73728
73729
73730
73731
73732
73733
73734
73735
73736
73737
73738
73739
73740
73741
73742
73743
73744
73745
73746
73747
73748
73749
73750
73751
73752
73753
73754
73755
73756
73757
73758
73759
73760
73761
73762
73763
73764
73765
73766
73767
73768
73769
73770
73771
73772
73773
73774
73775
73776
73777
73778
73779
73780
73781
73782
73783
73784
73785
73786
73787
73788
73789
73790
73791
73792
73793
73794
73795
73796
73797
73798
73799
73800
73801
73802
73803
73804
73805
73806
73807
73808
73809
73810
73811
73812
73813
73814
73815
73816
73817
73818
73819
73820
73821
73822
73823
73824
73825
73826
73827
73828
73829
73830
73831
73832
73833
73834
73835
73836
73837
73838
73839
73840
73841
73842
73843
73844
73845
73846
73847
73848
73849
73850
73851
73852
73853
73854
73855
73856
73857
73858
73859
73860
73861
73862
73863
73864
73865
73866
73867
73868
73869
73870
73871
73872
73873
73874
73875
73876
73877
73878
73879
73880
73881
73882
73883
73884
73885
73886
73887
73888
73889
73890
73891
73892
73893
73894
73895
73896
73897
73898
73899
73900
73901
73902
73903
73904
73905
73906
73907
73908
73909
73910
73911
73912
73913
73914
73915
73916
73917
73918
73919
73920
73921
73922
73923
73924
73925
73926
73927
73928
73929
73930
73931
73932
73933
73934
73935
73936
73937
73938
73939
73940
73941
73942
73943
73944
73945
73946
73947
73948
73949
73950
73951
73952
73953
73954
73955
73956
73957
73958
73959
73960
73961
73962
73963
73964
73965
73966
73967
73968
73969
73970
73971
73972
73973
73974
73975
73976
73977
73978
73979
73980
73981
73982
73983
73984
73985
73986
73987
73988
73989
73990
73991
73992
73993
73994
73995
73996
73997
73998
73999
74000
74001
74002
74003
74004
74005
74006
74007
74008
74009
74010
74011
74012
74013
74014
74015
74016
74017
74018
74019
74020
74021
74022
74023
74024
74025
74026
74027
74028
74029
74030
74031
74032
74033
74034
74035
74036
74037
74038
74039
74040
74041
74042
74043
74044
74045
74046
74047
74048
74049
74050
74051
74052
74053
74054
74055
74056
74057
74058
74059
74060
74061
74062
74063
74064
74065
74066
74067
74068
74069
74070
74071
74072
74073
74074
74075
74076
74077
74078
74079
74080
74081
74082
74083
74084
74085
74086
74087
74088
74089
74090
74091
74092
74093
74094
74095
74096
74097
74098
74099
74100
74101
74102
74103
74104
74105
74106
74107
74108
74109
74110
74111
74112
74113
74114
74115
74116
74117
74118
74119
74120
74121
74122
74123
74124
74125
74126
74127
74128
74129
74130
74131
74132
74133
74134
74135
74136
74137
74138
74139
74140
74141
74142
74143
74144
74145
74146
74147
74148
74149
74150
74151
74152
74153
74154
74155
74156
74157
74158
74159
74160
74161
74162
74163
74164
74165
74166
74167
74168
74169
74170
74171
74172
74173
74174
74175
74176
74177
74178
74179
74180
74181
74182
74183
74184
74185
74186
74187
74188
74189
74190
74191
74192
74193
74194
74195
74196
74197
74198
74199
74200
74201
74202
74203
74204
74205
74206
74207
74208
74209
74210
74211
74212
74213
74214
74215
74216
74217
74218
74219
74220
74221
74222
74223
74224
74225
74226
74227
74228
74229
74230
74231
74232
74233
74234
74235
74236
74237
74238
74239
74240
74241
74242
74243
74244
74245
74246
74247
74248
74249
74250
74251
74252
74253
74254
74255
74256
74257
74258
74259
74260
74261
74262
74263
74264
74265
74266
74267
74268
74269
74270
74271
74272
74273
74274
74275
74276
74277
74278
74279
74280
74281
74282
74283
74284
74285
74286
74287
74288
74289
74290
74291
74292
74293
74294
74295
74296
74297
74298
74299
74300
74301
74302
74303
74304
74305
74306
74307
74308
74309
74310
74311
74312
74313
74314
74315
74316
74317
74318
74319
74320
74321
74322
74323
74324
74325
74326
74327
74328
74329
74330
74331
74332
74333
74334
74335
74336
74337
74338
74339
74340
74341
74342
74343
74344
74345
74346
74347
74348
74349
74350
74351
74352
74353
74354
74355
74356
74357
74358
74359
74360
74361
74362
74363
74364
74365
74366
74367
74368
74369
74370
74371
74372
74373
74374
74375
74376
74377
74378
74379
74380
74381
74382
74383
74384
74385
74386
74387
74388
74389
74390
74391
74392
74393
74394
74395
74396
74397
74398
74399
74400
74401
74402
74403
74404
74405
74406
74407
74408
74409
74410
74411
74412
74413
74414
74415
74416
74417
74418
74419
74420
74421
74422
74423
74424
74425
74426
74427
74428
74429
74430
74431
74432
74433
74434
74435
74436
74437
74438
74439
74440
74441
74442
74443
74444
74445
74446
74447
74448
74449
74450
74451
74452
74453
74454
74455
74456
74457
74458
74459
74460
74461
74462
74463
74464
74465
74466
74467
74468
74469
74470
74471
74472
74473
74474
74475
74476
74477
74478
74479
74480
74481
74482
74483
74484
74485
74486
74487
74488
74489
74490
74491
74492
74493
74494
74495
74496
74497
74498
74499
74500
74501
74502
74503
74504
74505
74506
74507
74508
74509
74510
74511
74512
74513
74514
74515
74516
74517
74518
74519
74520
74521
74522
74523
74524
74525
74526
74527
74528
74529
74530
74531
74532
74533
74534
74535
74536
74537
74538
74539
74540
74541
74542
74543
74544
74545
74546
74547
74548
74549
74550
74551
74552
74553
74554
74555
74556
74557
74558
74559
74560
74561
74562
74563
74564
74565
74566
74567
74568
74569
74570
74571
74572
74573
74574
74575
74576
74577
74578
74579
74580
74581
74582
74583
74584
74585
74586
74587
74588
74589
74590
74591
74592
74593
74594
74595
74596
74597
74598
74599
74600
74601
74602
74603
74604
74605
74606
74607
74608
74609
74610
74611
74612
74613
74614
74615
74616
74617
74618
74619
74620
74621
74622
74623
74624
74625
74626
74627
74628
74629
74630
74631
74632
74633
74634
74635
74636
74637
74638
74639
74640
74641
74642
74643
74644
74645
74646
74647
74648
74649
74650
74651
74652
74653
74654
74655
74656
74657
74658
74659
74660
74661
74662
74663
74664
74665
74666
74667
74668
74669
74670
74671
74672
74673
74674
74675
74676
74677
74678
74679
74680
74681
74682
74683
74684
74685
74686
74687
74688
74689
74690
74691
74692
74693
74694
74695
74696
74697
74698
74699
74700
74701
74702
74703
74704
74705
74706
74707
74708
74709
74710
74711
74712
74713
74714
74715
74716
74717
74718
74719
74720
74721
74722
74723
74724
74725
74726
74727
74728
74729
74730
74731
74732
74733
74734
74735
74736
74737
74738
74739
74740
74741
74742
74743
74744
74745
74746
74747
74748
74749
74750
74751
74752
74753
74754
74755
74756
74757
74758
74759
74760
74761
74762
74763
74764
74765
74766
74767
74768
74769
74770
74771
74772
74773
74774
74775
74776
74777
74778
74779
74780
74781
74782
74783
74784
74785
74786
74787
74788
74789
74790
74791
74792
74793
74794
74795
74796
74797
74798
74799
74800
74801
74802
74803
74804
74805
74806
74807
74808
74809
74810
74811
74812
74813
74814
74815
74816
74817
74818
74819
74820
74821
74822
74823
74824
74825
74826
74827
74828
74829
74830
74831
74832
74833
74834
74835
74836
74837
74838
74839
74840
74841
74842
74843
74844
74845
74846
74847
74848
74849
74850
74851
74852
74853
74854
74855
74856
74857
74858
74859
74860
74861
74862
74863
74864
74865
74866
74867
74868
74869
74870
74871
74872
74873
74874
74875
74876
74877
74878
74879
74880
74881
74882
74883
74884
74885
74886
74887
74888
74889
74890
74891
74892
74893
74894
74895
74896
74897
74898
74899
74900
74901
74902
74903
74904
74905
74906
74907
74908
74909
74910
74911
74912
74913
74914
74915
74916
74917
74918
74919
74920
74921
74922
74923
74924
74925
74926
74927
74928
74929
74930
74931
74932
74933
74934
74935
74936
74937
74938
74939
74940
74941
74942
74943
74944
74945
74946
74947
74948
74949
74950
74951
74952
74953
74954
74955
74956
74957
74958
74959
74960
74961
74962
74963
74964
74965
74966
74967
74968
74969
74970
74971
74972
74973
74974
74975
74976
74977
74978
74979
74980
74981
74982
74983
74984
74985
74986
74987
74988
74989
74990
74991
74992
74993
74994
74995
74996
74997
74998
74999
75000
75001
75002
75003
75004
75005
75006
75007
75008
75009
75010
75011
75012
75013
75014
75015
75016
75017
75018
75019
75020
75021
75022
75023
75024
75025
75026
75027
75028
75029
75030
75031
75032
75033
75034
75035
75036
75037
75038
75039
75040
75041
75042
75043
75044
75045
75046
75047
75048
75049
75050
75051
75052
75053
75054
75055
75056
75057
75058
75059
75060
75061
75062
75063
75064
75065
75066
75067
75068
75069
75070
75071
75072
75073
75074
75075
75076
75077
75078
75079
75080
75081
75082
75083
75084
75085
75086
75087
75088
75089
75090
75091
75092
75093
75094
75095
75096
75097
75098
75099
75100
75101
75102
75103
75104
75105
75106
75107
75108
75109
75110
75111
75112
75113
75114
75115
75116
75117
75118
75119
75120
75121
75122
75123
75124
75125
75126
75127
75128
75129
75130
75131
75132
75133
75134
75135
75136
75137
75138
75139
75140
75141
75142
75143
75144
75145
75146
75147
75148
75149
75150
75151
75152
75153
75154
75155
75156
75157
75158
75159
75160
75161
75162
75163
75164
75165
75166
75167
75168
75169
75170
75171
75172
75173
75174
75175
75176
75177
75178
75179
75180
75181
75182
75183
75184
75185
75186
75187
75188
75189
75190
75191
75192
75193
75194
75195
75196
75197
75198
75199
75200
75201
75202
75203
75204
75205
75206
75207
75208
75209
75210
75211
75212
75213
75214
75215
75216
75217
75218
75219
75220
75221
75222
75223
75224
75225
75226
75227
75228
75229
75230
75231
75232
75233
75234
75235
75236
75237
75238
75239
75240
75241
75242
75243
75244
75245
75246
75247
75248
75249
75250
75251
75252
75253
75254
75255
75256
75257
75258
75259
75260
75261
75262
75263
75264
75265
75266
75267
75268
75269
75270
75271
75272
75273
75274
75275
75276
75277
75278
75279
75280
75281
75282
75283
75284
75285
75286
75287
75288
75289
75290
75291
75292
75293
75294
75295
75296
75297
75298
75299
75300
75301
75302
75303
75304
75305
75306
75307
75308
75309
75310
75311
75312
75313
75314
75315
75316
75317
75318
75319
75320
75321
75322
75323
75324
75325
75326
75327
75328
75329
75330
75331
75332
75333
75334
75335
75336
75337
75338
75339
75340
75341
75342
75343
75344
75345
75346
75347
75348
75349
75350
75351
75352
75353
75354
75355
75356
75357
75358
75359
75360
75361
75362
75363
75364
75365
75366
75367
75368
75369
75370
75371
75372
75373
75374
75375
75376
75377
75378
75379
75380
75381
75382
75383
75384
75385
75386
75387
75388
75389
75390
75391
75392
75393
75394
75395
75396
75397
75398
75399
75400
75401
75402
75403
75404
75405
75406
75407
75408
75409
75410
75411
75412
75413
75414
75415
75416
75417
75418
75419
75420
75421
75422
75423
75424
75425
75426
75427
75428
75429
75430
75431
75432
75433
75434
75435
75436
75437
75438
75439
75440
75441
75442
75443
75444
75445
75446
75447
75448
75449
75450
75451
75452
75453
75454
75455
75456
75457
75458
75459
75460
75461
75462
75463
75464
75465
75466
75467
75468
75469
75470
75471
75472
75473
75474
75475
75476
75477
75478
75479
75480
75481
75482
75483
75484
75485
75486
75487
75488
75489
75490
75491
75492
75493
75494
75495
75496
75497
75498
75499
75500
75501
75502
75503
75504
75505
75506
75507
75508
75509
75510
75511
75512
75513
75514
75515
75516
75517
75518
75519
75520
75521
75522
75523
75524
75525
75526
75527
75528
75529
75530
75531
75532
75533
75534
75535
75536
75537
75538
75539
75540
75541
75542
75543
75544
75545
75546
75547
75548
75549
75550
75551
75552
75553
75554
75555
75556
75557
75558
75559
75560
75561
75562
75563
75564
75565
75566
75567
75568
75569
75570
75571
75572
75573
75574
75575
75576
75577
75578
75579
75580
75581
75582
75583
75584
75585
75586
75587
75588
75589
75590
75591
75592
75593
75594
75595
75596
75597
75598
75599
75600
75601
75602
75603
75604
75605
75606
75607
75608
75609
75610
75611
75612
75613
75614
75615
75616
75617
75618
75619
75620
75621
75622
75623
75624
75625
75626
75627
75628
75629
75630
75631
75632
75633
75634
75635
75636
75637
75638
75639
75640
75641
75642
75643
75644
75645
75646
75647
75648
75649
75650
75651
75652
75653
75654
75655
75656
75657
75658
75659
75660
75661
75662
75663
75664
75665
75666
75667
75668
75669
75670
75671
75672
75673
75674
75675
75676
75677
75678
75679
75680
75681
75682
75683
75684
75685
75686
75687
75688
75689
75690
75691
75692
75693
75694
75695
75696
75697
75698
75699
75700
75701
75702
75703
75704
75705
75706
75707
75708
75709
75710
75711
75712
75713
75714
75715
75716
75717
75718
75719
75720
75721
75722
75723
75724
75725
75726
75727
75728
75729
75730
75731
75732
75733
75734
75735
75736
75737
75738
75739
75740
75741
75742
75743
75744
75745
75746
75747
75748
75749
75750
75751
75752
75753
75754
75755
75756
75757
75758
75759
75760
75761
75762
75763
75764
75765
75766
75767
75768
75769
75770
75771
75772
75773
75774
75775
75776
75777
75778
75779
75780
75781
75782
75783
75784
75785
75786
75787
75788
75789
75790
75791
75792
75793
75794
75795
75796
75797
75798
75799
75800
75801
75802
75803
75804
75805
75806
75807
75808
75809
75810
75811
75812
75813
75814
75815
75816
75817
75818
75819
75820
75821
75822
75823
75824
75825
75826
75827
75828
75829
75830
75831
75832
75833
75834
75835
75836
75837
75838
75839
75840
75841
75842
75843
75844
75845
75846
75847
75848
75849
75850
75851
75852
75853
75854
75855
75856
75857
75858
75859
75860
75861
75862
75863
75864
75865
75866
75867
75868
75869
75870
75871
75872
75873
75874
75875
75876
75877
75878
75879
75880
75881
75882
75883
75884
75885
75886
75887
75888
75889
75890
75891
75892
75893
75894
75895
75896
75897
75898
75899
75900
75901
75902
75903
75904
75905
75906
75907
75908
75909
75910
75911
75912
75913
75914
75915
75916
75917
75918
75919
75920
75921
75922
75923
75924
75925
75926
75927
75928
75929
75930
75931
75932
75933
75934
75935
75936
75937
75938
75939
75940
75941
75942
75943
75944
75945
75946
75947
75948
75949
75950
75951
75952
75953
75954
75955
75956
75957
75958
75959
75960
75961
75962
75963
75964
75965
75966
75967
75968
75969
75970
75971
75972
75973
75974
75975
75976
75977
75978
75979
75980
75981
75982
75983
75984
75985
75986
75987
75988
75989
75990
75991
75992
75993
75994
75995
75996
75997
75998
75999
76000
76001
76002
76003
76004
76005
76006
76007
76008
76009
76010
76011
76012
76013
76014
76015
76016
76017
76018
76019
76020
76021
76022
76023
76024
76025
76026
76027
76028
76029
76030
76031
76032
76033
76034
76035
76036
76037
76038
76039
76040
76041
76042
76043
76044
76045
76046
76047
76048
76049
76050
76051
76052
76053
76054
76055
76056
76057
76058
76059
76060
76061
76062
76063
76064
76065
76066
76067
76068
76069
76070
76071
76072
76073
76074
76075
76076
76077
76078
76079
76080
76081
76082
76083
76084
76085
76086
76087
76088
76089
76090
76091
76092
76093
76094
76095
76096
76097
76098
76099
76100
76101
76102
76103
76104
76105
76106
76107
76108
76109
76110
76111
76112
76113
76114
76115
76116
76117
76118
76119
76120
76121
76122
76123
76124
76125
76126
76127
76128
76129
76130
76131
76132
76133
76134
76135
76136
76137
76138
76139
76140
76141
76142
76143
76144
76145
76146
76147
76148
76149
76150
76151
76152
76153
76154
76155
76156
76157
76158
76159
76160
76161
76162
76163
76164
76165
76166
76167
76168
76169
76170
76171
76172
76173
76174
76175
76176
76177
76178
76179
76180
76181
76182
76183
76184
76185
76186
76187
76188
76189
76190
76191
76192
76193
76194
76195
76196
76197
76198
76199
76200
76201
76202
76203
76204
76205
76206
76207
76208
76209
76210
76211
76212
76213
76214
76215
76216
76217
76218
76219
76220
76221
76222
76223
76224
76225
76226
76227
76228
76229
76230
76231
76232
76233
76234
76235
76236
76237
76238
76239
76240
76241
76242
76243
76244
76245
76246
76247
76248
76249
76250
76251
76252
76253
76254
76255
76256
76257
76258
76259
76260
76261
76262
76263
76264
76265
76266
76267
76268
76269
76270
76271
76272
76273
76274
76275
76276
76277
76278
76279
76280
76281
76282
76283
76284
76285
76286
76287
76288
76289
76290
76291
76292
76293
76294
76295
76296
76297
76298
76299
76300
76301
76302
76303
76304
76305
76306
76307
76308
76309
76310
76311
76312
76313
76314
76315
76316
76317
76318
76319
76320
76321
76322
76323
76324
76325
76326
76327
76328
76329
76330
76331
76332
76333
76334
76335
76336
76337
76338
76339
76340
76341
76342
76343
76344
76345
76346
76347
76348
76349
76350
76351
76352
76353
76354
76355
76356
76357
76358
76359
76360
76361
76362
76363
76364
76365
76366
76367
76368
76369
76370
76371
76372
76373
76374
76375
76376
76377
76378
76379
76380
76381
76382
76383
76384
76385
76386
76387
76388
76389
76390
76391
76392
76393
76394
76395
76396
76397
76398
76399
76400
76401
76402
76403
76404
76405
76406
76407
76408
76409
76410
76411
76412
76413
76414
76415
76416
76417
76418
76419
76420
76421
76422
76423
76424
76425
76426
76427
76428
76429
76430
76431
76432
76433
76434
76435
76436
76437
76438
76439
76440
76441
76442
76443
76444
76445
76446
76447
76448
76449
76450
76451
76452
76453
76454
76455
76456
76457
76458
76459
76460
76461
76462
76463
76464
76465
76466
76467
76468
76469
76470
76471
76472
76473
76474
76475
76476
76477
76478
76479
76480
76481
76482
76483
76484
76485
76486
76487
76488
76489
76490
76491
76492
76493
76494
76495
76496
76497
76498
76499
76500
76501
76502
76503
76504
76505
76506
76507
76508
76509
76510
76511
76512
76513
76514
76515
76516
76517
76518
76519
76520
76521
76522
76523
76524
76525
76526
76527
76528
76529
76530
76531
76532
76533
76534
76535
76536
76537
76538
76539
76540
76541
76542
76543
76544
76545
76546
76547
76548
76549
76550
76551
76552
76553
76554
76555
76556
76557
76558
76559
76560
76561
76562
76563
76564
76565
76566
76567
76568
76569
76570
76571
76572
76573
76574
76575
76576
76577
76578
76579
76580
76581
76582
76583
76584
76585
76586
76587
76588
76589
76590
76591
76592
76593
76594
76595
76596
76597
76598
76599
76600
76601
76602
76603
76604
76605
76606
76607
76608
76609
76610
76611
76612
76613
76614
76615
76616
76617
76618
76619
76620
76621
76622
76623
76624
76625
76626
76627
76628
76629
76630
76631
76632
76633
76634
76635
76636
76637
76638
76639
76640
76641
76642
76643
76644
76645
76646
76647
76648
76649
76650
76651
76652
76653
76654
76655
76656
76657
76658
76659
76660
76661
76662
76663
76664
76665
76666
76667
76668
76669
76670
76671
76672
76673
76674
76675
76676
76677
76678
76679
76680
76681
76682
76683
76684
76685
76686
76687
76688
76689
76690
76691
76692
76693
76694
76695
76696
76697
76698
76699
76700
76701
76702
76703
76704
76705
76706
76707
76708
76709
76710
76711
76712
76713
76714
76715
76716
76717
76718
76719
76720
76721
76722
76723
76724
76725
76726
76727
76728
76729
76730
76731
76732
76733
76734
76735
76736
76737
76738
76739
76740
76741
76742
76743
76744
76745
76746
76747
76748
76749
76750
76751
76752
76753
76754
76755
76756
76757
76758
76759
76760
76761
76762
76763
76764
76765
76766
76767
76768
76769
76770
76771
76772
76773
76774
76775
76776
76777
76778
76779
76780
76781
76782
76783
76784
76785
76786
76787
76788
76789
76790
76791
76792
76793
76794
76795
76796
76797
76798
76799
76800
76801
76802
76803
76804
76805
76806
76807
76808
76809
76810
76811
76812
76813
76814
76815
76816
76817
76818
76819
76820
76821
76822
76823
76824
76825
76826
76827
76828
76829
76830
76831
76832
76833
76834
76835
76836
76837
76838
76839
76840
76841
76842
76843
76844
76845
76846
76847
76848
76849
76850
76851
76852
76853
76854
76855
76856
76857
76858
76859
76860
76861
76862
76863
76864
76865
76866
76867
76868
76869
76870
76871
76872
76873
76874
76875
76876
76877
76878
76879
76880
76881
76882
76883
76884
76885
76886
76887
76888
76889
76890
76891
76892
76893
76894
76895
76896
76897
76898
76899
76900
76901
76902
76903
76904
76905
76906
76907
76908
76909
76910
76911
76912
76913
76914
76915
76916
76917
76918
76919
76920
76921
76922
76923
76924
76925
76926
76927
76928
76929
76930
76931
76932
76933
76934
76935
76936
76937
76938
76939
76940
76941
76942
76943
76944
76945
76946
76947
76948
76949
76950
76951
76952
76953
76954
76955
76956
76957
76958
76959
76960
76961
76962
76963
76964
76965
76966
76967
76968
76969
76970
76971
76972
76973
76974
76975
76976
76977
76978
76979
76980
76981
76982
76983
76984
76985
76986
76987
76988
76989
76990
76991
76992
76993
76994
76995
76996
76997
76998
76999
77000
77001
77002
77003
77004
77005
77006
77007
77008
77009
77010
77011
77012
77013
77014
77015
77016
77017
77018
77019
77020
77021
77022
77023
77024
77025
77026
77027
77028
77029
77030
77031
77032
77033
77034
77035
77036
77037
77038
77039
77040
77041
77042
77043
77044
77045
77046
77047
77048
77049
77050
77051
77052
77053
77054
77055
77056
77057
77058
77059
77060
77061
77062
77063
77064
77065
77066
77067
77068
77069
77070
77071
77072
77073
77074
77075
77076
77077
77078
77079
77080
77081
77082
77083
77084
77085
77086
77087
77088
77089
77090
77091
77092
77093
77094
77095
77096
77097
77098
77099
77100
77101
77102
77103
77104
77105
77106
77107
77108
77109
77110
77111
77112
77113
77114
77115
77116
77117
77118
77119
77120
77121
77122
77123
77124
77125
77126
77127
77128
77129
77130
77131
77132
77133
77134
77135
77136
77137
77138
77139
77140
77141
77142
77143
77144
77145
77146
77147
77148
77149
77150
77151
77152
77153
77154
77155
77156
77157
77158
77159
77160
77161
77162
77163
77164
77165
77166
77167
77168
77169
77170
77171
77172
77173
77174
77175
77176
77177
77178
77179
77180
77181
77182
77183
77184
77185
77186
77187
77188
77189
77190
77191
77192
77193
77194
77195
77196
77197
77198
77199
77200
77201
77202
77203
77204
77205
77206
77207
77208
77209
77210
77211
77212
77213
77214
77215
77216
77217
77218
77219
77220
77221
77222
77223
77224
77225
77226
77227
77228
77229
77230
77231
77232
77233
77234
77235
77236
77237
77238
77239
77240
77241
77242
77243
77244
77245
77246
77247
77248
77249
77250
77251
77252
77253
77254
77255
77256
77257
77258
77259
77260
77261
77262
77263
77264
77265
77266
77267
77268
77269
77270
77271
77272
77273
77274
77275
77276
77277
77278
77279
77280
77281
77282
77283
77284
77285
77286
77287
77288
77289
77290
77291
77292
77293
77294
77295
77296
77297
77298
77299
77300
77301
77302
77303
77304
77305
77306
77307
77308
77309
77310
77311
77312
77313
77314
77315
77316
77317
77318
77319
77320
77321
77322
77323
77324
77325
77326
77327
77328
77329
77330
77331
77332
77333
77334
77335
77336
77337
77338
77339
77340
77341
77342
77343
77344
77345
77346
77347
77348
77349
77350
77351
77352
77353
77354
77355
77356
77357
77358
77359
77360
77361
77362
77363
77364
77365
77366
77367
77368
77369
77370
77371
77372
77373
77374
77375
77376
77377
77378
77379
77380
77381
77382
77383
77384
77385
77386
77387
77388
77389
77390
77391
77392
77393
77394
77395
77396
77397
77398
77399
77400
77401
77402
77403
77404
77405
77406
77407
77408
77409
77410
77411
77412
77413
77414
77415
77416
77417
77418
77419
77420
77421
77422
77423
77424
77425
77426
77427
77428
77429
77430
77431
77432
77433
77434
77435
77436
77437
77438
77439
77440
77441
77442
77443
77444
77445
77446
77447
77448
77449
77450
77451
77452
77453
77454
77455
77456
77457
77458
77459
77460
77461
77462
77463
77464
77465
77466
77467
77468
77469
77470
77471
77472
77473
77474
77475
77476
77477
77478
77479
77480
77481
77482
77483
77484
77485
77486
77487
77488
77489
77490
77491
77492
77493
77494
77495
77496
77497
77498
77499
77500
77501
77502
77503
77504
77505
77506
77507
77508
77509
77510
77511
77512
77513
77514
77515
77516
77517
77518
77519
77520
77521
77522
77523
77524
77525
77526
77527
77528
77529
77530
77531
77532
77533
77534
77535
77536
77537
77538
77539
77540
77541
77542
77543
77544
77545
77546
77547
77548
77549
77550
77551
77552
77553
77554
77555
77556
77557
77558
77559
77560
77561
77562
77563
77564
77565
77566
77567
77568
77569
77570
77571
77572
77573
77574
77575
77576
77577
77578
77579
77580
77581
77582
77583
77584
77585
77586
77587
77588
77589
77590
77591
77592
77593
77594
77595
77596
77597
77598
77599
77600
77601
77602
77603
77604
77605
77606
77607
77608
77609
77610
77611
77612
77613
77614
77615
77616
77617
77618
77619
77620
77621
77622
77623
77624
77625
77626
77627
77628
77629
77630
77631
77632
77633
77634
77635
77636
77637
77638
77639
77640
77641
77642
77643
77644
77645
77646
77647
77648
77649
77650
77651
77652
77653
77654
77655
77656
77657
77658
77659
77660
77661
77662
77663
77664
77665
77666
77667
77668
77669
77670
77671
77672
77673
77674
77675
77676
77677
77678
77679
77680
77681
77682
77683
77684
77685
77686
77687
77688
77689
77690
77691
77692
77693
77694
77695
77696
77697
77698
77699
77700
77701
77702
77703
77704
77705
77706
77707
77708
77709
77710
77711
77712
77713
77714
77715
77716
77717
77718
77719
77720
77721
77722
77723
77724
77725
77726
77727
77728
77729
77730
77731
77732
77733
77734
77735
77736
77737
77738
77739
77740
77741
77742
77743
77744
77745
77746
77747
77748
77749
77750
77751
77752
77753
77754
77755
77756
77757
77758
77759
77760
77761
77762
77763
77764
77765
77766
77767
77768
77769
77770
77771
77772
77773
77774
77775
77776
77777
77778
77779
77780
77781
77782
77783
77784
77785
77786
77787
77788
77789
77790
77791
77792
77793
77794
77795
77796
77797
77798
77799
77800
77801
77802
77803
77804
77805
77806
77807
77808
77809
77810
77811
77812
77813
77814
77815
77816
77817
77818
77819
77820
77821
77822
77823
77824
77825
77826
77827
77828
77829
77830
77831
77832
77833
77834
77835
77836
77837
77838
77839
77840
77841
77842
77843
77844
77845
77846
77847
77848
77849
77850
77851
77852
77853
77854
77855
77856
77857
77858
77859
77860
77861
77862
77863
77864
77865
77866
77867
77868
77869
77870
77871
77872
77873
77874
77875
77876
77877
77878
77879
77880
77881
77882
77883
77884
77885
77886
77887
77888
77889
77890
77891
77892
77893
77894
77895
77896
77897
77898
77899
77900
77901
77902
77903
77904
77905
77906
77907
77908
77909
77910
77911
77912
77913
77914
77915
77916
77917
77918
77919
77920
77921
77922
77923
77924
77925
77926
77927
77928
77929
77930
77931
77932
77933
77934
77935
77936
77937
77938
77939
77940
77941
77942
77943
77944
77945
77946
77947
77948
77949
77950
77951
77952
77953
77954
77955
77956
77957
77958
77959
77960
77961
77962
77963
77964
77965
77966
77967
77968
77969
77970
77971
77972
77973
77974
77975
77976
77977
77978
77979
77980
77981
77982
77983
77984
77985
77986
77987
77988
77989
77990
77991
77992
77993
77994
77995
77996
77997
77998
77999
78000
78001
78002
78003
78004
78005
78006
78007
78008
78009
78010
78011
78012
78013
78014
78015
78016
78017
78018
78019
78020
78021
78022
78023
78024
78025
78026
78027
78028
78029
78030
78031
78032
78033
78034
78035
78036
78037
78038
78039
78040
78041
78042
78043
78044
78045
78046
78047
78048
78049
78050
78051
78052
78053
78054
78055
78056
78057
78058
78059
78060
78061
78062
78063
78064
78065
78066
78067
78068
78069
78070
78071
78072
78073
78074
78075
78076
78077
78078
78079
78080
78081
78082
78083
78084
78085
78086
78087
78088
78089
78090
78091
78092
78093
78094
78095
78096
78097
78098
78099
78100
78101
78102
78103
78104
78105
78106
78107
78108
78109
78110
78111
78112
78113
78114
78115
78116
78117
78118
78119
78120
78121
78122
78123
78124
78125
78126
78127
78128
78129
78130
78131
78132
78133
78134
78135
78136
78137
78138
78139
78140
78141
78142
78143
78144
78145
78146
78147
78148
78149
78150
78151
78152
78153
78154
78155
78156
78157
78158
78159
78160
78161
78162
78163
78164
78165
78166
78167
78168
78169
78170
78171
78172
78173
78174
78175
78176
78177
78178
78179
78180
78181
78182
78183
78184
78185
78186
78187
78188
78189
78190
78191
78192
78193
78194
78195
78196
78197
78198
78199
78200
78201
78202
78203
78204
78205
78206
78207
78208
78209
78210
78211
78212
78213
78214
78215
78216
78217
78218
78219
78220
78221
78222
78223
78224
78225
78226
78227
78228
78229
78230
78231
78232
78233
78234
78235
78236
78237
78238
78239
78240
78241
78242
78243
78244
78245
78246
78247
78248
78249
78250
78251
78252
78253
78254
78255
78256
78257
78258
78259
78260
78261
78262
78263
78264
78265
78266
78267
78268
78269
78270
78271
78272
78273
78274
78275
78276
78277
78278
78279
78280
78281
78282
78283
78284
78285
78286
78287
78288
78289
78290
78291
78292
78293
78294
78295
78296
78297
78298
78299
78300
78301
78302
78303
78304
78305
78306
78307
78308
78309
78310
78311
78312
78313
78314
78315
78316
78317
78318
78319
78320
78321
78322
78323
78324
78325
78326
78327
78328
78329
78330
78331
78332
78333
78334
78335
78336
78337
78338
78339
78340
78341
78342
78343
78344
78345
78346
78347
78348
78349
78350
78351
78352
78353
78354
78355
78356
78357
78358
78359
78360
78361
78362
78363
78364
78365
78366
78367
78368
78369
78370
78371
78372
78373
78374
78375
78376
78377
78378
78379
78380
78381
78382
78383
78384
78385
78386
78387
78388
78389
78390
78391
78392
78393
78394
78395
78396
78397
78398
78399
78400
78401
78402
78403
78404
78405
78406
78407
78408
78409
78410
78411
78412
78413
78414
78415
78416
78417
78418
78419
78420
78421
78422
78423
78424
78425
78426
78427
78428
78429
78430
78431
78432
78433
78434
78435
78436
78437
78438
78439
78440
78441
78442
78443
78444
78445
78446
78447
78448
78449
78450
78451
78452
78453
78454
78455
78456
78457
78458
78459
78460
78461
78462
78463
78464
78465
78466
78467
78468
78469
78470
78471
78472
78473
78474
78475
78476
78477
78478
78479
78480
78481
78482
78483
78484
78485
78486
78487
78488
78489
78490
78491
78492
78493
78494
78495
78496
78497
78498
78499
78500
78501
78502
78503
78504
78505
78506
78507
78508
78509
78510
78511
78512
78513
78514
78515
78516
78517
78518
78519
78520
78521
78522
78523
78524
78525
78526
78527
78528
78529
78530
78531
78532
78533
78534
78535
78536
78537
78538
78539
78540
78541
78542
78543
78544
78545
78546
78547
78548
78549
78550
78551
78552
78553
78554
78555
78556
78557
78558
78559
78560
78561
78562
78563
78564
78565
78566
78567
78568
78569
78570
78571
78572
78573
78574
78575
78576
78577
78578
78579
78580
78581
78582
78583
78584
78585
78586
78587
78588
78589
78590
78591
78592
78593
78594
78595
78596
78597
78598
78599
78600
78601
78602
78603
78604
78605
78606
78607
78608
78609
78610
78611
78612
78613
78614
78615
78616
78617
78618
78619
78620
78621
78622
78623
78624
78625
78626
78627
78628
78629
78630
78631
78632
78633
78634
78635
78636
78637
78638
78639
78640
78641
78642
78643
78644
78645
78646
78647
78648
78649
78650
78651
78652
78653
78654
78655
78656
78657
78658
78659
78660
78661
78662
78663
78664
78665
78666
78667
78668
78669
78670
78671
78672
78673
78674
78675
78676
78677
78678
78679
78680
78681
78682
78683
78684
78685
78686
78687
78688
78689
78690
78691
78692
78693
78694
78695
78696
78697
78698
78699
78700
78701
78702
78703
78704
78705
78706
78707
78708
78709
78710
78711
78712
78713
78714
78715
78716
78717
78718
78719
78720
78721
78722
78723
78724
78725
78726
78727
78728
78729
78730
78731
78732
78733
78734
78735
78736
78737
78738
78739
78740
78741
78742
78743
78744
78745
78746
78747
78748
78749
78750
78751
78752
78753
78754
78755
78756
78757
78758
78759
78760
78761
78762
78763
78764
78765
78766
78767
78768
78769
78770
78771
78772
78773
78774
78775
78776
78777
78778
78779
78780
78781
78782
78783
78784
78785
78786
78787
78788
78789
78790
78791
78792
78793
78794
78795
78796
78797
78798
78799
78800
78801
78802
78803
78804
78805
78806
78807
78808
78809
78810
78811
78812
78813
78814
78815
78816
78817
78818
78819
78820
78821
78822
78823
78824
78825
78826
78827
78828
78829
78830
78831
78832
78833
78834
78835
78836
78837
78838
78839
78840
78841
78842
78843
78844
78845
78846
78847
78848
78849
78850
78851
78852
78853
78854
78855
78856
78857
78858
78859
78860
78861
78862
78863
78864
78865
78866
78867
78868
78869
78870
78871
78872
78873
78874
78875
78876
78877
78878
78879
78880
78881
78882
78883
78884
78885
78886
78887
78888
78889
78890
78891
78892
78893
78894
78895
78896
78897
78898
78899
78900
78901
78902
78903
78904
78905
78906
78907
78908
78909
78910
78911
78912
78913
78914
78915
78916
78917
78918
78919
78920
78921
78922
78923
78924
78925
78926
78927
78928
78929
78930
78931
78932
78933
78934
78935
78936
78937
78938
78939
78940
78941
78942
78943
78944
78945
78946
78947
78948
78949
78950
78951
78952
78953
78954
78955
78956
78957
78958
78959
78960
78961
78962
78963
78964
78965
78966
78967
78968
78969
78970
78971
78972
78973
78974
78975
78976
78977
78978
78979
78980
78981
78982
78983
78984
78985
78986
78987
78988
78989
78990
78991
78992
78993
78994
78995
78996
78997
78998
78999
79000
79001
79002
79003
79004
79005
79006
79007
79008
79009
79010
79011
79012
79013
79014
79015
79016
79017
79018
79019
79020
79021
79022
79023
79024
79025
79026
79027
79028
79029
79030
79031
79032
79033
79034
79035
79036
79037
79038
79039
79040
79041
79042
79043
79044
79045
79046
79047
79048
79049
79050
79051
79052
79053
79054
79055
79056
79057
79058
79059
79060
79061
79062
79063
79064
79065
79066
79067
79068
79069
79070
79071
79072
79073
79074
79075
79076
79077
79078
79079
79080
79081
79082
79083
79084
79085
79086
79087
79088
79089
79090
79091
79092
79093
79094
79095
79096
79097
79098
79099
79100
79101
79102
79103
79104
79105
79106
79107
79108
79109
79110
79111
79112
79113
79114
79115
79116
79117
79118
79119
79120
79121
79122
79123
79124
79125
79126
79127
79128
79129
79130
79131
79132
79133
79134
79135
79136
79137
79138
79139
79140
79141
79142
79143
79144
79145
79146
79147
79148
79149
79150
79151
79152
79153
79154
79155
79156
79157
79158
79159
79160
79161
79162
79163
79164
79165
79166
79167
79168
79169
79170
79171
79172
79173
79174
79175
79176
79177
79178
79179
79180
79181
79182
79183
79184
79185
79186
79187
79188
79189
79190
79191
79192
79193
79194
79195
79196
79197
79198
79199
79200
79201
79202
79203
79204
79205
79206
79207
79208
79209
79210
79211
79212
79213
79214
79215
79216
79217
79218
79219
79220
79221
79222
79223
79224
79225
79226
79227
79228
79229
79230
79231
79232
79233
79234
79235
79236
79237
79238
79239
79240
79241
79242
79243
79244
79245
79246
79247
79248
79249
79250
79251
79252
79253
79254
79255
79256
79257
79258
79259
79260
79261
79262
79263
79264
79265
79266
79267
79268
79269
79270
79271
79272
79273
79274
79275
79276
79277
79278
79279
79280
79281
79282
79283
79284
79285
79286
79287
79288
79289
79290
79291
79292
79293
79294
79295
79296
79297
79298
79299
79300
79301
79302
79303
79304
79305
79306
79307
79308
79309
79310
79311
79312
79313
79314
79315
79316
79317
79318
79319
79320
79321
79322
79323
79324
79325
79326
79327
79328
79329
79330
79331
79332
79333
79334
79335
79336
79337
79338
79339
79340
79341
79342
79343
79344
79345
79346
79347
79348
79349
79350
79351
79352
79353
79354
79355
79356
79357
79358
79359
79360
79361
79362
79363
79364
79365
79366
79367
79368
79369
79370
79371
79372
79373
79374
79375
79376
79377
79378
79379
79380
79381
79382
79383
79384
79385
79386
79387
79388
79389
79390
79391
79392
79393
79394
79395
79396
79397
79398
79399
79400
79401
79402
79403
79404
79405
79406
79407
79408
79409
79410
79411
79412
79413
79414
79415
79416
79417
79418
79419
79420
79421
79422
79423
79424
79425
79426
79427
79428
79429
79430
79431
79432
79433
79434
79435
79436
79437
79438
79439
79440
79441
79442
79443
79444
79445
79446
79447
79448
79449
79450
79451
79452
79453
79454
79455
79456
79457
79458
79459
79460
79461
79462
79463
79464
79465
79466
79467
79468
79469
79470
79471
79472
79473
79474
79475
79476
79477
79478
79479
79480
79481
79482
79483
79484
79485
79486
79487
79488
79489
79490
79491
79492
79493
79494
79495
79496
79497
79498
79499
79500
79501
79502
79503
79504
79505
79506
79507
79508
79509
79510
79511
79512
79513
79514
79515
79516
79517
79518
79519
79520
79521
79522
79523
79524
79525
79526
79527
79528
79529
79530
79531
79532
79533
79534
79535
79536
79537
79538
79539
79540
79541
79542
79543
79544
79545
79546
79547
79548
79549
79550
79551
79552
79553
79554
79555
79556
79557
79558
79559
79560
79561
79562
79563
79564
79565
79566
79567
79568
79569
79570
79571
79572
79573
79574
79575
79576
79577
79578
79579
79580
79581
79582
79583
79584
79585
79586
79587
79588
79589
79590
79591
79592
79593
79594
79595
79596
79597
79598
79599
79600
79601
79602
79603
79604
79605
79606
79607
79608
79609
79610
79611
79612
79613
79614
79615
79616
79617
79618
79619
79620
79621
79622
79623
79624
79625
79626
79627
79628
79629
79630
79631
79632
79633
79634
79635
79636
79637
79638
79639
79640
79641
79642
79643
79644
79645
79646
79647
79648
79649
79650
79651
79652
79653
79654
79655
79656
79657
79658
79659
79660
79661
79662
79663
79664
79665
79666
79667
79668
79669
79670
79671
79672
79673
79674
79675
79676
79677
79678
79679
79680
79681
79682
79683
79684
79685
79686
79687
79688
79689
79690
79691
79692
79693
79694
79695
79696
79697
79698
79699
79700
79701
79702
79703
79704
79705
79706
79707
79708
79709
79710
79711
79712
79713
79714
79715
79716
79717
79718
79719
79720
79721
79722
79723
79724
79725
79726
79727
79728
79729
79730
79731
79732
79733
79734
79735
79736
79737
79738
79739
79740
79741
79742
79743
79744
79745
79746
79747
79748
79749
79750
79751
79752
79753
79754
79755
79756
79757
79758
79759
79760
79761
79762
79763
79764
79765
79766
79767
79768
79769
79770
79771
79772
79773
79774
79775
79776
79777
79778
79779
79780
79781
79782
79783
79784
79785
79786
79787
79788
79789
79790
79791
79792
79793
79794
79795
79796
79797
79798
79799
79800
79801
79802
79803
79804
79805
79806
79807
79808
79809
79810
79811
79812
79813
79814
79815
79816
79817
79818
79819
79820
79821
79822
79823
79824
79825
79826
79827
79828
79829
79830
79831
79832
79833
79834
79835
79836
79837
79838
79839
79840
79841
79842
79843
79844
79845
79846
79847
79848
79849
79850
79851
79852
79853
79854
79855
79856
79857
79858
79859
79860
79861
79862
79863
79864
79865
79866
79867
79868
79869
79870
79871
79872
79873
79874
79875
79876
79877
79878
79879
79880
79881
79882
79883
79884
79885
79886
79887
79888
79889
79890
79891
79892
79893
79894
79895
79896
79897
79898
79899
79900
79901
79902
79903
79904
79905
79906
79907
79908
79909
79910
79911
79912
79913
79914
79915
79916
79917
79918
79919
79920
79921
79922
79923
79924
79925
79926
79927
79928
79929
79930
79931
79932
79933
79934
79935
79936
79937
79938
79939
79940
79941
79942
79943
79944
79945
79946
79947
79948
79949
79950
79951
79952
79953
79954
79955
79956
79957
79958
79959
79960
79961
79962
79963
79964
79965
79966
79967
79968
79969
79970
79971
79972
79973
79974
79975
79976
79977
79978
79979
79980
79981
79982
79983
79984
79985
79986
79987
79988
79989
79990
79991
79992
79993
79994
79995
79996
79997
79998
79999
80000
80001
80002
80003
80004
80005
80006
80007
80008
80009
80010
80011
80012
80013
80014
80015
80016
80017
80018
80019
80020
80021
80022
80023
80024
80025
80026
80027
80028
80029
80030
80031
80032
80033
80034
80035
80036
80037
80038
80039
80040
80041
80042
80043
80044
80045
80046
80047
80048
80049
80050
80051
80052
80053
80054
80055
80056
80057
80058
80059
80060
80061
80062
80063
80064
80065
80066
80067
80068
80069
80070
80071
80072
80073
80074
80075
80076
80077
80078
80079
80080
80081
80082
80083
80084
80085
80086
80087
80088
80089
80090
80091
80092
80093
80094
80095
80096
80097
80098
80099
80100
80101
80102
80103
80104
80105
80106
80107
80108
80109
80110
80111
80112
80113
80114
80115
80116
80117
80118
80119
80120
80121
80122
80123
80124
80125
80126
80127
80128
80129
80130
80131
80132
80133
80134
80135
80136
80137
80138
80139
80140
80141
80142
80143
80144
80145
80146
80147
80148
80149
80150
80151
80152
80153
80154
80155
80156
80157
80158
80159
80160
80161
80162
80163
80164
80165
80166
80167
80168
80169
80170
80171
80172
80173
80174
80175
80176
80177
80178
80179
80180
80181
80182
80183
80184
80185
80186
80187
80188
80189
80190
80191
80192
80193
80194
80195
80196
80197
80198
80199
80200
80201
80202
80203
80204
80205
80206
80207
80208
80209
80210
80211
80212
80213
80214
80215
80216
80217
80218
80219
80220
80221
80222
80223
80224
80225
80226
80227
80228
80229
80230
80231
80232
80233
80234
80235
80236
80237
80238
80239
80240
80241
80242
80243
80244
80245
80246
80247
80248
80249
80250
80251
80252
80253
80254
80255
80256
80257
80258
80259
80260
80261
80262
80263
80264
80265
80266
80267
80268
80269
80270
80271
80272
80273
80274
80275
80276
80277
80278
80279
80280
80281
80282
80283
80284
80285
80286
80287
80288
80289
80290
80291
80292
80293
80294
80295
80296
80297
80298
80299
80300
80301
80302
80303
80304
80305
80306
80307
80308
80309
80310
80311
80312
80313
80314
80315
80316
80317
80318
80319
80320
80321
80322
80323
80324
80325
80326
80327
80328
80329
80330
80331
80332
80333
80334
80335
80336
80337
80338
80339
80340
80341
80342
80343
80344
80345
80346
80347
80348
80349
80350
80351
80352
80353
80354
80355
80356
80357
80358
80359
80360
80361
80362
80363
80364
80365
80366
80367
80368
80369
80370
80371
80372
80373
80374
80375
80376
80377
80378
80379
80380
80381
80382
80383
80384
80385
80386
80387
80388
80389
80390
80391
80392
80393
80394
80395
80396
80397
80398
80399
80400
80401
80402
80403
80404
80405
80406
80407
80408
80409
80410
80411
80412
80413
80414
80415
80416
80417
80418
80419
80420
80421
80422
80423
80424
80425
80426
80427
80428
80429
80430
80431
80432
80433
80434
80435
80436
80437
80438
80439
80440
80441
80442
80443
80444
80445
80446
80447
80448
80449
80450
80451
80452
80453
80454
80455
80456
80457
80458
80459
80460
80461
80462
80463
80464
80465
80466
80467
80468
80469
80470
80471
80472
80473
80474
80475
80476
80477
80478
80479
80480
80481
80482
80483
80484
80485
80486
80487
80488
80489
80490
80491
80492
80493
80494
80495
80496
80497
80498
80499
80500
80501
80502
80503
80504
80505
80506
80507
80508
80509
80510
80511
80512
80513
80514
80515
80516
80517
80518
80519
80520
80521
80522
80523
80524
80525
80526
80527
80528
80529
80530
80531
80532
80533
80534
80535
80536
80537
80538
80539
80540
80541
80542
80543
80544
80545
80546
80547
80548
80549
80550
80551
80552
80553
80554
80555
80556
80557
80558
80559
80560
80561
80562
80563
80564
80565
80566
80567
80568
80569
80570
80571
80572
80573
80574
80575
80576
80577
80578
80579
80580
80581
80582
80583
80584
80585
80586
80587
80588
80589
80590
80591
80592
80593
80594
80595
80596
80597
80598
80599
80600
80601
80602
80603
80604
80605
80606
80607
80608
80609
80610
80611
80612
80613
80614
80615
80616
80617
80618
80619
80620
80621
80622
80623
80624
80625
80626
80627
80628
80629
80630
80631
80632
80633
80634
80635
80636
80637
80638
80639
80640
80641
80642
80643
80644
80645
80646
80647
80648
80649
80650
80651
80652
80653
80654
80655
80656
80657
80658
80659
80660
80661
80662
80663
80664
80665
80666
80667
80668
80669
80670
80671
80672
80673
80674
80675
80676
80677
80678
80679
80680
80681
80682
80683
80684
80685
80686
80687
80688
80689
80690
80691
80692
80693
80694
80695
80696
80697
80698
80699
80700
80701
80702
80703
80704
80705
80706
80707
80708
80709
80710
80711
80712
80713
80714
80715
80716
80717
80718
80719
80720
80721
80722
80723
80724
80725
80726
80727
80728
80729
80730
80731
80732
80733
80734
80735
80736
80737
80738
80739
80740
80741
80742
80743
80744
80745
80746
80747
80748
80749
80750
80751
80752
80753
80754
80755
80756
80757
80758
80759
80760
80761
80762
80763
80764
80765
80766
80767
80768
80769
80770
80771
80772
80773
80774
80775
80776
80777
80778
80779
80780
80781
80782
80783
80784
80785
80786
80787
80788
80789
80790
80791
80792
80793
80794
80795
80796
80797
80798
80799
80800
80801
80802
80803
80804
80805
80806
80807
80808
80809
80810
80811
80812
80813
80814
80815
80816
80817
80818
80819
80820
80821
80822
80823
80824
80825
80826
80827
80828
80829
80830
80831
80832
80833
80834
80835
80836
80837
80838
80839
80840
80841
80842
80843
80844
80845
80846
80847
80848
80849
80850
80851
80852
80853
80854
80855
80856
80857
80858
80859
80860
80861
80862
80863
80864
80865
80866
80867
80868
80869
80870
80871
80872
80873
80874
80875
80876
80877
80878
80879
80880
80881
80882
80883
80884
80885
80886
80887
80888
80889
80890
80891
80892
80893
80894
80895
80896
80897
80898
80899
80900
80901
80902
80903
80904
80905
80906
80907
80908
80909
80910
80911
80912
80913
80914
80915
80916
80917
80918
80919
80920
80921
80922
80923
80924
80925
80926
80927
80928
80929
80930
80931
80932
80933
80934
80935
80936
80937
80938
80939
80940
80941
80942
80943
80944
80945
80946
80947
80948
80949
80950
80951
80952
80953
80954
80955
80956
80957
80958
80959
80960
80961
80962
80963
80964
80965
80966
80967
80968
80969
80970
80971
80972
80973
80974
80975
80976
80977
80978
80979
80980
80981
80982
80983
80984
80985
80986
80987
80988
80989
80990
80991
80992
80993
80994
80995
80996
80997
80998
80999
81000
81001
81002
81003
81004
81005
81006
81007
81008
81009
81010
81011
81012
81013
81014
81015
81016
81017
81018
81019
81020
81021
81022
81023
81024
81025
81026
81027
81028
81029
81030
81031
81032
81033
81034
81035
81036
81037
81038
81039
81040
81041
81042
81043
81044
81045
81046
81047
81048
81049
81050
81051
81052
81053
81054
81055
81056
81057
81058
81059
81060
81061
81062
81063
81064
81065
81066
81067
81068
81069
81070
81071
81072
81073
81074
81075
81076
81077
81078
81079
81080
81081
81082
81083
81084
81085
81086
81087
81088
81089
81090
81091
81092
81093
81094
81095
81096
81097
81098
81099
81100
81101
81102
81103
81104
81105
81106
81107
81108
81109
81110
81111
81112
81113
81114
81115
81116
81117
81118
81119
81120
81121
81122
81123
81124
81125
81126
81127
81128
81129
81130
81131
81132
81133
81134
81135
81136
81137
81138
81139
81140
81141
81142
81143
81144
81145
81146
81147
81148
81149
81150
81151
81152
81153
81154
81155
81156
81157
81158
81159
81160
81161
81162
81163
81164
81165
81166
81167
81168
81169
81170
81171
81172
81173
81174
81175
81176
81177
81178
81179
81180
81181
81182
81183
81184
81185
81186
81187
81188
81189
81190
81191
81192
81193
81194
81195
81196
81197
81198
81199
81200
81201
81202
81203
81204
81205
81206
81207
81208
81209
81210
81211
81212
81213
81214
81215
81216
81217
81218
81219
81220
81221
81222
81223
81224
81225
81226
81227
81228
81229
81230
81231
81232
81233
81234
81235
81236
81237
81238
81239
81240
81241
81242
81243
81244
81245
81246
81247
81248
81249
81250
81251
81252
81253
81254
81255
81256
81257
81258
81259
81260
81261
81262
81263
81264
81265
81266
81267
81268
81269
81270
81271
81272
81273
81274
81275
81276
81277
81278
81279
81280
81281
81282
81283
81284
81285
81286
81287
81288
81289
81290
81291
81292
81293
81294
81295
81296
81297
81298
81299
81300
81301
81302
81303
81304
81305
81306
81307
81308
81309
81310
81311
81312
81313
81314
81315
81316
81317
81318
81319
81320
81321
81322
81323
81324
81325
81326
81327
81328
81329
81330
81331
81332
81333
81334
81335
81336
81337
81338
81339
81340
81341
81342
81343
81344
81345
81346
81347
81348
81349
81350
81351
81352
81353
81354
81355
81356
81357
81358
81359
81360
81361
81362
81363
81364
81365
81366
81367
81368
81369
81370
81371
81372
81373
81374
81375
81376
81377
81378
81379
81380
81381
81382
81383
81384
81385
81386
81387
81388
81389
81390
81391
81392
81393
81394
81395
81396
81397
81398
81399
81400
81401
81402
81403
81404
81405
81406
81407
81408
81409
81410
81411
81412
81413
81414
81415
81416
81417
81418
81419
81420
81421
81422
81423
81424
81425
81426
81427
81428
81429
81430
81431
81432
81433
81434
81435
81436
81437
81438
81439
81440
81441
81442
81443
81444
81445
81446
81447
81448
81449
81450
81451
81452
81453
81454
81455
81456
81457
81458
81459
81460
81461
81462
81463
81464
81465
81466
81467
81468
81469
81470
81471
81472
81473
81474
81475
81476
81477
81478
81479
81480
81481
81482
81483
81484
81485
81486
81487
81488
81489
81490
81491
81492
81493
81494
81495
81496
81497
81498
81499
81500
81501
81502
81503
81504
81505
81506
81507
81508
81509
81510
81511
81512
81513
81514
81515
81516
81517
81518
81519
81520
81521
81522
81523
81524
81525
81526
81527
81528
81529
81530
81531
81532
81533
81534
81535
81536
81537
81538
81539
81540
81541
81542
81543
81544
81545
81546
81547
81548
81549
81550
81551
81552
81553
81554
81555
81556
81557
81558
81559
81560
81561
81562
81563
81564
81565
81566
81567
81568
81569
81570
81571
81572
81573
81574
81575
81576
81577
81578
81579
81580
81581
81582
81583
81584
81585
81586
81587
81588
81589
81590
81591
81592
81593
81594
81595
81596
81597
81598
81599
81600
81601
81602
81603
81604
81605
81606
81607
81608
81609
81610
81611
81612
81613
81614
81615
81616
81617
81618
81619
81620
81621
81622
81623
81624
81625
81626
81627
81628
81629
81630
81631
81632
81633
81634
81635
81636
81637
81638
81639
81640
81641
81642
81643
81644
81645
81646
81647
81648
81649
81650
81651
81652
81653
81654
81655
81656
81657
81658
81659
81660
81661
81662
81663
81664
81665
81666
81667
81668
81669
81670
81671
81672
81673
81674
81675
81676
81677
81678
81679
81680
81681
81682
81683
81684
81685
81686
81687
81688
81689
81690
81691
81692
81693
81694
81695
81696
81697
81698
81699
81700
81701
81702
81703
81704
81705
81706
81707
81708
81709
81710
81711
81712
81713
81714
81715
81716
81717
81718
81719
81720
81721
81722
81723
81724
81725
81726
81727
81728
81729
81730
81731
81732
81733
81734
81735
81736
81737
81738
81739
81740
81741
81742
81743
81744
81745
81746
81747
81748
81749
81750
81751
81752
81753
81754
81755
81756
81757
81758
81759
81760
81761
81762
81763
81764
81765
81766
81767
81768
81769
81770
81771
81772
81773
81774
81775
81776
81777
81778
81779
81780
81781
81782
81783
81784
81785
81786
81787
81788
81789
81790
81791
81792
81793
81794
81795
81796
81797
81798
81799
81800
81801
81802
81803
81804
81805
81806
81807
81808
81809
81810
81811
81812
81813
81814
81815
81816
81817
81818
81819
81820
81821
81822
81823
81824
81825
81826
81827
81828
81829
81830
81831
81832
81833
81834
81835
81836
81837
81838
81839
81840
81841
81842
81843
81844
81845
81846
81847
81848
81849
81850
81851
81852
81853
81854
81855
81856
81857
81858
81859
81860
81861
81862
81863
81864
81865
81866
81867
81868
81869
81870
81871
81872
81873
81874
81875
81876
81877
81878
81879
81880
81881
81882
81883
81884
81885
81886
81887
81888
81889
81890
81891
81892
81893
81894
81895
81896
81897
81898
81899
81900
81901
81902
81903
81904
81905
81906
81907
81908
81909
81910
81911
81912
81913
81914
81915
81916
81917
81918
81919
81920
81921
81922
81923
81924
81925
81926
81927
81928
81929
81930
81931
81932
81933
81934
81935
81936
81937
81938
81939
81940
81941
81942
81943
81944
81945
81946
81947
81948
81949
81950
81951
81952
81953
81954
81955
81956
81957
81958
81959
81960
81961
81962
81963
81964
81965
81966
81967
81968
81969
81970
81971
81972
81973
81974
81975
81976
81977
81978
81979
81980
81981
81982
81983
81984
81985
81986
81987
81988
81989
81990
81991
81992
81993
81994
81995
81996
81997
81998
81999
82000
82001
82002
82003
82004
82005
82006
82007
82008
82009
82010
82011
82012
82013
82014
82015
82016
82017
82018
82019
82020
82021
82022
82023
82024
82025
82026
82027
82028
82029
82030
82031
82032
82033
82034
82035
82036
82037
82038
82039
82040
82041
82042
82043
82044
82045
82046
82047
82048
82049
82050
82051
82052
82053
82054
82055
82056
82057
82058
82059
82060
82061
82062
82063
82064
82065
82066
82067
82068
82069
82070
82071
82072
82073
82074
82075
82076
82077
82078
82079
82080
82081
82082
82083
82084
82085
82086
82087
82088
82089
82090
82091
82092
82093
82094
82095
82096
82097
82098
82099
82100
82101
82102
82103
82104
82105
82106
82107
82108
82109
82110
82111
82112
82113
82114
82115
82116
82117
82118
82119
82120
82121
82122
82123
82124
82125
82126
82127
82128
82129
82130
82131
82132
82133
82134
82135
82136
82137
82138
82139
82140
82141
82142
82143
82144
82145
82146
82147
82148
82149
82150
82151
82152
82153
82154
82155
82156
82157
82158
82159
82160
82161
82162
82163
82164
82165
82166
82167
82168
82169
82170
82171
82172
82173
82174
82175
82176
82177
82178
82179
82180
82181
82182
82183
82184
82185
82186
82187
82188
82189
82190
82191
82192
82193
82194
82195
82196
82197
82198
82199
82200
82201
82202
82203
82204
82205
82206
82207
82208
82209
82210
82211
82212
82213
82214
82215
82216
82217
82218
82219
82220
82221
82222
82223
82224
82225
82226
82227
82228
82229
82230
82231
82232
82233
82234
82235
82236
82237
82238
82239
82240
82241
82242
82243
82244
82245
82246
82247
82248
82249
82250
82251
82252
82253
82254
82255
82256
82257
82258
82259
82260
82261
82262
82263
82264
82265
82266
82267
82268
82269
82270
82271
82272
82273
82274
82275
82276
82277
82278
82279
82280
82281
82282
82283
82284
82285
82286
82287
82288
82289
82290
82291
82292
82293
82294
82295
82296
82297
82298
82299
82300
82301
82302
82303
82304
82305
82306
82307
82308
82309
82310
82311
82312
82313
82314
82315
82316
82317
82318
82319
82320
82321
82322
82323
82324
82325
82326
82327
82328
82329
82330
82331
82332
82333
82334
82335
82336
82337
82338
82339
82340
82341
82342
82343
82344
82345
82346
82347
82348
82349
82350
82351
82352
82353
82354
82355
82356
82357
82358
82359
82360
82361
82362
82363
82364
82365
82366
82367
82368
82369
82370
82371
82372
82373
82374
82375
82376
82377
82378
82379
82380
82381
82382
82383
82384
82385
82386
82387
82388
82389
82390
82391
82392
82393
82394
82395
82396
82397
82398
82399
82400
82401
82402
82403
82404
82405
82406
82407
82408
82409
82410
82411
82412
82413
82414
82415
82416
82417
82418
82419
82420
82421
82422
82423
82424
82425
82426
82427
82428
82429
82430
82431
82432
82433
82434
82435
82436
82437
82438
82439
82440
82441
82442
82443
82444
82445
82446
82447
82448
82449
82450
82451
82452
82453
82454
82455
82456
82457
82458
82459
82460
82461
82462
82463
82464
82465
82466
82467
82468
82469
82470
82471
82472
82473
82474
82475
82476
82477
82478
82479
82480
82481
82482
82483
82484
82485
82486
82487
82488
82489
82490
82491
82492
82493
82494
82495
82496
82497
82498
82499
82500
82501
82502
82503
82504
82505
82506
82507
82508
82509
82510
82511
82512
82513
82514
82515
82516
82517
82518
82519
82520
82521
82522
82523
82524
82525
82526
82527
82528
82529
82530
82531
82532
82533
82534
82535
82536
82537
82538
82539
82540
82541
82542
82543
82544
82545
82546
82547
82548
82549
82550
82551
82552
82553
82554
82555
82556
82557
82558
82559
82560
82561
82562
82563
82564
82565
82566
82567
82568
82569
82570
82571
82572
82573
82574
82575
82576
82577
82578
82579
82580
82581
82582
82583
82584
82585
82586
82587
82588
82589
82590
82591
82592
82593
82594
82595
82596
82597
82598
82599
82600
82601
82602
82603
82604
82605
82606
82607
82608
82609
82610
82611
82612
82613
82614
82615
82616
82617
82618
82619
82620
82621
82622
82623
82624
82625
82626
82627
82628
82629
82630
82631
82632
82633
82634
82635
82636
82637
82638
82639
82640
82641
82642
82643
82644
82645
82646
82647
82648
82649
82650
82651
82652
82653
82654
82655
82656
82657
82658
82659
82660
82661
82662
82663
82664
82665
82666
82667
82668
82669
82670
82671
82672
82673
82674
82675
82676
82677
82678
82679
82680
82681
82682
82683
82684
82685
82686
82687
82688
82689
82690
82691
82692
82693
82694
82695
82696
82697
82698
82699
82700
82701
82702
82703
82704
82705
82706
82707
82708
82709
82710
82711
82712
82713
82714
82715
82716
82717
82718
82719
82720
82721
82722
82723
82724
82725
82726
82727
82728
82729
82730
82731
82732
82733
82734
82735
82736
82737
82738
82739
82740
82741
82742
82743
82744
82745
82746
82747
82748
82749
82750
82751
82752
82753
82754
82755
82756
82757
82758
82759
82760
82761
82762
82763
82764
82765
82766
82767
82768
82769
82770
82771
82772
82773
82774
82775
82776
82777
82778
82779
82780
82781
82782
82783
82784
82785
82786
82787
82788
82789
82790
82791
82792
82793
82794
82795
82796
82797
82798
82799
82800
82801
82802
82803
82804
82805
82806
82807
82808
82809
82810
82811
82812
82813
82814
82815
82816
82817
82818
82819
82820
82821
82822
82823
82824
82825
82826
82827
82828
82829
82830
82831
82832
82833
82834
82835
82836
82837
82838
82839
82840
82841
82842
82843
82844
82845
82846
82847
82848
82849
82850
82851
82852
82853
82854
82855
82856
82857
82858
82859
82860
82861
82862
82863
82864
82865
82866
82867
82868
82869
82870
82871
82872
82873
82874
82875
82876
82877
82878
82879
82880
82881
82882
82883
82884
82885
82886
82887
82888
82889
82890
82891
82892
82893
82894
82895
82896
82897
82898
82899
82900
82901
82902
82903
82904
82905
82906
82907
82908
82909
82910
82911
82912
82913
82914
82915
82916
82917
82918
82919
82920
82921
82922
82923
82924
82925
82926
82927
82928
82929
82930
82931
82932
82933
82934
82935
82936
82937
82938
82939
82940
82941
82942
82943
82944
82945
82946
82947
82948
82949
82950
82951
82952
82953
82954
82955
82956
82957
82958
82959
82960
82961
82962
82963
82964
82965
82966
82967
82968
82969
82970
82971
82972
82973
82974
82975
82976
82977
82978
82979
82980
82981
82982
82983
82984
82985
82986
82987
82988
82989
82990
82991
82992
82993
82994
82995
82996
82997
82998
82999
83000
83001
83002
83003
83004
83005
83006
83007
83008
83009
83010
83011
83012
83013
83014
83015
83016
83017
83018
83019
83020
83021
83022
83023
83024
83025
83026
83027
83028
83029
83030
83031
83032
83033
83034
83035
83036
83037
83038
83039
83040
83041
83042
83043
83044
83045
83046
83047
83048
83049
83050
83051
83052
83053
83054
83055
83056
83057
83058
83059
83060
83061
83062
83063
83064
83065
83066
83067
83068
83069
83070
83071
83072
83073
83074
83075
83076
83077
83078
83079
83080
83081
83082
83083
83084
83085
83086
83087
83088
83089
83090
83091
83092
83093
83094
83095
83096
83097
83098
83099
83100
83101
83102
83103
83104
83105
83106
83107
83108
83109
83110
83111
83112
83113
83114
83115
83116
83117
83118
83119
83120
83121
83122
83123
83124
83125
83126
83127
83128
83129
83130
83131
83132
83133
83134
83135
83136
83137
83138
83139
83140
83141
83142
83143
83144
83145
83146
83147
83148
83149
83150
83151
83152
83153
83154
83155
83156
83157
83158
83159
83160
83161
83162
83163
83164
83165
83166
83167
83168
83169
83170
83171
83172
83173
83174
83175
83176
83177
83178
83179
83180
83181
83182
83183
83184
83185
83186
83187
83188
83189
83190
83191
83192
83193
83194
83195
83196
83197
83198
83199
83200
83201
83202
83203
83204
83205
83206
83207
83208
83209
83210
83211
83212
83213
83214
83215
83216
83217
83218
83219
83220
83221
83222
83223
83224
83225
83226
83227
83228
83229
83230
83231
83232
83233
83234
83235
83236
83237
83238
83239
83240
83241
83242
83243
83244
83245
83246
83247
83248
83249
83250
83251
83252
83253
83254
83255
83256
83257
83258
83259
83260
83261
83262
83263
83264
83265
83266
83267
83268
83269
83270
83271
83272
83273
83274
83275
83276
83277
83278
83279
83280
83281
83282
83283
83284
83285
83286
83287
83288
83289
83290
83291
83292
83293
83294
83295
83296
83297
83298
83299
83300
83301
83302
83303
83304
83305
83306
83307
83308
83309
83310
83311
83312
83313
83314
83315
83316
83317
83318
83319
83320
83321
83322
83323
83324
83325
83326
83327
83328
83329
83330
83331
83332
83333
83334
83335
83336
83337
83338
83339
83340
83341
83342
83343
83344
83345
83346
83347
83348
83349
83350
83351
83352
83353
83354
83355
83356
83357
83358
83359
83360
83361
83362
83363
83364
83365
83366
83367
83368
83369
83370
83371
83372
83373
83374
83375
83376
83377
83378
83379
83380
83381
83382
83383
83384
83385
83386
83387
83388
83389
83390
83391
83392
83393
83394
83395
83396
83397
83398
83399
83400
83401
83402
83403
83404
83405
83406
83407
83408
83409
83410
83411
83412
83413
83414
83415
83416
83417
83418
83419
83420
83421
83422
83423
83424
83425
83426
83427
83428
83429
83430
83431
83432
83433
83434
83435
83436
83437
83438
83439
83440
83441
83442
83443
83444
83445
83446
83447
83448
83449
83450
83451
83452
83453
83454
83455
83456
83457
83458
83459
83460
83461
83462
83463
83464
83465
83466
83467
83468
83469
83470
83471
83472
83473
83474
83475
83476
83477
83478
83479
83480
83481
83482
83483
83484
83485
83486
83487
83488
83489
83490
83491
83492
83493
83494
83495
83496
83497
83498
83499
83500
83501
83502
83503
83504
83505
83506
83507
83508
83509
83510
83511
83512
83513
83514
83515
83516
83517
83518
83519
83520
83521
83522
83523
83524
83525
83526
83527
83528
83529
83530
83531
83532
83533
83534
83535
83536
83537
83538
83539
83540
83541
83542
83543
83544
83545
83546
83547
83548
83549
83550
83551
83552
83553
83554
83555
83556
83557
83558
83559
83560
83561
83562
83563
83564
83565
83566
83567
83568
83569
83570
83571
83572
83573
83574
83575
83576
83577
83578
83579
83580
83581
83582
83583
83584
83585
83586
83587
83588
83589
83590
// src/builtins.rs
#![allow(dead_code, unreachable_code, unused_variables)]
use anyhow::{Context, Result};
use serde_json;
use std::collections::{BTreeMap, HashMap};
use std::fs;
use sysinfo::{Disks, Networks, System};
use walkdir::WalkDir;

use crate::{
    ai::a2ui::{
        A2UIEvent, A2UIEventType, NotificationLevel, PromptResponse, RenderContent, A2UI_CHANNEL,
    },
    config::{get_config, reload_config, ShellConfig},
    env::Env,
    eval::eval_expr,
    evolution::{CrossoverStrategy, EvolutionConfig, FitnessResult, Population, SelectionStrategy},
    neural::{Activation, ConsensusNetwork, NeuralNetwork},
    os_tools::{execute_tool_safe, OSToolsDatabase, OperatingSystem, ToolCategory},
    rl::{
        ActorCriticAgent, DQNAgent, GridWorld, PolicyGradientAgent, QLearningAgent, ReplayBuffer,
        SarsaAgent,
    },
    rlm::{run_recursive, run_recursive_with_model, RlmConfig},
    security::{
        check_file_size_limit, check_rate_limit, validate_ai_prompt, validate_hostname_or_ip,
        validate_read_path, validate_sh_allowed,
    },
    value::{Lambda, Value},
};
use std::time::Duration;

use crate::path_builtins::{
    bi_path_basename, bi_path_dirname, bi_path_extension, bi_path_is_absolute, bi_path_join,
    bi_path_normalize, bi_path_split, bi_path_stem,
};

// Fast builtin lookup using hash map
lazy_static::lazy_static! {
    /// Public accessor for builtin lookup table (used by agent_api for dynamic discovery)
    // Fx, not SipHash: looked up on every builtin call, keyed by names the
    // shell itself defines. Its iteration order was never stable either way.
    pub static ref BUILTIN_LOOKUP: rustc_hash::FxHashMap<&'static str, usize> = {
        let mut map = rustc_hash::FxHashMap::default();

        // General functions
        map.insert("help", 0);
        map.insert("call", 1);
        map.insert("clear", 2);
        map.insert("echo", 3);
        map.insert("print", 4);
        map.insert("http_get", 5);

        // Option constructors
        map.insert("Some", 6);
        map.insert("None", 7);

        // File system
        map.insert("ls", 8);
        map.insert("list", 8); // alias
        map.insert("pwd", 9);
        map.insert("cat", 10);
        map.insert("read_text", 11);
        map.insert("head", 12);
        map.insert("tail", 13);
        map.insert("find", 14);
        map.insert("sort", 15);
        map.insert("uniq", 16);
        map.insert("wc", 17);
        map.insert("grep", 18);

        // Data/pipelines
        map.insert("map", 19);
        map.insert("where", 20);
        map.insert("reduce", 21);
        map.insert("take", 22);
        map.insert("keys", 23);
        map.insert("len", 24);
        map.insert("length", 24); // alias
        map.insert("type_of", 25);
        map.insert("typeof", 25); // alias

        // Array functions
        map.insert("first", 26);
        map.insert("last", 27);
        map.insert("any", 28);
        map.insert("all", 29);

        // MCP functions
        map.insert("mcp_servers", 30);
        map.insert("mcp-servers", 30); // alias
        map.insert("mcp_detect", 31);
        map.insert("mcp-detect", 31); // alias
        map.insert("mcp_cache_clear", 32);
        map.insert("mcp-cache-clear", 32); // alias
        map.insert("mcp_cache_status", 33);
        map.insert("mcp-cache-status", 33); // alias

        // String functions
        map.insert("split", 34);
        map.insert("join", 35);
        map.insert("trim", 36);
        map.insert("upper", 37);
        map.insert("lower", 38);
        map.insert("replace", 39);
        map.insert("contains", 40);
        map.insert("starts_with", 41);
        map.insert("ends_with", 42);

        // Array functions (extended)
        map.insert("flatten", 43);
        map.insert("reverse", 44);
        map.insert("slice", 45);
        map.insert("range", 46);
        map.insert("zip", 47);
        map.insert("push", 48);
        map.insert("concat", 49);

        // Math functions
        map.insert("abs", 50);
        map.insert("min", 51);
        map.insert("max", 52);
        map.insert("floor", 53);
        map.insert("ceil", 54);
        map.insert("round", 55);
        map.insert("sqrt", 56);
        map.insert("pow", 57);

        // Utility functions
        map.insert("exit", 58);
        map.insert("env", 59);
        map.insert("set_env", 60);
        map.insert("sleep", 61);
        map.insert("time", 62);
        map.insert("json_parse", 63);
        map.insert("json_stringify", 64);

        // Syntax Knowledge Base functions
        map.insert("syntax_get", 65);
        map.insert("syntax_list", 66);
        map.insert("syntax_search", 67);
        map.insert("syntax_add", 68);
        map.insert("syntax_categories", 69);
        map.insert("ab_encode", 70);
        map.insert("ab_decode", 71);

        // Neural Network functions (72-82)
        map.insert("nn_create", 72);
        map.insert("nn_forward", 73);
        map.insert("nn_mutate", 74);
        map.insert("nn_crossover", 75);
        map.insert("nn_params", 76);
        map.insert("nn_set_params", 77);
        map.insert("nn_layers", 78);
        map.insert("nn_info", 79);
        map.insert("consensus_net", 80);
        map.insert("consensus_vote", 81);
        map.insert("activation", 82);

        // Evolution functions (83-92)
        map.insert("population", 83);
        map.insert("evolve", 84);
        map.insert("evolve_step", 85);
        map.insert("fitness", 86);
        map.insert("best_individual", 87);
        map.insert("evolution_stats", 88);
        map.insert("selection_strategy", 89);
        map.insert("crossover_strategy", 90);
        map.insert("evolution_config", 91);
        map.insert("coevolve", 92);

        // Reinforcement Learning functions (93-107)
        map.insert("rl_agent", 93);
        map.insert("rl_action", 94);
        map.insert("rl_update", 95);
        map.insert("rl_sarsa_agent", 96);
        map.insert("rl_sarsa_update", 97);
        map.insert("rl_pg_agent", 98);
        map.insert("rl_pg_step", 99);
        map.insert("rl_pg_episode_end", 100);
        map.insert("rl_ac_agent", 101);
        map.insert("rl_ac_update", 102);
        map.insert("rl_dqn_agent", 103);
        map.insert("rl_dqn_step", 104);
        map.insert("rl_replay_buffer", 105);
        map.insert("rl_gridworld", 106);
        map.insert("rl_env_step", 107);

        // OS Tools functions (108-112)
        map.insert("tools", 108);
        map.insert("tool_list", 108); // alias
        map.insert("os_tools", 108); // alias for tools
        map.insert("tool_info", 109);
        map.insert("tool_schema", 110);
        map.insert("tool_schemas", 110); // alias
        map.insert("tool_exec", 111);
        map.insert("tool_execute", 111); // alias
        map.insert("tool_search", 112);

        // Recursive Language Model functions (113-116)
        map.insert("rlm_agent", 113);
        map.insert("recursive_agent", 113); // alias
        map.insert("rlm_config", 114);
        map.insert("rlm_stats", 115);
        map.insert("rlm_spawn", 116);
        map.insert("spawn_agent", 116); // alias

        // MCP Server/Client functions (117-122)
        map.insert("mcp_server", 117);
        map.insert("mcp_tools", 118);
        map.insert("mcp_list_tools", 118); // alias
        map.insert("mcp_call", 119);
        map.insert("mcp_call_tool", 119); // alias
        map.insert("mcp_resources", 120);
        map.insert("mcp_list_resources", 120); // alias
        map.insert("mcp_prompts", 121);
        map.insert("mcp_list_prompts", 121); // alias
        map.insert("mcp_connect", 122);
        map.insert("mcp_client", 122); // alias

        // New aspirational features (123-131)
        map.insert("sh", 123);
        map.insert("shell", 123); // alias
        map.insert("now", 124);
        map.insert("timestamp", 124); // alias
        map.insert("sort_by", 125);
        map.insert("save_json", 126);
        map.insert("write_json", 126); // alias
        map.insert("ai_backends", 127);
        map.insert("mcp_server_start", 128);
        map.insert("agent_with_mcp", 129);
        map.insert("each", 130); // alias for map with side effects
        map.insert("in", 131); // membership test

        // Additional utility functions (132-136)
        map.insert("values", 132);
        map.insert("sum", 133);
        map.insert("unique", 134);
        map.insert("avg", 135);
        map.insert("mean", 135); // alias for avg
        map.insert("product", 136);

        // Configuration functions (137-143)
        map.insert("config", 137);
        map.insert("config_get", 138);
        map.insert("config_set", 139);
        map.insert("config_path", 140);
        map.insert("config_init", 141);
        map.insert("config_reload", 142);
        map.insert("themes", 143);

        // Plugin functions (144-150)
        map.insert("plugins", 144);
        map.insert("plugin_list", 144); // alias
        map.insert("plugin_info", 145);
        map.insert("plugin_enable", 146);
        map.insert("plugin_disable", 147);
        map.insert("plugin_load", 148);
        map.insert("plugin_unload", 149);
        map.insert("plugin_categories", 150);

        // Error handling functions (151)
        map.insert("is_error", 151);

        // Debugging tools (152-156)
        map.insert("debug", 152);
        map.insert("dbg", 152); // alias
        map.insert("assert", 153);
        map.insert("trace", 154);
        map.insert("type_assert", 155);
        map.insert("assert_type", 155); // alias
        map.insert("inspect", 156);

        // Platform detection functions (157-163)
        map.insert("platform", 157);
        map.insert("is_windows", 158);
        map.insert("is_linux", 159);
        map.insert("is_macos", 160);
        map.insert("is_unix", 161);
        map.insert("is_bsd", 162);
        map.insert("platform_module", 163);

        // Feature flag functions (164-168)
        map.insert("features", 164);
        map.insert("feature_list", 164); // alias
        map.insert("feature_enabled", 165);
        map.insert("has_feature", 165); // alias
        map.insert("feature_enable", 166);
        map.insert("feature_disable", 167);
        map.insert("feature_set", 168);

        // Distributed Computing functions (169-180)
        map.insert("cluster_create", 169);
        map.insert("cluster", 169); // alias
        map.insert("cluster_add_node", 170);
        map.insert("add_node", 170); // alias
        map.insert("cluster_remove_node", 171);
        map.insert("remove_node", 171); // alias
        map.insert("cluster_status", 172);
        map.insert("cluster_nodes", 173);
        map.insert("nodes", 173); // alias
        map.insert("job_submit", 174);
        map.insert("submit", 174); // alias
        map.insert("job_status", 175);
        map.insert("job_cancel", 176);
        map.insert("job_results", 177);
        map.insert("results", 177); // alias
        map.insert("job_list", 178);
        map.insert("jobs", 178); // alias
        map.insert("remote_exec", 179);
        map.insert("exec_remote", 179); // alias
        map.insert("aggregate_results", 180);
        map.insert("aggregate", 180); // alias

        // Advanced AI functions (181-192)
        map.insert("rag_index", 181);
        map.insert("index_docs", 181); // alias
        map.insert("rag_search", 182);
        map.insert("search_docs", 182); // alias
        map.insert("rag_query", 183);
        map.insert("rag", 183); // alias
        map.insert("rag_clear", 184);
        map.insert("kg_add", 185);
        map.insert("add_entity", 185); // alias
        map.insert("kg_relate", 186);
        map.insert("add_relation", 186); // alias
        map.insert("kg_query", 187);
        map.insert("query_kg", 187); // alias
        map.insert("kg_entities", 188);
        map.insert("entities", 188); // alias
        map.insert("kg_relations", 189);
        map.insert("relations", 189); // alias
        map.insert("semantic_cache", 190);
        map.insert("cache_ai", 190); // alias
        map.insert("semantic_cache_get", 191);
        map.insert("cache_get", 191); // alias
        map.insert("semantic_cache_clear", 192);
        map.insert("cache_clear_ai", 192); // alias

        // 193-199: RBAC (Role-Based Access Control)
        map.insert("role_create", 193);
        map.insert("create_role", 193); // alias
        map.insert("role_delete", 194);
        map.insert("delete_role", 194); // alias
        map.insert("role_grant", 195);
        map.insert("grant_permission", 195); // alias
        map.insert("role_revoke", 196);
        map.insert("revoke_permission", 196); // alias
        map.insert("user_roles", 197);
        map.insert("get_roles", 197); // alias
        map.insert("check_permission", 198);
        map.insert("has_permission", 198); // alias
        map.insert("roles_list", 199);
        map.insert("list_roles", 199); // alias

        // 200-203: Audit Logging
        map.insert("audit_log", 200);
        map.insert("log_audit", 200); // alias
        map.insert("audit_query", 201);
        map.insert("query_audit", 201); // alias
        map.insert("audit_export", 202);
        map.insert("export_audit", 202); // alias
        map.insert("audit_stats", 203);
        map.insert("audit_statistics", 203); // alias

        // 204-208: SSO Integration
        map.insert("sso_init", 204);
        map.insert("init_sso", 204); // alias
        map.insert("sso_auth", 205);
        map.insert("sso_authenticate", 205); // alias
        map.insert("sso_validate", 206);
        map.insert("validate_sso", 206); // alias
        map.insert("sso_logout", 207);
        map.insert("logout_sso", 207); // alias
        map.insert("sso_status", 208);
        map.insert("sso_info", 208); // alias

        // 209-210: Compliance Reporting
        map.insert("compliance_check", 209);
        map.insert("check_compliance", 209); // alias
        map.insert("compliance_report", 210);
        map.insert("generate_compliance", 210); // alias

        // 211-214: Model Fine-tuning
        map.insert("finetune_start", 211);
        map.insert("start_finetune", 211); // alias
        map.insert("finetune_status", 212);
        map.insert("finetune_progress", 212); // alias
        map.insert("finetune_list", 213);
        map.insert("list_finetunes", 213); // alias
        map.insert("finetune_cancel", 214);
        map.insert("cancel_finetune", 214); // alias

        // 215-229: A2UI (Agent-to-User Interface) functions
        map.insert("a2ui_notify", 215);
        map.insert("notify_user", 215); // alias
        map.insert("a2ui_prompt", 216);
        map.insert("prompt_user", 216); // alias
        map.insert("a2ui_confirm", 217);
        map.insert("confirm_user", 217); // alias
        map.insert("a2ui_select", 218);
        map.insert("select_user", 218); // alias
        map.insert("a2ui_progress", 219);
        map.insert("progress_update", 219); // alias
        map.insert("a2ui_progress_complete", 220);
        map.insert("progress_done", 220); // alias
        map.insert("a2ui_render", 221);
        map.insert("render_content", 221); // alias
        map.insert("a2ui_render_table", 222);
        map.insert("render_table", 222); // alias
        map.insert("a2ui_render_code", 223);
        map.insert("render_code", 223); // alias
        map.insert("a2ui_toast", 224);
        map.insert("toast", 224); // alias
        map.insert("a2ui_status", 225);
        map.insert("status_bar", 225); // alias
        map.insert("a2ui_clear", 226);
        map.insert("ui_clear", 226); // alias
        map.insert("a2ui_agent_started", 227);
        map.insert("agent_started", 227); // alias
        map.insert("a2ui_agent_completed", 228);
        map.insert("agent_completed", 228); // alias
        map.insert("a2ui_agent_thinking", 229);
        map.insert("agent_thinking", 229); // alias
        // 230-249: Process Management
        map.insert("proc_list", 230);
        map.insert("proc_kill", 231);
        map.insert("proc_info", 232);
        map.insert("proc_spawn", 233);
        map.insert("proc_wait", 234);
        map.insert("proc_exists", 235);
        map.insert("proc_children", 236);
        map.insert("proc_parent", 237);
        map.insert("proc_priority", 238);
        map.insert("proc_set_priority", 239);
        map.insert("proc_cpu_usage", 240);
        map.insert("proc_mem_usage", 241);
        map.insert("proc_threads", 242);
        map.insert("proc_env", 243);
        map.insert("proc_cwd", 244);
        map.insert("proc_exe", 245);
        map.insert("proc_cmdline", 246);
        map.insert("proc_start_time", 247);
        map.insert("proc_suspend", 248);
        map.insert("proc_resume", 249);
        map.insert("ps", 230);
        map.insert("kill", 231);
        // 250-269: Filesystem Extended
        map.insert("fs_stat", 250);
        map.insert("fs_lstat", 251);
        map.insert("fs_chmod", 252);
        map.insert("fs_chown", 253);
        map.insert("fs_link", 254);
        map.insert("fs_symlink", 255);
        map.insert("fs_readlink", 256);
        map.insert("fs_realpath", 257);
        map.insert("fs_tempfile", 258);
        map.insert("fs_tempdir", 259);
        map.insert("fs_watch", 260);
        map.insert("fs_unwatch", 261);
        map.insert("fs_glob", 262);
        map.insert("fs_walk", 263);
        map.insert("fs_tree", 264);
        map.insert("fs_du", 265);
        map.insert("fs_df", 266);
        map.insert("fs_mount", 267);
        map.insert("fs_unmount", 268);
        map.insert("fs_mounts", 269);
        map.insert("stat", 250);
        map.insert("glob", 262);
        map.insert("tree", 264);
        map.insert("du", 265);
        map.insert("df", 266);
        // 270-289: Network Operations
        map.insert("net_interfaces", 270);
        map.insert("net_ip", 271);
        map.insert("net_dns_lookup", 272);
        map.insert("net_dns_reverse", 273);
        map.insert("net_ping", 274);
        map.insert("net_traceroute", 275);
        map.insert("net_connections", 276);
        map.insert("net_listen", 277);
        map.insert("net_connect", 278);
        map.insert("net_send", 279);
        map.insert("net_recv", 280);
        map.insert("net_close", 281);
        map.insert("net_ports", 282);
        map.insert("net_arp", 283);
        map.insert("net_route", 284);
        map.insert("net_stats", 285);
        map.insert("net_bandwidth", 286);
        map.insert("net_latency", 287);
        map.insert("net_scan", 288);
        map.insert("net_whois", 289);
        map.insert("ping", 274);
        map.insert("ifconfig", 270);
        // 290-309: System Information
        map.insert("sys_info", 290);
        map.insert("sys_hostname", 291);
        map.insert("sys_os", 292);
        map.insert("sys_arch", 293);
        map.insert("sys_kernel", 294);
        map.insert("sys_uptime", 295);
        map.insert("sys_boot_time", 296);
        map.insert("sys_cpu_info", 297);
        map.insert("sys_cpu_count", 298);
        map.insert("sys_cpu_freq", 299);
        map.insert("sys_mem_info", 300);
        map.insert("sys_swap_info", 301);
        map.insert("sys_disk_info", 302);
        map.insert("sys_load_avg", 303);
        map.insert("sys_users", 304);
        map.insert("sys_groups", 305);
        map.insert("sys_user_info", 306);
        map.insert("sys_env_all", 307);
        map.insert("sys_locale", 308);
        map.insert("sys_timezone", 309);
        map.insert("hostname", 291);
        map.insert("uptime", 295);
        // Was 304, `sys_users`: every account on the machine, not the caller.
        map.insert("whoami", 1157);
        // 310-329: Service & Daemon Management
        map.insert("svc_list", 310);
        map.insert("svc_status", 311);
        map.insert("svc_start", 312);
        map.insert("svc_stop", 313);
        map.insert("svc_restart", 314);
        map.insert("svc_enable", 315);
        map.insert("svc_disable", 316);
        map.insert("svc_logs", 317);
        map.insert("svc_info", 318);
        map.insert("svc_create", 319);
        map.insert("svc_delete", 320);
        map.insert("cron_list", 321);
        map.insert("cron_add", 322);
        map.insert("cron_remove", 323);
        map.insert("cron_enable", 324);
        map.insert("cron_disable", 325);
        map.insert("at_schedule", 326);
        map.insert("at_list", 327);
        map.insert("at_remove", 328);
        map.insert("startup_list", 329);
        map.insert("service", 311);
        map.insert("systemctl", 311);
        // 330-349: Archive & Compression
        map.insert("zip_create", 330);
        map.insert("zip_extract", 331);
        map.insert("zip_list", 332);
        map.insert("zip_add", 333);
        map.insert("tar_create", 334);
        map.insert("tar_extract", 335);
        map.insert("tar_list", 336);
        map.insert("gzip_compress", 337);
        map.insert("gzip_decompress", 338);
        map.insert("bzip2_compress", 339);
        map.insert("bzip2_decompress", 340);
        map.insert("xz_compress", 341);
        map.insert("xz_decompress", 342);
        map.insert("zstd_compress", 343);
        map.insert("zstd_decompress", 344);
        map.insert("archive_info", 345);
        map.insert("archive_test", 346);
        map.insert("compress", 337);
        map.insert("decompress", 338);
        map.insert("unzip", 331);
        // 350-369: User & Permission Management
        map.insert("user_list", 350);
        map.insert("user_add", 351);
        map.insert("user_del", 352);
        map.insert("user_mod", 353);
        map.insert("user_passwd", 354);
        map.insert("user_lock", 355);
        map.insert("user_unlock", 356);
        map.insert("group_list", 357);
        map.insert("group_add", 358);
        map.insert("group_del", 359);
        map.insert("group_mod", 360);
        map.insert("group_members", 361);
        map.insert("perm_get", 362);
        map.insert("perm_set", 363);
        map.insert("perm_check", 364);
        map.insert("acl_get", 365);
        map.insert("acl_set", 366);
        map.insert("sudo_check", 367);
        map.insert("sudo_exec", 368);
        map.insert("capabilities", 369);
        map.insert("useradd", 351);
        map.insert("userdel", 352);
        map.insert("chmod", 252);
        // 370-389: Package Management
        map.insert("pkg_list", 370);
        map.insert("pkg_search", 371);
        map.insert("pkg_info", 372);
        map.insert("pkg_install", 373);
        map.insert("pkg_remove", 374);
        map.insert("pkg_update", 375);
        map.insert("pkg_upgrade", 376);
        map.insert("pkg_clean", 377);
        map.insert("pkg_sources", 378);
        map.insert("pkg_add_source", 379);
        map.insert("pkg_files", 380);
        map.insert("pkg_owner", 381);
        map.insert("pkg_verify", 382);
        map.insert("pkg_deps", 383);
        map.insert("pkg_rdeps", 384);
        map.insert("pkg_changelog", 385);
        map.insert("pkg_hold", 386);
        map.insert("pkg_unhold", 387);
        map.insert("pkg_autoremove", 388);
        map.insert("pkg_history", 389);
        map.insert("apt", 373);
        map.insert("brew", 373);
        // 390-399: Hardware & Device Info
        map.insert("hw_cpu", 390);
        map.insert("hw_memory", 391);
        map.insert("hw_disk", 392);
        map.insert("hw_gpu", 393);
        map.insert("hw_network", 394);
        map.insert("hw_usb", 395);
        map.insert("hw_pci", 396);
        map.insert("hw_audio", 397);
        map.insert("hw_battery", 398);
        map.insert("hw_sensors", 399);
        map.insert("lscpu", 390);
        map.insert("lsusb", 395);
        map.insert("lspci", 396);
        // 400-429: GUI Automation
        map.insert("gui_list_windows", 400);
        map.insert("gui_focus_window", 401);
        map.insert("gui_minimize_window", 402);
        map.insert("gui_maximize_window", 403);
        map.insert("gui_close_window", 404);
        map.insert("gui_move_window", 405);
        map.insert("gui_resize_window", 406);
        map.insert("gui_screenshot", 407);
        map.insert("gui_screenshot_window", 408);
        map.insert("gui_mouse_move", 409);
        map.insert("gui_mouse_click", 410);
        map.insert("gui_mouse_double_click", 411);
        map.insert("gui_mouse_drag", 412);
        map.insert("gui_mouse_scroll", 413);
        map.insert("gui_mouse_position", 414);
        map.insert("gui_key_press", 415);
        map.insert("gui_key_combo", 416);
        map.insert("gui_type_text", 417);
        map.insert("gui_get_active_window", 418);
        map.insert("gui_screen_size", 419);
        map.insert("gui_find_image", 420);
        map.insert("gui_ocr", 421);
        map.insert("gui_notify", 422);
        map.insert("gui_dialog_message", 423);
        map.insert("gui_dialog_input", 424);
        map.insert("gui_dialog_file_open", 425);
        map.insert("gui_dialog_file_save", 426);
        map.insert("gui_dialog_folder", 427);
        map.insert("gui_wait", 428);
        map.insert("gui_color_picker", 429);
        map.insert("windows", 400);
        map.insert("screenshot", 407);
        // 430-459: Web Automation
        map.insert("web_open_url", 430);
        map.insert("web_fetch", 431);
        map.insert("web_get", 432);
        map.insert("web_post", 433);
        map.insert("web_json_get", 434);
        map.insert("web_json_post", 435);
        map.insert("web_scrape", 436);
        map.insert("web_download", 437);
        map.insert("web_browser_open", 438);
        map.insert("web_parse_url", 439);
        map.insert("web_encode_url", 440);
        map.insert("web_decode_url", 441);
        map.insert("web_parse_query", 442);
        map.insert("web_build_query", 443);
        map.insert("web_headers", 444);
        map.insert("web_cookies", 445);
        map.insert("web_form_submit", 446);
        map.insert("web_upload_file", 447);
        map.insert("web_rest_api", 448);
        map.insert("web_websocket", 449);
        map.insert("web_graphql", 450);
        map.insert("web_check_url", 451);
        map.insert("web_robots_txt", 452);
        map.insert("web_sitemap", 453);
        map.insert("web_extract_emails", 454);
        map.insert("web_extract_phones", 455);
        map.insert("web_html_to_text", 456);
        map.insert("web_html_to_markdown", 457);
        map.insert("web_json_path", 458);
        map.insert("web_xpath", 459);
        map.insert("fetch", 431);
        map.insert("scrape", 436);
        map.insert("curl", 432);
        // 460-479: Clipboard & Input
        map.insert("clipboard_get", 460);
        map.insert("clipboard_set", 461);
        map.insert("clipboard_clear", 462);
        map.insert("clipboard_has_text", 463);
        map.insert("clipboard_get_image", 464);
        map.insert("clipboard_set_image", 465);
        map.insert("clipboard_history", 466);
        map.insert("input_read_line", 467);
        map.insert("input_read_password", 468);
        map.insert("input_read_char", 469);
        map.insert("input_confirm", 470);
        map.insert("input_select", 471);
        map.insert("input_multiselect", 472);
        map.insert("input_editor", 473);
        map.insert("input_autocomplete", 474);
        map.insert("input_spinner", 475);
        map.insert("input_progress", 476);
        map.insert("input_table", 477);
        map.insert("input_form", 478);
        map.insert("input_date", 479);
        map.insert("clipboard", 460);
        map.insert("read_line", 467);
        map.insert("prompt", 467);
        // 480-499: Security & Crypto
        map.insert("crypto_hash", 480);
        map.insert("crypto_hash_file", 481);
        map.insert("crypto_hmac", 482);
        map.insert("crypto_random_bytes", 483);
        map.insert("crypto_uuid", 484);
        map.insert("crypto_base64_encode", 485);
        map.insert("crypto_base64_decode", 486);
        map.insert("crypto_hex_encode", 487);
        map.insert("crypto_hex_decode", 488);
        map.insert("crypto_encrypt", 489);
        map.insert("crypto_decrypt", 490);
        map.insert("crypto_password_hash", 491);
        map.insert("crypto_password_verify", 492);
        map.insert("crypto_cert_info", 493);
        map.insert("crypto_cert_verify", 494);
        map.insert("crypto_generate_key", 495);
        map.insert("crypto_sign", 496);
        map.insert("crypto_verify_signature", 497);
        map.insert("crypto_checksum", 498);
        map.insert("crypto_jwt_decode", 499);
        map.insert("hash", 480);
        map.insert("uuid", 484);
        map.insert("base64_encode", 485);
        map.insert("base64_decode", 486);
        map.insert("hex_encode", 487);
        map.insert("hex_decode", 488);
        map.insert("md5", 1158); // was 480, crypto_hash: md5 answered SHA-256
        map.insert("sha256", 1159); // was 480, crypto_hash: md5 answered SHA-256
        // Appended with the other rows: the id is the row's index in BUILTIN_DISPATCH.
        map.insert("error", 1160);
        map.insert("args", 1161);
        map.insert("int", 1162);
        map.insert("float", 1163);
        map.insert("now_iso", 1164);
        map.insert("regex_match", 1165);
        map.insert("regex_find", 1166);
        map.insert("regex_find_all", 1167);
        map.insert("regex_replace", 1168);
        map.insert("pad_left", 1169);
        map.insert("pad_right", 1170);
        map.insert("date_parse", 1171);
        map.insert("date_diff", 1172);
        map.insert("date_format", 1173);
        map.insert("date_add", 1174);
        map.insert("to_toml", 1175);
        map.insert("from_toml", 1176);
        // Records and number text (1177-1178)
        map.insert("merge", 1177);
        map.insert("format_number", 1178);
        // Paths: text only, no disk access (1179-1186)
        map.insert("path_join", 1179);
        map.insert("path_basename", 1180);
        map.insert("path_dirname", 1181);
        map.insert("path_extension", 1182);
        map.insert("path_stem", 1183);
        map.insert("path_normalize", 1184);
        map.insert("path_is_absolute", 1185);
        map.insert("path_split", 1186);
        map.insert("chunk", 1187);
        // Percent-encoding, RFC 3986 (1188-1189)
        map.insert("url_encode", 1188);
        map.insert("url_decode", 1189);
        // Optional fields and entries (1190-1193)
        map.insert("get", 1190);
        map.insert("has", 1191);
        map.insert("to_entries", 1192);
        map.insert("from_entries", 1193);
        // Text (1194-1197), logarithms and exp (1198-1202), epoch seconds (1203-1204)
        map.insert("title", 1194);
        map.insert("capitalize", 1195);
        map.insert("repeat", 1196);
        map.insert("words", 1197);
        map.insert("log", 1198);
        map.insert("ln", 1199);
        map.insert("log10", 1200);
        map.insert("log2", 1201);
        map.insert("exp", 1202);
        map.insert("from_epoch", 1203);
        map.insert("to_epoch", 1204);
        // Statistics (1205-1208), beside avg
        map.insert("median", 1205);
        map.insert("variance", 1206);
        map.insert("stddev", 1207);
        map.insert("percentile", 1208);
        // Substring position (1209-1210) and regex split (1211)
        map.insert("index_of", 1209);
        map.insert("last_index_of", 1210);
        map.insert("regex_split", 1211);
        // The PowerShell transpiler's `+` (1212)
        map.insert("ps_add", 1212);
        // 500-519: Database
        map.insert("db_sqlite_open", 500);
        map.insert("db_sqlite_query", 501);
        map.insert("db_sqlite_exec", 502);
        map.insert("db_sqlite_tables", 503);
        map.insert("db_sqlite_schema", 504);
        map.insert("db_sqlite_insert", 505);
        map.insert("db_sqlite_update", 506);
        map.insert("db_sqlite_delete", 507);
        map.insert("db_sqlite_count", 508);
        map.insert("db_sqlite_create_table", 509);
        map.insert("db_sqlite_drop_table", 510);
        map.insert("db_sqlite_backup", 511);
        map.insert("db_sqlite_vacuum", 512);
        map.insert("db_sqlite_dump", 513);
        map.insert("db_sqlite_import", 514);
        map.insert("db_csv_to_sqlite", 515);
        map.insert("db_sqlite_to_csv", 516);
        map.insert("db_json_to_sqlite", 517);
        map.insert("db_sqlite_to_json", 518);
        map.insert("db_kv_store", 519);
        map.insert("sqlite_query", 501);
        map.insert("sqlite_exec", 502);
        map.insert("sql", 501);

        // 520-527: File Editing (for AI agents)
        map.insert("file_write", 520);
        map.insert("write_file", 520);
        map.insert("text_write", 520);
        map.insert("file_append", 521);
        map.insert("append_file", 521);
        map.insert("file_patch", 522);
        map.insert("patch_file", 522);
        map.insert("file_replace", 523);
        map.insert("text_replace", 523);
        map.insert("str_replace_in_file", 523);
        map.insert("file_insert", 524);
        map.insert("insert_lines", 524);
        map.insert("file_delete_lines", 525);
        map.insert("delete_lines", 525);
        map.insert("remove_lines", 525);
        map.insert("file_edit", 526);
        map.insert("edit_file", 526);
        map.insert("text_edit", 526);
        map.insert("file_diff", 527);
        map.insert("diff_files", 527);
        // 528-532: Additional file operations
        map.insert("file_backup", 528);
        map.insert("backup_file", 528);
        map.insert("file_copy", 529);
        map.insert("copy_file", 529);
        map.insert("cp", 529);
        map.insert("file_move", 530);
        map.insert("move_file", 530);
        map.insert("mv", 530);
        map.insert("file_rename", 530);
        map.insert("file_exists", 531);
        map.insert("path_exists", 531);
        map.insert("exists", 531);
        map.insert("file_mkdir", 532);
        map.insert("mkdir", 532);
        map.insert("mkdirp", 532);
        // 540-549: A2A (Agent-to-Agent) Protocol
        map.insert("a2a_send", 539);
        map.insert("a2a_receive", 540);
        map.insert("a2a_broadcast", 541);
        map.insert("a2a_discover", 542);
        map.insert("a2a_register", 543);
        map.insert("a2a_unregister", 544);
        map.insert("a2a_status", 545);
        map.insert("a2a_agents", 546);

        // 550-559: NANDA (Consensus) Protocol
        map.insert("nanda_propose", 549);
        map.insert("nanda_vote", 550);
        map.insert("nanda_commit", 551);
        map.insert("nanda_abort", 552);
        map.insert("nanda_status", 553);
        map.insert("nanda_consensus", 554);
        map.insert("nanda_quorum", 555);
    // AI Coding Assistant - Git (560-586)
    map.insert("git_status", 560);
    map.insert("git_diff", 561);
    map.insert("git_diff_staged", 562);
    map.insert("git_log", 563);
    map.insert("git_blame", 564);
    map.insert("git_branch", 565);
    map.insert("git_branches", 566);
    map.insert("git_checkout", 567);
    map.insert("git_commit", 568);
    map.insert("git_add", 569);
    map.insert("git_reset", 570);
    map.insert("git_stash", 571);
    map.insert("git_stash_pop", 572);
    map.insert("git_stash_list", 573);
    map.insert("git_remote", 574);
    map.insert("git_fetch", 575);
    map.insert("git_pull", 576);
    map.insert("git_push", 577);
    map.insert("git_merge", 578);
    map.insert("git_rebase", 579);
    map.insert("git_cherry_pick", 580);
    map.insert("git_tags", 581);
    map.insert("git_show", 582);
    map.insert("git_rev_parse", 583);
    map.insert("git_root", 584);
    map.insert("git_ignore", 585);
    map.insert("git_clean", 586);
    // AI Coding Assistant - Code (590-606)
    map.insert("code_parse", 590);
    map.insert("code_symbols", 591);
    map.insert("code_outline", 592);
    map.insert("code_references", 593);
    map.insert("code_definition", 594);
    map.insert("code_imports", 595);
    map.insert("code_exports", 596);
    map.insert("code_dependencies", 597);
    map.insert("code_callers", 598);
    map.insert("code_callees", 599);
    map.insert("code_hover", 600);
    map.insert("code_signature", 601);
    map.insert("code_completions", 602);
    map.insert("code_format", 603);
    map.insert("code_language", 604);
    map.insert("code_comments", 605);
    map.insert("code_todos", 606);
    // AI Coding Assistant - Project (610-626)
    map.insert("project_type", 610);
    map.insert("project_root", 611);
    map.insert("project_name", 612);
    map.insert("project_version", 613);
    map.insert("project_dependencies", 614);
    map.insert("project_dev_dependencies", 615);
    map.insert("project_scripts", 616);
    map.insert("project_structure", 617);
    map.insert("project_entry_points", 618);
    map.insert("project_test_files", 619);
    map.insert("project_config_files", 620);
    map.insert("project_readme", 621);
    map.insert("project_license", 622);
    map.insert("project_gitignore", 623);
    map.insert("project_languages", 624);
    map.insert("project_loc", 625);
    map.insert("project_size", 626);
    // AI Coding Assistant - Search (630-643)
    map.insert("search_code", 630);
    map.insert("search_grep", 631);
    map.insert("search_regex", 632);
    map.insert("search_symbols", 633);
    map.insert("search_files", 634);
    map.insert("search_recent", 635);
    map.insert("search_modified", 636);
    map.insert("search_by_type", 637);
    map.insert("search_by_size", 638);
    map.insert("search_duplicates", 639);
    map.insert("search_todos", 640);
    map.insert("search_fixmes", 641);
    map.insert("search_semantic", 642);
    map.insert("search_similar", 643);
    // AI Coding Assistant - Test (650-661)
    map.insert("test_run", 650);
    map.insert("test_run_file", 651);
    map.insert("test_run_function", 652);
    map.insert("test_list", 653);
    map.insert("test_coverage", 654);
    map.insert("test_failing", 655);
    map.insert("test_passing", 656);
    map.insert("test_skipped", 657);
    map.insert("test_watch", 658);
    map.insert("test_bench", 659);
    map.insert("test_snapshot", 660);
    map.insert("test_generate", 661);
    // AI Coding Assistant - Diagnostics (670-678)
    map.insert("diag_check", 670);
    map.insert("diag_lint", 671);
    map.insert("diag_errors", 672);
    map.insert("diag_warnings", 673);
    map.insert("diag_all", 674);
    map.insert("diag_fix", 675);
    map.insert("diag_explain", 676);
    map.insert("diag_suppress", 677);
    map.insert("diag_config", 678);
    // AI Coding Assistant - Refactor (680-691)
    map.insert("refactor_rename", 680);
    map.insert("refactor_rename_file", 681);
    map.insert("refactor_extract_function", 682);
    map.insert("refactor_extract_variable", 683);
    map.insert("refactor_extract_constant", 684);
    map.insert("refactor_inline", 685);
    map.insert("refactor_move_to_file", 686);
    map.insert("refactor_change_signature", 687);
    map.insert("refactor_add_parameter", 688);
    map.insert("refactor_remove_parameter", 689);
    map.insert("refactor_organize_imports", 690);
    map.insert("refactor_remove_unused", 691);
    // AI Coding Assistant - Session (700-712)
    map.insert("session_start", 700);
    map.insert("session_end", 701);
    map.insert("session_id", 702);
    map.insert("session_history", 703);
    map.insert("session_undo", 704);
    map.insert("session_redo", 705);
    map.insert("session_checkpoint", 706);
    map.insert("session_restore", 707);
    map.insert("session_checkpoints", 708);
    map.insert("session_diff_since", 709);
    map.insert("session_changes", 710);
    map.insert("session_rollback", 711);
    map.insert("session_export", 712);
    // AI Coding Assistant - Docs (720-727)
    map.insert("docs_generate", 720);
    map.insert("docs_search", 721);
    map.insert("docs_api", 722);
    map.insert("docs_readme", 723);
    map.insert("docs_changelog", 724);
    map.insert("docs_examples", 725);
    map.insert("docs_types", 726);
    map.insert("docs_signatures", 727);
    // AI Coding Assistant - Environment (730-747)
    map.insert("env_detect", 730);
    map.insert("env_python", 731);
    map.insert("env_node", 732);
    map.insert("env_rust", 733);
    map.insert("env_go", 734);
    map.insert("env_java", 735);
    map.insert("env_dotnet", 736);
    map.insert("env_ruby", 737);
    map.insert("env_shell", 738);
    map.insert("env_path", 739);
    map.insert("env_var", 740);
    map.insert("env_vars", 741);
    map.insert("env_set", 742);
    map.insert("env_unset", 743);
    map.insert("env_docker", 744);
    map.insert("env_container", 745);
    map.insert("env_venv", 746);
    map.insert("env_activate", 747);
    // Platform versioning module (indices 748-787)
    map.insert("platform_snapshot", 748);
    map.insert("platform_os_version", 749);
    map.insert("platform_kernel", 750);
    map.insert("platform_build", 751);
    map.insert("platform_arch", 752);
    map.insert("platform_hostname", 753);
    map.insert("platform_machine_id", 754);
    map.insert("platform_tool_version", 755);
    map.insert("platform_tool_versions", 756);
    map.insert("platform_detect_tools", 757);
    map.insert("platform_has_tool", 758);
    map.insert("platform_capabilities", 759);
    map.insert("platform_has_admin", 760);
    map.insert("platform_has_sudo", 761);
    map.insert("platform_has_gui", 762);
    map.insert("platform_has_network", 763);
    map.insert("platform_has_container", 764);
    map.insert("platform_pkg_managers", 765);
    map.insert("platform_normalize_path", 766);
    map.insert("platform_normalize_output", 767);
    map.insert("platform_path_sep", 768);
    map.insert("platform_line_ending", 769);
    map.insert("platform_shell_type", 770);
    map.insert("platform_require", 771);
    map.insert("platform_check_reqs", 772);
    map.insert("platform_satisfies", 773);
    map.insert("platform_diff", 774);
    map.insert("platform_compatible", 775);
    map.insert("platform_db_init", 776);
    map.insert("platform_db_store", 777);
    map.insert("platform_db_load", 778);
    map.insert("platform_db_list", 779);
    map.insert("platform_db_delete", 780);
    map.insert("platform_db_compare", 781);
    map.insert("platform_db_export", 782);
    map.insert("platform_db_import", 783);
    map.insert("platform_fingerprint", 784);
    map.insert("platform_hash", 785);
    // Platform categorized tools (786-799)
    map.insert("platform_compilers", 786);
    map.insert("platform_build_systems", 787);
    map.insert("platform_runtimes", 788);
    map.insert("platform_pkg_lang", 789);
    map.insert("platform_containers", 790);
    map.insert("platform_cloud_clis", 791);
    map.insert("platform_databases", 792);
    map.insert("platform_linters", 793);
    map.insert("platform_vcs", 794);
    map.insert("platform_iac_tools", 795);
    // Platform library detection (796-803)
    map.insert("platform_libs", 796);
    map.insert("platform_lib_version", 797);
    map.insert("platform_system_libs", 798);
    map.insert("platform_sdk_version", 799);
    map.insert("platform_libc", 800);
    map.insert("platform_libcpp", 801);
    map.insert("platform_ssl_version", 802);
    map.insert("platform_cuda_version", 803);
    // Platform hardware detection (804-815)
    map.insert("platform_cpu", 804);
    map.insert("platform_cpu_count", 805);
    map.insert("platform_cpu_freq", 806);
    map.insert("platform_memory", 807);
    map.insert("platform_memory_total", 808);
    map.insert("platform_memory_free", 809);
    map.insert("platform_disks", 810);
    map.insert("platform_disk_usage", 811);
    map.insert("platform_gpus", 812);
    map.insert("platform_gpu_memory", 813);
    map.insert("platform_network_interfaces", 814);
    map.insert("platform_hardware_summary", 815);
    // Proactive monitoring & alerting (816-843)
    map.insert("monitor_htop", 816);
    map.insert("monitor_iotop", 817);
    map.insert("monitor_nmon", 818);
    map.insert("monitor_nethogs", 819);
    map.insert("monitor_iftop", 820);
    map.insert("monitor_glances", 821);
    map.insert("monitor_tcpdump", 822);
    map.insert("monitor_sockets", 823);
    map.insert("monitor_ip_addr", 824);
    map.insert("monitor_ip_route", 825);
    map.insert("monitor_ip_link", 826);
    map.insert("monitor_ethtool", 827);
    map.insert("monitor_perf_stat", 828);
    map.insert("monitor_perf_record", 829);
    map.insert("monitor_memory", 830);
    map.insert("monitor_uptime", 831);
    map.insert("monitor_users", 832);
    map.insert("monitor_logins", 833);
    map.insert("monitor_syslog", 834);
    map.insert("monitor_dstat", 835);
    // Proactive alerting (836-843)
    map.insert("monitor_health_check", 836);
    map.insert("monitor_alert_create", 837);
    map.insert("monitor_alert_list", 838);
    map.insert("monitor_alert_history", 839);
    map.insert("monitor_alert_remove", 840);
    map.insert("monitor_watch_cpu", 841);
    map.insert("monitor_watch_memory", 842);
    map.insert("monitor_watch_disk", 843);
    // Cloud & Scale (844-868)
    // Cloud platform
    map.insert("cloud_deploy", 844);
    map.insert("cloud_instances", 845);
    map.insert("cloud_instance_create", 846);
    map.insert("cloud_instance_destroy", 847);
    map.insert("cloud_instance_status", 848);
    map.insert("cloud_instance_connect", 849);
    map.insert("cloud_regions", 850);
    map.insert("cloud_config", 851);
    // Remote REPL
    map.insert("repl_serve", 852);
    map.insert("repl_connect", 853);
    map.insert("repl_sessions", 854);
    map.insert("repl_disconnect", 855);
    map.insert("repl_broadcast", 856);
    // Team workspaces
    map.insert("workspace_create", 857);
    map.insert("workspace_list", 858);
    map.insert("workspace_join", 859);
    map.insert("workspace_leave", 860);
    map.insert("workspace_members", 861);
    map.insert("workspace_share_agent", 862);
    map.insert("workspace_agents", 863);
    map.insert("workspace_sync", 864);
    // Marketplace
    map.insert("marketplace_publish", 865);
    map.insert("marketplace_search", 866);
    map.insert("marketplace_install", 867);
    map.insert("marketplace_uninstall", 868);
    map.insert("marketplace_list", 869);
    map.insert("marketplace_info", 870);
    map.insert("marketplace_rate", 871);
    map.insert("marketplace_update", 872);
    // Telemetry & Analytics
    map.insert("telemetry_enable", 873);
    map.insert("telemetry_disable", 874);
    map.insert("telemetry_status", 875);
    map.insert("telemetry_report", 876);
    map.insert("telemetry_events", 877);
    map.insert("telemetry_reset", 878);
    // ── CLI Tool Wrappers (879-987) ──────────────────────────
    // SSH (879-883)
    map.insert("ssh_exec", 879);
    map.insert("ssh_tunnel", 880);
    map.insert("ssh_keygen", 881);
    map.insert("ssh_copy_id", 882);
    map.insert("ssh_config", 883);
    // rsync (884)
    map.insert("rsync_sync", 884);
    map.insert("rsync", 884);
    // scp (885-886)
    map.insert("scp_upload", 885);
    map.insert("scp_download", 886);
    // openssl (887-888)
    map.insert("openssl_cert_info", 887);
    map.insert("openssl_genrsa", 888);
    // gpg (889-891)
    map.insert("gpg_list_keys", 889);
    map.insert("gpg_encrypt", 890);
    map.insert("gpg_decrypt", 891);
    // Docker (892-911)
    map.insert("docker_ps", 892);
    map.insert("docker_images", 893);
    map.insert("docker_run", 894);
    map.insert("docker_exec", 895);
    map.insert("docker_logs", 896);
    map.insert("docker_stop", 897);
    map.insert("docker_rm", 898);
    map.insert("docker_build", 899);
    map.insert("docker_pull", 900);
    map.insert("docker_push", 901);
    map.insert("docker_inspect", 902);
    map.insert("docker_volumes", 903);
    map.insert("docker_networks", 904);
    map.insert("docker_compose_up", 905);
    map.insert("docker_compose_down", 906);
    map.insert("docker_compose_ps", 907);
    map.insert("docker_stats", 908);
    map.insert("docker_top", 909);
    map.insert("docker_cp", 910);
    map.insert("docker_tag", 911);
    // Podman (912-920)
    map.insert("podman_ps", 912);
    map.insert("podman_images", 913);
    map.insert("podman_run", 914);
    map.insert("podman_exec", 915);
    map.insert("podman_logs", 916);
    map.insert("podman_stop", 917);
    map.insert("podman_rm", 918);
    map.insert("podman_build", 919);
    map.insert("podman_pull", 920);
    // Kubernetes / kubectl (921-943)
    map.insert("k8s_get", 921);
    map.insert("kubectl_get", 921);
    map.insert("k8s_apply", 922);
    map.insert("kubectl_apply", 922);
    map.insert("k8s_delete", 923);
    map.insert("kubectl_delete", 923);
    map.insert("k8s_describe", 924);
    map.insert("kubectl_describe", 924);
    map.insert("k8s_logs", 925);
    map.insert("kubectl_logs", 925);
    map.insert("k8s_exec", 926);
    map.insert("kubectl_exec", 926);
    map.insert("k8s_pods", 927);
    map.insert("k8s_services", 928);
    map.insert("k8s_deployments", 929);
    map.insert("k8s_namespaces", 930);
    map.insert("k8s_nodes", 931);
    map.insert("k8s_events", 932);
    map.insert("k8s_configmaps", 933);
    map.insert("k8s_secrets", 934);
    map.insert("k8s_ingresses", 935);
    map.insert("k8s_rollout_status", 936);
    map.insert("k8s_rollout_restart", 937);
    map.insert("k8s_scale", 938);
    map.insert("k8s_top_pods", 939);
    map.insert("k8s_top_nodes", 940);
    map.insert("k8s_context", 941);
    map.insert("k8s_contexts", 942);
    map.insert("k8s_cluster_info", 943);
    // Helm (944-950)
    map.insert("helm_list", 944);
    map.insert("helm_install", 945);
    map.insert("helm_upgrade", 946);
    map.insert("helm_uninstall", 947);
    map.insert("helm_repos", 948);
    map.insert("helm_search", 949);
    map.insert("helm_status", 950);
    // Terraform (951-958)
    map.insert("terraform_init", 951);
    map.insert("terraform_plan", 952);
    map.insert("terraform_apply", 953);
    map.insert("terraform_destroy", 954);
    map.insert("terraform_state", 955);
    map.insert("terraform_output", 956);
    map.insert("terraform_workspace", 957);
    map.insert("terraform_validate", 958);
    // Ansible (959-962)
    map.insert("ansible_playbook", 959);
    map.insert("ansible_inventory", 960);
    map.insert("ansible_galaxy", 961);
    map.insert("ansible_vault", 962);
    // journalctl (963)
    map.insert("journalctl", 963);
    // lsof (964)
    map.insert("lsof", 964);
    // ── New cross-platform tool implementations (965-987) ────
    // wget (965)
    map.insert("wget", 965);
    map.insert("wget_download", 965);
    // age encryption (966-968)
    map.insert("age_encrypt", 966);
    map.insert("age_decrypt", 967);
    map.insert("age_keygen", 968);
    // ripgrep (969)
    map.insert("rg", 969);
    map.insert("rg_search", 969);
    map.insert("ripgrep", 969);
    // fd (970)
    map.insert("fd", 970);
    map.insert("fd_find", 970);
    // sed (971)
    map.insert("sed", 971);
    map.insert("sed_replace", 971);
    // awk (972)
    map.insert("awk", 972);
    map.insert("awk_process", 972);
    // cut (973)
    map.insert("cut", 973);
    map.insert("cut_columns", 973);
    // xargs (974)
    map.insert("xargs", 974);
    map.insert("xargs_exec", 974);
    // jq (975-976)
    map.insert("jq", 975);
    map.insert("jq_query", 975);
    map.insert("jq_filter", 976);
    // yq (977)
    map.insert("yq", 977);
    map.insert("yq_query", 977);
    // pager/less (978)
    map.insert("less", 978);
    map.insert("pager", 978);
    // tee (979)
    map.insert("tee", 979);
    map.insert("tee_output", 979);
    // make (980-981)
    map.insert("make_run", 980);
    map.insert("make_targets", 981);
    // cmake (982-983)
    map.insert("cmake_configure", 982);
    map.insert("cmake_build", 983);
    // ninja (984)
    map.insert("ninja_build", 984);
    // netstat (985)
    map.insert("netstat", 985);
    map.insert("netstat_info", 985);
    // nmap (986-987)
    map.insert("nmap_scan", 986);
    map.insert("nmap_quick", 987);
    // ============================================================
    // CLI Tool Wrappers — Tools 51-150 (indices 988-1103)
    // ============================================================
    // Dead-code activations (988-994)
    map.insert("file_type", 988);
    map.insert("dd_copy", 989);
    map.insert("lsblk", 990);
    map.insert("blkid", 991);
    map.insert("strace_cmd", 992);
    map.insert("strace", 992);
    map.insert("mount_info", 993);
    map.insert("top_snapshot", 994);
    // tmux (995-998)
    map.insert("tmux_new", 995);
    map.insert("tmux_list", 996);
    map.insert("tmux_attach", 997);
    map.insert("tmux_send", 998);
    // tmux_kill took reserved slot 556; the tmux range 995-998 is full.
    map.insert("tmux_kill", 556);
    // screen (999-1001)
    map.insert("screen_new", 999);
    map.insert("screen_list", 1000);
    map.insert("screen_attach", 1001);
    // timeout (1002)
    map.insert("timeout_cmd", 1002);
    map.insert("timeout", 1002);
    // pkill (1003)
    map.insert("pkill", 1003);
    // pgrep (1004)
    map.insert("pgrep", 1004);
    // lnav (1005)
    map.insert("lnav_open", 1005);
    map.insert("lnav", 1005);
    // multitail (1006)
    map.insert("multitail_open", 1006);
    map.insert("multitail", 1006);
    // logrotate (1007)
    map.insert("logrotate_run", 1007);
    map.insert("logrotate", 1007);
    // ltrace (1008)
    map.insert("ltrace_cmd", 1008);
    map.insert("ltrace", 1008);
    // valgrind (1009-1010)
    map.insert("valgrind_run", 1009);
    map.insert("valgrind", 1009);
    map.insert("valgrind_memcheck", 1010);
    // gdb (1011-1012)
    map.insert("gdb_run", 1011);
    map.insert("gdb", 1011);
    map.insert("gdb_bt", 1012);
    // lldb (1013)
    map.insert("lldb_run", 1013);
    map.insert("lldb", 1013);
    // objdump (1014-1015)
    map.insert("objdump_disasm", 1014);
    map.insert("objdump", 1014);
    map.insert("objdump_headers", 1015);
    // nm (1016)
    map.insert("nm_symbols", 1016);
    map.insert("nm", 1016);
    // readelf (1017-1018)
    map.insert("readelf_headers", 1017);
    map.insert("readelf", 1017);
    map.insert("readelf_sections", 1018);
    // strings (1019)
    map.insert("strings_extract", 1019);
    map.insert("strings", 1019);
    // chgrp (1020)
    map.insert("chgrp", 1020);
    // mtr (1021)
    map.insert("mtr_trace", 1021);
    map.insert("mtr", 1021);
    // host (1022)
    map.insert("host_lookup", 1022);
    map.insert("host", 1022);
    // nc/netcat (1023-1024)
    map.insert("nc_connect", 1023);
    map.insert("nc", 1023);
    map.insert("netcat", 1023);
    map.insert("nc_listen", 1024);
    // socat (1025)
    map.insert("socat_relay", 1025);
    map.insert("socat", 1025);
    // iperf3 (1026-1027)
    map.insert("iperf3_server", 1026);
    map.insert("iperf3_client", 1027);
    map.insert("iperf3", 1027);
    // bat (1028)
    map.insert("bat_view", 1028);
    map.insert("bat", 1028);
    // eza (1029)
    map.insert("eza_list", 1029);
    map.insert("eza", 1029);
    // zoxide (1030-1031)
    map.insert("zoxide_add", 1030);
    map.insert("zoxide_query", 1031);
    map.insert("zoxide", 1031);
    // delta (1032)
    map.insert("delta_diff", 1032);
    map.insert("delta", 1032);
    // lazygit (1033)
    map.insert("lazygit_open", 1033);
    map.insert("lazygit", 1033);
    // fzf (1034)
    map.insert("fzf_select", 1034);
    map.insert("fzf", 1034);
    // rga (1035)
    map.insert("rga_search", 1035);
    map.insert("rga", 1035);
    // sd (1036)
    map.insert("sd_replace", 1036);
    map.insert("sd", 1036);
    // hyperfine (1037)
    map.insert("hyperfine_bench", 1037);
    map.insert("hyperfine", 1037);
    // tokei (1038)
    map.insert("tokei_count", 1038);
    map.insert("tokei", 1038);
    // entr (1039)
    map.insert("entr_watch", 1039);
    map.insert("entr", 1039);
    // watchexec (1040)
    map.insert("watchexec_run", 1040);
    map.insert("watchexec", 1040);
    // just (1041-1042)
    map.insert("just_run", 1041);
    map.insert("just", 1041);
    map.insert("just_list", 1042);
    // task (1043-1044)
    map.insert("task_run", 1043);
    map.insert("task_list", 1044);
    // direnv (1045-1046)
    map.insert("direnv_allow", 1045);
    map.insert("direnv_status", 1046);
    map.insert("direnv", 1046);
    // asdf (1047-1048)
    map.insert("asdf_list", 1047);
    map.insert("asdf_install", 1048);
    map.insert("asdf", 1047);
    // mise (1049-1050)
    map.insert("mise_use", 1049);
    map.insert("mise_list", 1050);
    map.insert("mise", 1050);
    // uv (1051-1053)
    map.insert("uv_run", 1051);
    map.insert("uv_pip", 1052);
    map.insert("uv_venv", 1053);
    // pipx (1054-1055)
    map.insert("pipx_install", 1054);
    map.insert("pipx_list", 1055);
    map.insert("pipx", 1055);
    // poetry (1056-1057)
    map.insert("poetry_run", 1056);
    map.insert("poetry_install", 1057);
    // node (1058)
    map.insert("node_run", 1058);
    // npm (1059-1060)
    map.insert("npm_run", 1059);
    map.insert("npm_install", 1060);
    // pnpm (1061-1062)
    map.insert("pnpm_run", 1061);
    map.insert("pnpm_install", 1062);
    // yarn (1063-1064)
    map.insert("yarn_run", 1063);
    map.insert("yarn_install", 1064);
    // cargo (1065-1067)
    map.insert("cargo_run", 1065);
    map.insert("cargo_build_cmd", 1066);
    map.insert("cargo_test_cmd", 1067);
    // rustup (1068-1069)
    map.insert("rustup_show", 1068);
    map.insert("rustup_update", 1069);
    // go (1070-1072)
    map.insert("go_run", 1070);
    map.insert("go_build", 1071);
    map.insert("go_test", 1072);
    // mage (1073)
    map.insert("mage_run", 1073);
    map.insert("mage", 1073);
    // bun (1074-1075)
    map.insert("bun_run", 1074);
    map.insert("bun_install", 1075);
    // deno (1076-1077)
    map.insert("deno_run", 1076);
    map.insert("deno_task", 1077);
    // gh (1078-1080)
    map.insert("gh_pr", 1078);
    map.insert("gh_issue", 1079);
    map.insert("gh_repo_cmd", 1080);
    map.insert("gh_repo", 1080);
    // glab (1081-1082)
    map.insert("glab_mr", 1081);
    map.insert("glab_issue", 1082);
    // act (1083)
    map.insert("act_run", 1083);
    map.insert("act", 1083);
    // pre-commit (1084-1085)
    map.insert("pre_commit_run", 1084);
    map.insert("pre_commit_install", 1085);
    // buildah (1086-1087)
    map.insert("buildah_build", 1086);
    map.insert("buildah_images", 1087);
    // skopeo (1088-1089)
    map.insert("skopeo_copy", 1088);
    map.insert("skopeo_inspect", 1089);
    // trivy (1090-1091)
    map.insert("trivy_scan", 1090);
    map.insert("trivy_image", 1091);
    // hadolint (1092)
    map.insert("hadolint_check", 1092);
    map.insert("hadolint", 1092);
    // shellcheck (1093)
    map.insert("shellcheck_check", 1093);
    map.insert("shellcheck", 1093);
    // shfmt (1094)
    map.insert("shfmt_format", 1094);
    map.insert("shfmt", 1094);
    // yamllint (1095)
    map.insert("yamllint_check", 1095);
    map.insert("yamllint", 1095);
    // prettier (1096)
    map.insert("prettier_format", 1096);
    map.insert("prettier", 1096);
    // eslint (1097)
    map.insert("eslint_check", 1097);
    map.insert("eslint", 1097);
    // ruff (1098-1099)
    map.insert("ruff_check", 1098);
    map.insert("ruff_format", 1099);
    // black (1100)
    map.insert("black_format", 1100);
    map.insert("black", 1100);
    // mypy (1101)
    map.insert("mypy_check", 1101);
    map.insert("mypy", 1101);
    // pytest (1102)
    map.insert("pytest_run", 1102);
    map.insert("pytest", 1102);
    // nodemon (1103)
    map.insert("nodemon_run", 1103);
    map.insert("nodemon", 1103);
    // safety: approval + audit verification (1104-1105)
    map.insert("approve", 1104);
    map.insert("audit_verify", 1105);
    // safety: RBAC principal authorization (1106-1108)
    map.insert("rbac_principal", 1106);
    map.insert("rbac_grant", 1107);
    map.insert("rbac_can", 1108);
    map.insert("rbac_register", 1146);
    map.insert("rbac_login", 1147);
    map.insert("rbac_logout", 1148);
    map.insert("rbac_session", 1149);
    map.insert("db_csv_query", 1150);
    map.insert("db_csv_to_json", 1150);
    map.insert("db_json_query", 1151);
    map.insert("db_json_to_csv", 1152);
    map.insert("clipboard_types", 1153);
    map.insert("crypto_random_string", 1154);
    map.insert("input_number", 1155);
    map.insert("input_timeout", 1156);
    // output economy: compact rendering + token estimate (1109-1110)
    map.insert("aecon", 1109);
    map.insert("tokens", 1110);
    // progressive ontology disclosure (1111-1112)
    map.insert("ontology_manifest", 1111);
    map.insert("ontology_describe", 1112);
    // deterministic canonical serialization (1113)
    map.insert("canonical", 1113);
    // filesystem transactions / checkpoints (1114-1117)
    map.insert("tx_begin", 1114);
    map.insert("tx_commit", 1115);
    map.insert("tx_rollback", 1116);
    map.insert("tx_status", 1117);
    // output budgeting / paging (1118)
    map.insert("budget", 1118);
    // plan / apply: atomic, approved, reviewable destructive batches (1119-1120)
    map.insert("plan", 1119);
    map.insert("plan_diff", 1141);
    // Filesystem removal and creation. These have had working, guarded
    // implementations the whole time and were never registered, so
    // `rm(...)` answered "unknown builtin" while `effect_of("rm")`
    // reported Destructive -- the safety layer was guarding a name the
    // dispatcher did not have. A shell that cannot delete a file is not
    // a product decision.
    map.insert("rm", 1142);
    map.insert("rmdir", 1143);
    map.insert("touch", 1144);
    map.insert("cd", 1145);
    map.insert("apply", 1120);
    // safety introspection (1121)
    map.insert("safety_status", 1121);
    // stateful sessions: persistent Env across calls (1122-1125)
    map.insert("sess_open", 1122);
    map.insert("sess_eval", 1123);
    map.insert("sess_close", 1124);
    map.insert("sess_usage", 1125);
    // audit review (1126)
    map.insert("audit_tail", 1126);
    // output economy: structural digest (1127)
    map.insert("digest", 1127);
    // output economy: source-side field projection (1128)
    map.insert("pick", 1128);
    // output economy: AECON decoder — reverses the tabular encoding (1129)
    map.insert("aecon_decode", 1129);
    // persistent key-value store (sqlite-backed; transactional via db_sqlite_exec)
    map.insert("db_kv_get", 1130);
    map.insert("db_kv_set", 1131);
    map.insert("db_kv_delete", 1132);
    map.insert("db_kv_keys", 1133);
    map.insert("db_kv_store", 1134);
    // transactions: named savepoints (partial rollback)
    map.insert("tx_savepoint", 1135);
    map.insert("tx_rollback_to", 1136);
    // resource governors (§7.6)
    map.insert("governor_status", 1137);
    map.insert("governor_reset", 1138);
    // self-healing: minimal repair context + rollback-bracketed attempts
    map.insert("diagnose", 1139);
    map.insert("try_repair", 1140);
        map
    };

    /// Runtime feature flags registry
    /// Features can be set via IRONSHELL_FEATURES env var (comma-separated) or via feature_enable/disable
    static ref FEATURE_FLAGS: std::sync::RwLock<std::collections::HashSet<String>> = {
        let mut features = std::collections::HashSet::new();
        // Load features from environment variable
        if let Ok(env_features) = std::env::var("IRONSHELL_FEATURES") {
            for feature in env_features.split(',') {
                let feature = feature.trim();
                if !feature.is_empty() {
                    features.insert(feature.to_string());
                }
            }
        }
        std::sync::RwLock::new(features)
    };

    // ===================== Distributed Computing Storage =====================

    /// Cluster node representation for distributed computing
    static ref CLUSTER_NODES: std::sync::RwLock<HashMap<String, ClusterNode>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    /// Clusters made by cluster_create, keyed by name. In-process only.
    static ref CLUSTERS: std::sync::RwLock<BTreeMap<String, String>> = {
        std::sync::RwLock::new(BTreeMap::new())
    };

    /// Distributed jobs registry
    static ref DISTRIBUTED_JOBS: std::sync::RwLock<HashMap<String, DistributedJob>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    /// Job results storage
    static ref JOB_RESULTS: std::sync::RwLock<HashMap<String, Vec<Value>>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    // ===================== Advanced AI Storage =====================

    /// RAG document index - stores document chunks with embeddings
    static ref RAG_INDEX: std::sync::RwLock<RagIndex> = {
        std::sync::RwLock::new(RagIndex::new())
    };

    /// Knowledge graph storage
    static ref KNOWLEDGE_GRAPH: std::sync::RwLock<KnowledgeGraph> = {
        std::sync::RwLock::new(KnowledgeGraph::new())
    };

    /// Semantic cache for AI responses
    static ref SEMANTIC_CACHE: std::sync::RwLock<SemanticCache> = {
        std::sync::RwLock::new(SemanticCache::new())
    };

    // ===================== Enterprise Storage =====================

    /// RBAC role definitions
    static ref RBAC_ROLES: std::sync::RwLock<HashMap<String, Role>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    /// User to roles mapping
    static ref USER_ROLES: std::sync::RwLock<HashMap<String, Vec<String>>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    /// Audit log entries
    static ref AUDIT_LOG: std::sync::RwLock<Vec<AuditEntry>> = {
        std::sync::RwLock::new(Vec::new())
    };

    /// SSO configuration
    static ref SSO_CONFIG: std::sync::RwLock<Option<SsoConfig>> = {
        std::sync::RwLock::new(None)
    };

    /// SSO active sessions
    /// Live SSO tokens, mapped to their user. Nothing inserts into it: `sso_auth`
    /// cannot verify a callback, so it mints none (see `bi_sso_auth`).
    static ref SSO_SESSIONS: std::sync::RwLock<HashMap<String, String>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    /// Fine-tuning jobs
    static ref FINETUNE_JOBS: std::sync::RwLock<HashMap<String, FinetuneJob>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    // ===================== Cloud & Scale Storage =====================

    /// Cloud platform configuration
    static ref CLOUD_CONFIG: std::sync::RwLock<Option<CloudConfig>> = {
        std::sync::RwLock::new(None)
    };

    /// Remote REPL sessions
    static ref REPL_SESSIONS: std::sync::RwLock<HashMap<String, ReplSession>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    /// The REPL listener started by repl_serve.
    static ref REPL_SERVER: std::sync::Mutex<Option<ReplServer>> = std::sync::Mutex::new(None);

    /// Team workspaces
    static ref WORKSPACES: std::sync::RwLock<HashMap<String, TeamWorkspace>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    /// Marketplace package registry (local cache)
    static ref MARKETPLACE_PACKAGES: std::sync::RwLock<HashMap<String, MarketplacePackage>> = {
        std::sync::RwLock::new(HashMap::new())
    };

    /// Telemetry events buffer
    static ref TELEMETRY_EVENTS: std::sync::RwLock<Vec<TelemetryEvent>> = {
        std::sync::RwLock::new(Vec::new())
    };

    /// Telemetry opt-in state
    static ref TELEMETRY_ENABLED: std::sync::RwLock<bool> = {
        // Respect IRONSHELL_TELEMETRY env var, default to disabled (opt-in)
        let enabled = std::env::var("IRONSHELL_TELEMETRY")
            .map(|v| v == "1" || v.to_lowercase() == "true")
            .unwrap_or(false);
        std::sync::RwLock::new(enabled)
    };
}

// ===================== Distributed Computing Types =====================

/// Cluster node representation
#[derive(Debug, Clone)]
struct ClusterNode {
    id: String,
    address: String,
    capabilities: Vec<String>,
    status: NodeStatus,
    load: f32,
    last_heartbeat: std::time::Instant,
}

#[derive(Debug, Clone, PartialEq)]
enum NodeStatus {
    /// Added with cluster_add_node. Nothing has checked that the node is up.
    Registered,
    Online,
    Offline,
    Busy,
    Draining,
}

impl NodeStatus {
    fn as_str(&self) -> &'static str {
        match self {
            NodeStatus::Registered => "registered",
            NodeStatus::Online => "online",
            NodeStatus::Offline => "offline",
            NodeStatus::Busy => "busy",
            NodeStatus::Draining => "draining",
        }
    }
}

/// Distributed job representation
#[derive(Debug, Clone)]
struct DistributedJob {
    id: String,
    name: String,
    task: String,
    node_id: Option<String>,
    status: JobStatus,
    priority: i32,
    created_at: std::time::Instant,
    started_at: Option<std::time::Instant>,
    completed_at: Option<std::time::Instant>,
}

#[derive(Debug, Clone, PartialEq)]
enum JobStatus {
    Pending,
    Running,
    Completed,
    Failed(String),
    Cancelled,
}

impl JobStatus {
    fn as_str(&self) -> &str {
        match self {
            JobStatus::Pending => "pending",
            JobStatus::Running => "running",
            JobStatus::Completed => "completed",
            JobStatus::Failed(_) => "failed",
            JobStatus::Cancelled => "cancelled",
        }
    }
}

// ===================== Cloud & Scale Types =====================

/// Cloud platform configuration
#[derive(Debug, Clone)]
struct CloudConfig {
    provider: String,
    region: String,
    api_endpoint: Option<String>,
    default_instance_type: String,
}

/// Remote REPL session
#[derive(Debug, Clone)]
struct ReplSession {
    id: String,
    host: String,
    port: u16,
    user: String,
    connected_at: String,
    status: String,
    workspace_id: Option<String>,
}

/// Team workspace
#[derive(Debug, Clone)]
struct TeamWorkspace {
    id: String,
    name: String,
    owner: String,
    members: Vec<WorkspaceMember>,
    shared_agents: Vec<String>,
    created_at: String,
    description: String,
}

/// Workspace member
#[derive(Debug, Clone)]
struct WorkspaceMember {
    user: String,
    role: String,
    joined_at: String,
}

/// Marketplace package
#[derive(Debug, Clone)]
struct MarketplacePackage {
    name: String,
    version: String,
    author: String,
    description: String,
    category: String,
    downloads: i64,
    rating: f64,
    rating_count: i64,
    published_at: String,
    installed: bool,
    keywords: Vec<String>,
}

/// Telemetry event
#[derive(Debug, Clone)]
struct TelemetryEvent {
    id: String,
    event_type: String,
    category: String,
    data: HashMap<String, String>,
    timestamp: String,
    session_id: String,
}

// ===================== RAG Types =====================

/// RAG document chunk with simple embedding
#[derive(Debug, Clone)]
struct RagChunk {
    id: String,
    content: String,
    source: String,
    embedding: Vec<f32>,
    metadata: HashMap<String, String>,
}

/// RAG index for retrieval-augmented generation
#[derive(Debug)]
struct RagIndex {
    chunks: Vec<RagChunk>,
    dimension: usize,
}

impl RagIndex {
    fn new() -> Self {
        Self {
            chunks: Vec::new(),
            dimension: 384, // Default embedding dimension
        }
    }

    /// Simple word-frequency based embedding (for demo purposes)
    /// In production, use a proper embedding model
    fn simple_embed(&self, text: &str) -> Vec<f32> {
        let words: Vec<&str> = text.split_whitespace().collect();
        let mut embedding = vec![0.0f32; self.dimension];

        for (i, word) in words.iter().enumerate() {
            let hash = word
                .bytes()
                .fold(0u32, |acc, b| acc.wrapping_add(b as u32).wrapping_mul(31));
            let idx = (hash as usize) % self.dimension;
            embedding[idx] += 1.0 / (i + 1) as f32;
        }

        // Normalize
        let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for x in &mut embedding {
                *x /= norm;
            }
        }
        embedding
    }

    /// Cosine similarity between two embeddings
    fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
        if a.len() != b.len() {
            return 0.0;
        }
        let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
        let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
        let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm_a > 0.0 && norm_b > 0.0 {
            dot / (norm_a * norm_b)
        } else {
            0.0
        }
    }

    fn add_document(
        &mut self,
        content: &str,
        source: &str,
        metadata: HashMap<String, String>,
    ) -> String {
        let id = format!("doc_{}", self.chunks.len());
        let embedding = self.simple_embed(content);
        self.chunks.push(RagChunk {
            id: id.clone(),
            content: content.to_string(),
            source: source.to_string(),
            embedding,
            metadata,
        });
        id
    }

    fn search(&self, query: &str, top_k: usize) -> Vec<(&RagChunk, f32)> {
        let query_embedding = self.simple_embed(query);
        let mut results: Vec<(&RagChunk, f32)> = self
            .chunks
            .iter()
            .map(|chunk| {
                let score = Self::cosine_similarity(&query_embedding, &chunk.embedding);
                (chunk, score)
            })
            .collect();

        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        results.into_iter().take(top_k).collect()
    }

    fn clear(&mut self) {
        self.chunks.clear();
    }
}

// ===================== Knowledge Graph Types =====================

/// Entity in the knowledge graph
#[derive(Debug, Clone)]
struct KgEntity {
    id: String,
    entity_type: String,
    name: String,
    properties: HashMap<String, String>,
}

/// Relation between entities
#[derive(Debug, Clone)]
struct KgRelation {
    id: String,
    source_id: String,
    target_id: String,
    relation_type: String,
    properties: HashMap<String, String>,
}

/// Knowledge graph storage
#[derive(Debug)]
struct KnowledgeGraph {
    entities: HashMap<String, KgEntity>,
    relations: Vec<KgRelation>,
    next_entity_id: usize,
    next_relation_id: usize,
}

impl KnowledgeGraph {
    fn new() -> Self {
        Self {
            entities: HashMap::new(),
            relations: Vec::new(),
            next_entity_id: 0,
            next_relation_id: 0,
        }
    }

    fn add_entity(
        &mut self,
        entity_type: &str,
        name: &str,
        properties: HashMap<String, String>,
    ) -> String {
        let id = format!("e_{}", self.next_entity_id);
        self.next_entity_id += 1;
        self.entities.insert(
            id.clone(),
            KgEntity {
                id: id.clone(),
                entity_type: entity_type.to_string(),
                name: name.to_string(),
                properties,
            },
        );
        id
    }

    fn add_relation(
        &mut self,
        source_id: &str,
        target_id: &str,
        relation_type: &str,
        properties: HashMap<String, String>,
    ) -> Result<String> {
        if !self.entities.contains_key(source_id) {
            return Err(crate::safety::not_found(
                "kg_relate",
                "source entity",
                source_id,
            ));
        }
        if !self.entities.contains_key(target_id) {
            return Err(crate::safety::not_found(
                "kg_relate",
                "target entity",
                target_id,
            ));
        }

        let id = format!("r_{}", self.next_relation_id);
        self.next_relation_id += 1;
        self.relations.push(KgRelation {
            id: id.clone(),
            source_id: source_id.to_string(),
            target_id: target_id.to_string(),
            relation_type: relation_type.to_string(),
            properties,
        });
        Ok(id)
    }

    fn query(&self, pattern: &str) -> Vec<Value> {
        let mut results = Vec::new();
        let pattern_lower = pattern.to_lowercase();

        // Search entities
        for entity in self.entities.values() {
            if entity.name.to_lowercase().contains(&pattern_lower)
                || entity.entity_type.to_lowercase().contains(&pattern_lower)
            {
                let mut record = BTreeMap::new();
                record.insert("id".to_string(), Value::Str(entity.id.clone()));
                record.insert("type".to_string(), Value::Str("entity".to_string()));
                record.insert(
                    "entity_type".to_string(),
                    Value::Str(entity.entity_type.clone()),
                );
                record.insert("name".to_string(), Value::Str(entity.name.clone()));
                results.push(Value::Record(record));
            }
        }

        // Search relations
        for relation in &self.relations {
            if relation
                .relation_type
                .to_lowercase()
                .contains(&pattern_lower)
            {
                let mut record = BTreeMap::new();
                record.insert("id".to_string(), Value::Str(relation.id.clone()));
                record.insert("type".to_string(), Value::Str("relation".to_string()));
                record.insert(
                    "relation_type".to_string(),
                    Value::Str(relation.relation_type.clone()),
                );
                record.insert("source".to_string(), Value::Str(relation.source_id.clone()));
                record.insert("target".to_string(), Value::Str(relation.target_id.clone()));
                results.push(Value::Record(record));
            }
        }

        results
    }
}

// ===================== Semantic Cache Types =====================

/// Cached AI response with embedding
#[derive(Debug, Clone)]
struct CachedResponse {
    query: String,
    response: String,
    embedding: Vec<f32>,
    created_at: std::time::Instant,
    hit_count: usize,
}

/// Semantic cache for AI responses
#[derive(Debug)]
struct SemanticCache {
    entries: Vec<CachedResponse>,
    max_entries: usize,
    similarity_threshold: f32,
    ttl_seconds: u64,
}

impl SemanticCache {
    fn new() -> Self {
        Self {
            entries: Vec::new(),
            max_entries: 1000,
            similarity_threshold: 0.85,
            ttl_seconds: 3600, // 1 hour default TTL
        }
    }

    /// Simple embedding for cache lookups
    fn simple_embed(&self, text: &str) -> Vec<f32> {
        let dimension = 128;
        let words: Vec<&str> = text.split_whitespace().collect();
        let mut embedding = vec![0.0f32; dimension];

        for (i, word) in words.iter().enumerate() {
            let hash = word
                .bytes()
                .fold(0u32, |acc, b| acc.wrapping_add(b as u32).wrapping_mul(31));
            let idx = (hash as usize) % dimension;
            embedding[idx] += 1.0 / (i + 1) as f32;
        }

        let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for x in &mut embedding {
                *x /= norm;
            }
        }
        embedding
    }

    fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
        if a.len() != b.len() {
            return 0.0;
        }
        let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
        let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
        let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm_a > 0.0 && norm_b > 0.0 {
            dot / (norm_a * norm_b)
        } else {
            0.0
        }
    }

    fn get(&mut self, query: &str) -> Option<String> {
        let query_embedding = self.simple_embed(query);
        let now = std::time::Instant::now();

        // Clean up expired entries
        self.entries
            .retain(|e| now.duration_since(e.created_at).as_secs() < self.ttl_seconds);

        // Find best match
        let mut best_match: Option<(usize, f32)> = None;
        for (i, entry) in self.entries.iter().enumerate() {
            let similarity = Self::cosine_similarity(&query_embedding, &entry.embedding);
            if similarity >= self.similarity_threshold
                && (best_match.is_none() || similarity > best_match.unwrap().1)
            {
                best_match = Some((i, similarity));
            }
        }

        if let Some((idx, _)) = best_match {
            self.entries[idx].hit_count += 1;
            return Some(self.entries[idx].response.clone());
        }

        None
    }

    fn put(&mut self, query: &str, response: &str) {
        let embedding = self.simple_embed(query);

        // Evict oldest entries if at capacity
        while self.entries.len() >= self.max_entries {
            self.entries.remove(0);
        }

        self.entries.push(CachedResponse {
            query: query.to_string(),
            response: response.to_string(),
            embedding,
            created_at: std::time::Instant::now(),
            hit_count: 0,
        });
    }

    fn clear(&mut self) {
        self.entries.clear();
    }

    fn stats(&self) -> (usize, usize) {
        let total_hits: usize = self.entries.iter().map(|e| e.hit_count).sum();
        (self.entries.len(), total_hits)
    }
}

// ===================== Enterprise Types =====================

/// RBAC Role definition
#[derive(Debug, Clone)]
struct Role {
    name: String,
    permissions: Vec<Permission>,
    description: String,
    created_at: std::time::Instant,
}

/// Permission definition
#[derive(Debug, Clone)]
struct Permission {
    resource: String,
    actions: Vec<String>,
}

/// Audit log entry
#[derive(Debug, Clone)]
struct AuditEntry {
    id: String,
    timestamp: std::time::Instant,
    user: String,
    action: String,
    resource: String,
    details: String,
    severity: AuditSeverity,
    success: bool,
}

#[derive(Debug, Clone)]
enum AuditSeverity {
    Info,
    Warning,
    Critical,
}

impl AuditSeverity {
    fn as_str(&self) -> &'static str {
        match self {
            AuditSeverity::Info => "info",
            AuditSeverity::Warning => "warning",
            AuditSeverity::Critical => "critical",
        }
    }
}

/// SSO Provider types
#[derive(Debug, Clone)]
enum SsoProvider {
    OAuth2,
    SAML,
    OIDC,
}

impl SsoProvider {
    fn as_str(&self) -> &'static str {
        match self {
            SsoProvider::OAuth2 => "oauth2",
            SsoProvider::SAML => "saml",
            SsoProvider::OIDC => "oidc",
        }
    }

    fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "oauth2" => Some(SsoProvider::OAuth2),
            "saml" => Some(SsoProvider::SAML),
            "oidc" => Some(SsoProvider::OIDC),
            _ => None,
        }
    }
}

/// SSO Configuration
#[derive(Debug, Clone)]
struct SsoConfig {
    provider: SsoProvider,
    client_id: String,
    issuer_url: String,
    enabled: bool,
}

/// Compliance standards
#[derive(Debug, Clone)]
enum ComplianceStandard {
    GDPR,
    HIPAA,
    SOC2,
    PCI,
}

impl ComplianceStandard {
    fn from_str(s: &str) -> Option<Self> {
        match s.to_uppercase().as_str() {
            "GDPR" => Some(ComplianceStandard::GDPR),
            "HIPAA" => Some(ComplianceStandard::HIPAA),
            "SOC2" => Some(ComplianceStandard::SOC2),
            "PCI" => Some(ComplianceStandard::PCI),
            _ => None,
        }
    }

    fn as_str(&self) -> &'static str {
        match self {
            ComplianceStandard::GDPR => "GDPR",
            ComplianceStandard::HIPAA => "HIPAA",
            ComplianceStandard::SOC2 => "SOC2",
            ComplianceStandard::PCI => "PCI",
        }
    }
}

/// Fine-tuning job
#[derive(Debug, Clone)]
struct FinetuneJob {
    id: String,
    model: String,
    dataset: String,
    status: FinetuneStatus,
    created_at: std::time::Instant,
    config: HashMap<String, String>,
}

/// Fine-tuning status
#[derive(Debug, Clone)]
enum FinetuneStatus {
    Pending,
    Training,
    Completed,
    Failed(String),
    Cancelled,
}

impl FinetuneStatus {
    fn as_str(&self) -> &str {
        match self {
            FinetuneStatus::Pending => "pending",
            FinetuneStatus::Training => "training",
            FinetuneStatus::Completed => "completed",
            FinetuneStatus::Failed(_) => "failed",
            FinetuneStatus::Cancelled => "cancelled",
        }
    }
}

// Fast dispatch table for builtin functions
static BUILTIN_DISPATCH: &[fn(Vec<Value>, Option<Value>, &mut Env) -> Result<Value>] = &[
    // 0-9: General and file system functions
    // help() is the short reference; help("name") is ontology_describe("name").
    |args, _, _| bi_help_entry(args),
    |args, input, env| bi_call(args, input, env),
    |_, _, _| bi_clear(),
    |args, input, _| bi_echo(&args, input),
    |args, input, _| bi_print(args, input),
    |args, input, _| bi_http_get(args, input),
    |args, _, _| bi_some(args),
    |_, _, _| bi_none(),
    |args, input, _| bi_ls(args, input),
    |_, _, _| bi_pwd(),
    // 10-19: File operations and data functions
    |args, input, _| bi_cat(args, input),
    |args, input, _| bi_read_text(args, input),
    |args, input, _| bi_head(args, input),
    |args, input, _| bi_tail(args, input),
    |args, input, _| bi_find(args, input),
    |args, input, _| bi_sort(args, input),
    |args, input, _| bi_uniq(args, input),
    |args, input, _| bi_wc(args, input),
    |args, input, _| bi_grep(args, input),
    |args, input, env| bi_map(args, input, env),
    // 20-29: Pipeline and array functions
    |args, input, env| bi_where(args, input, env),
    |args, input, env| bi_reduce(args, input, env),
    |args, input, _| bi_take(args, input),
    |args, input, _| bi_keys(args, input),
    |args, input, _| bi_len(args, input),
    |args, input, _| bi_type_of(args, input),
    |args, input, _| bi_first(args, input),
    |args, input, _| bi_last(args, input),
    |args, input, env| bi_any(args, input, env),
    |args, input, env| bi_all(args, input, env),
    // 30-33: MCP functions
    |args, input, _| bi_mcp_servers(args, input),
    |args, input, _| bi_mcp_detect(args, input),
    |args, input, _| bi_mcp_cache_clear(args, input),
    |args, input, _| bi_mcp_cache_status(args, input),
    // 34-42: String functions
    |args, input, _| bi_split(args, input),
    |args, input, _| bi_join(args, input),
    |args, input, _| bi_trim(args, input),
    |args, input, _| bi_upper(args, input),
    |args, input, _| bi_lower(args, input),
    |args, input, _| bi_replace(args, input),
    |args, input, _| bi_contains(args, input),
    |args, input, _| bi_starts_with(args, input),
    |args, input, _| bi_ends_with(args, input),
    // 43-49: Array functions (extended)
    |args, input, _| bi_flatten(args, input),
    |args, input, _| bi_reverse(args, input),
    |args, input, _| bi_slice(args, input),
    |args, input, _| bi_range(args, input),
    |args, input, _| bi_zip(args, input),
    |args, input, _| bi_push(args, input),
    |args, input, _| bi_concat(args, input),
    // 50-57: Math functions
    |args, input, _| bi_abs(args, input),
    |args, input, _| bi_min(args, input),
    |args, input, _| bi_max(args, input),
    |args, input, _| bi_floor(args, input),
    |args, input, _| bi_ceil(args, input),
    |args, input, _| bi_round(args, input),
    |args, input, _| bi_sqrt(args, input),
    |args, input, _| bi_pow(args, input),
    // 58-64: Utility functions
    |args, input, _| bi_exit(args, input),
    |args, input, _| bi_env(args, input),
    |args, input, _| bi_set_env(args, input),
    |args, input, _| bi_sleep(args, input),
    |args, input, _| bi_time(args, input),
    |args, input, _| bi_json_parse(args, input),
    |args, input, _| bi_json_stringify(args, input),
    // 65-71: Syntax Knowledge Base functions
    |args, input, _| bi_syntax_get(args, input),
    |args, input, _| bi_syntax_list(args, input),
    |args, input, _| bi_syntax_search(args, input),
    |args, input, _| bi_syntax_add(args, input),
    |args, input, _| bi_syntax_categories(args, input),
    |args, input, _| bi_ab_encode(args, input),
    |args, input, _| bi_ab_decode(args, input),
    // 72-82: Neural Network functions
    |args, input, _| bi_nn_create(args, input),
    |args, input, _| bi_nn_forward(args, input),
    |args, input, _| bi_nn_mutate(args, input),
    |args, input, _| bi_nn_crossover(args, input),
    |args, input, _| bi_nn_params(args, input),
    |args, input, _| bi_nn_set_params(args, input),
    |args, input, _| bi_nn_layers(args, input),
    |args, input, _| bi_nn_info(args, input),
    |args, input, _| bi_consensus_net(args, input),
    |args, input, _| bi_consensus_vote(args, input),
    |args, input, _| bi_activation(args, input),
    // 83-92: Evolution functions
    |args, input, env| bi_population(args, input, env),
    |args, input, env| bi_evolve(args, input, env),
    |args, input, env| bi_evolve_step(args, input, env),
    |args, input, env| bi_fitness(args, input, env),
    |args, input, _| bi_best_individual(args, input),
    |args, input, _| bi_evolution_stats(args, input),
    |args, input, _| bi_selection_strategy(args, input),
    |args, input, _| bi_crossover_strategy(args, input),
    |args, input, _| bi_evolution_config(args, input),
    |args, input, env| bi_coevolve(args, input, env),
    // 93-107: Reinforcement Learning functions
    |args, input, _| bi_rl_agent(args, input),
    |args, input, _| bi_rl_action(args, input),
    |args, input, _| bi_rl_update(args, input),
    |args, input, _| bi_rl_sarsa_agent(args, input),
    |args, input, _| bi_rl_sarsa_update(args, input),
    |args, input, _| bi_rl_pg_agent(args, input),
    |args, input, _| bi_rl_pg_step(args, input),
    |args, input, _| bi_rl_pg_episode_end(args, input),
    |args, input, _| bi_rl_ac_agent(args, input),
    |args, input, _| bi_rl_ac_update(args, input),
    |args, input, _| bi_rl_dqn_agent(args, input),
    |args, input, _| bi_rl_dqn_step(args, input),
    |args, input, _| bi_rl_replay_buffer(args, input),
    |args, input, _| bi_rl_gridworld(args, input),
    |args, input, _| bi_rl_env_step(args, input),
    // 108-112: OS Tools functions
    |args, input, _| bi_tools(args, input),
    |args, input, _| bi_tool_info(args, input),
    |args, input, _| bi_tool_schema(args, input),
    |args, input, _| bi_tool_exec(args, input),
    |args, input, _| bi_tool_search(args, input),
    // 113-116: Recursive Language Model functions
    |args, input, env| bi_rlm_agent(args, input, env),
    |args, input, _| bi_rlm_config(args, input),
    |args, input, _| bi_rlm_stats(args, input),
    |args, input, env| bi_rlm_spawn(args, input, env),
    // 117-122: MCP Server/Client functions
    |args, input, _| bi_mcp_server(args, input),
    |args, input, _| bi_mcp_tools(args, input),
    |args, input, _| bi_mcp_call(args, input),
    |args, input, _| bi_mcp_resources(args, input),
    |args, input, _| bi_mcp_prompts(args, input),
    |args, input, _| bi_mcp_connect(args, input),
    // 123-131: New aspirational features
    |args, input, _| bi_sh(args, input),
    |args, input, _| bi_now(args, input),
    |args, input, env| bi_sort_by(args, input, env),
    |args, input, _| bi_save_json(args, input),
    |args, input, _| bi_ai_backends(args, input),
    |args, input, _| bi_mcp_server_start(args, input),
    |args, input, env| bi_agent_with_mcp(args, input, env),
    |args, input, env| bi_each(args, input, env),
    |args, input, _| bi_in(args, input),
    // 132-136: Additional utility functions
    |args, input, _| bi_values(args, input),
    |args, input, _| bi_sum(args, input),
    |args, input, _| bi_unique(args, input),
    |args, input, _| bi_avg(args, input),
    |args, input, _| bi_product(args, input),
    // 137-142: Configuration functions
    |args, input, _| bi_config(args, input),
    |args, input, _| bi_config_get(args, input),
    |args, input, _| bi_config_set(args, input),
    |_, _, _| bi_config_path(),
    |args, input, _| bi_config_init(args, input),
    |_, _, _| bi_config_reload(),
    |_, _, _| bi_themes(),
    // 144-150: Plugin functions
    |args, input, _| bi_plugins(args, input),
    |args, input, _| bi_plugin_info(args, input),
    |args, input, _| bi_plugin_enable(args, input),
    |args, input, _| bi_plugin_disable(args, input),
    |args, input, _| bi_plugin_load(args, input),
    |args, input, _| bi_plugin_unload(args, input),
    |_, _, _| bi_plugin_categories(),
    // 151: Error handling functions
    |args, input, _| bi_is_error(args, input),
    // 152-156: Debugging tools
    |args, input, _| bi_debug(args, input),
    |args, input, _| bi_assert(args, input),
    |args, input, _| bi_trace(args, input),
    |args, input, _| bi_type_assert(args, input),
    |args, input, _| bi_inspect(args, input),
    // 157-163: Platform detection functions
    |_, _, _| bi_platform(),
    |_, _, _| bi_is_windows(),
    |_, _, _| bi_is_linux(),
    |_, _, _| bi_is_macos(),
    |_, _, _| bi_is_unix(),
    |_, _, _| bi_is_bsd(),
    |args, input, _| bi_platform_module(args, input),
    // 164-168: Feature flag functions
    |_, _, _| bi_features(),
    |args, input, _| bi_feature_enabled(args, input),
    |args, input, _| bi_feature_enable(args, input),
    |args, input, _| bi_feature_disable(args, input),
    |args, input, _| bi_feature_set(args, input),
    // 169-180: Distributed Computing functions
    |args, input, _| bi_cluster_create(args, input),
    |args, input, _| bi_cluster_add_node(args, input),
    |args, input, _| bi_cluster_remove_node(args, input),
    |args, input, _| bi_cluster_status(args, input),
    |args, input, _| bi_cluster_nodes(args, input),
    |args, input, _| bi_job_submit(args, input),
    |args, input, _| bi_job_status(args, input),
    |args, input, _| bi_job_cancel(args, input),
    |args, input, _| bi_job_results(args, input),
    |args, input, _| bi_job_list(args, input),
    |args, input, _| bi_remote_exec(args, input),
    |args, input, _| bi_aggregate_results(args, input),
    // 181-192: Advanced AI functions
    |args, input, _| bi_rag_index(args, input),
    |args, input, _| bi_rag_search(args, input),
    |args, input, _| bi_rag_query(args, input),
    |args, input, _| bi_rag_clear(args, input),
    |args, input, _| bi_kg_add(args, input),
    |args, input, _| bi_kg_relate(args, input),
    |args, input, _| bi_kg_query(args, input),
    |args, input, _| bi_kg_entities(args, input),
    |args, input, _| bi_kg_relations(args, input),
    |args, input, _| bi_semantic_cache(args, input),
    |args, input, _| bi_semantic_cache_get(args, input),
    |args, input, _| bi_semantic_cache_clear(args, input),
    // 193-199: RBAC functions
    |args, input, _| bi_role_create(args, input),
    |args, input, _| bi_role_delete(args, input),
    |args, input, _| bi_role_grant(args, input),
    |args, input, _| bi_role_revoke(args, input),
    |args, input, _| bi_user_roles(args, input),
    |args, input, _| bi_check_permission(args, input),
    |args, input, _| bi_roles_list(args, input),
    // 200-203: Audit functions
    |args, input, _| bi_audit_log(args, input),
    |args, input, _| bi_audit_query(args, input),
    |args, input, _| bi_audit_export(args, input),
    |args, input, _| bi_audit_stats(args, input),
    // 204-208: SSO functions
    |args, input, _| bi_sso_init(args, input),
    |args, input, _| bi_sso_auth(args, input),
    |args, input, _| bi_sso_validate(args, input),
    |args, input, _| bi_sso_logout(args, input),
    |args, input, _| bi_sso_status(args, input),
    // 209-210: Compliance functions
    |args, input, _| bi_compliance_check(args, input),
    |args, input, _| bi_compliance_report(args, input),
    // 211-214: Fine-tuning functions
    |args, input, _| bi_finetune_start(args, input),
    |args, input, _| bi_finetune_status(args, input),
    |args, input, _| bi_finetune_list(args, input),
    |args, input, _| bi_finetune_cancel(args, input),
    // 215-229: A2UI (Agent-to-User Interface) functions
    |args, input, _| bi_a2ui_notify(args, input),
    |args, input, _| bi_a2ui_prompt(args, input),
    |args, input, _| bi_a2ui_confirm(args, input),
    |args, input, _| bi_a2ui_select(args, input),
    |args, input, _| bi_a2ui_progress(args, input),
    |args, input, _| bi_a2ui_progress_complete(args, input),
    |args, input, _| bi_a2ui_render(args, input),
    |args, input, _| bi_a2ui_render_table(args, input),
    |args, input, _| bi_a2ui_render_code(args, input),
    |args, input, _| bi_a2ui_toast(args, input),
    |args, input, _| bi_a2ui_status(args, input),
    |args, input, _| bi_a2ui_clear(args, input),
    |args, input, _| bi_a2ui_agent_started(args, input),
    |args, input, _| bi_a2ui_agent_completed(args, input),
    |args, input, _| bi_a2ui_agent_thinking(args, input),
    // 230-249: Process Management
    |args, input, _| bi_proc_list(args, input),
    |args, input, _| bi_proc_kill(args, input),
    |args, input, _| bi_proc_info(args, input),
    |args, input, _| bi_proc_spawn(args, input),
    |args, input, _| bi_proc_wait(args, input),
    |args, input, _| bi_proc_exists(args, input),
    |args, input, _| bi_proc_children(args, input),
    |args, input, _| bi_proc_parent(args, input),
    |args, input, _| bi_proc_priority(args, input),
    |args, input, _| bi_proc_set_priority(args, input),
    |args, input, _| bi_proc_cpu_usage(args, input),
    |args, input, _| bi_proc_mem_usage(args, input),
    |args, input, _| bi_proc_threads(args, input),
    |args, input, _| bi_proc_env(args, input),
    |args, input, _| bi_proc_cwd(args, input),
    |args, input, _| bi_proc_exe(args, input),
    |args, input, _| bi_proc_cmdline(args, input),
    |args, input, _| bi_proc_start_time(args, input),
    |args, input, _| bi_proc_suspend(args, input),
    |args, input, _| bi_proc_resume(args, input),
    // 250-269: Filesystem Extended
    |args, input, _| bi_fs_stat(args, input),
    |args, input, _| bi_fs_lstat(args, input),
    |args, input, _| bi_fs_chmod(args, input),
    |args, input, _| bi_fs_chown(args, input),
    |args, input, _| bi_fs_link(args, input),
    |args, input, _| bi_fs_symlink(args, input),
    |args, input, _| bi_fs_readlink(args, input),
    |args, input, _| bi_fs_realpath(args, input),
    |args, input, _| bi_fs_tempfile(args, input),
    |args, input, _| bi_fs_tempdir(args, input),
    |args, input, _| bi_fs_watch(args, input),
    |args, input, _| bi_fs_unwatch(args, input),
    |args, input, _| bi_fs_glob(args, input),
    |args, input, _| bi_fs_walk(args, input),
    |args, input, _| bi_fs_tree(args, input),
    |args, input, _| bi_fs_du(args, input),
    |args, input, _| bi_fs_df(args, input),
    |args, input, _| bi_fs_mount(args, input),
    |args, input, _| bi_fs_unmount(args, input),
    |args, input, _| bi_fs_mounts(args, input),
    // 270-289: Network Operations
    |args, input, _| bi_net_interfaces(args, input),
    |args, input, _| bi_net_ip(args, input),
    |args, input, _| bi_net_dns_lookup(args, input),
    |args, input, _| bi_net_dns_reverse(args, input),
    |args, input, _| bi_net_ping(args, input),
    |args, input, _| bi_net_traceroute(args, input),
    |args, input, _| bi_net_connections(args, input),
    |args, input, _| bi_net_listen(args, input),
    |args, input, _| bi_net_connect(args, input),
    |args, input, _| bi_net_send(args, input),
    |args, input, _| bi_net_recv(args, input),
    |args, input, _| bi_net_close(args, input),
    |args, input, _| bi_net_ports(args, input),
    |args, input, _| bi_net_arp(args, input),
    |args, input, _| bi_net_route(args, input),
    |args, input, _| bi_net_stats(args, input),
    |args, input, _| bi_net_bandwidth(args, input),
    |args, input, _| bi_net_latency(args, input),
    |args, input, _| bi_net_scan(args, input),
    |args, input, _| bi_net_whois(args, input),
    // 290-309: System Information
    |args, input, _| bi_sys_info(args, input),
    |args, input, _| bi_sys_hostname(args, input),
    |args, input, _| bi_sys_os(args, input),
    |args, input, _| bi_sys_arch(args, input),
    |args, input, _| bi_sys_kernel(args, input),
    |args, input, _| bi_sys_uptime(args, input),
    |args, input, _| bi_sys_boot_time(args, input),
    |args, input, _| bi_sys_cpu_info(args, input),
    |args, input, _| bi_sys_cpu_count(args, input),
    |args, input, _| bi_sys_cpu_freq(args, input),
    |args, input, _| bi_sys_mem_info(args, input),
    |args, input, _| bi_sys_swap_info(args, input),
    |args, input, _| bi_sys_disk_info(args, input),
    |args, input, _| bi_sys_load_avg(args, input),
    |args, input, _| bi_sys_users(args, input),
    |args, input, _| bi_sys_groups(args, input),
    |args, input, _| bi_sys_user_info(args, input),
    |args, input, _| bi_sys_env_all(args, input),
    |args, input, _| bi_sys_locale(args, input),
    |args, input, _| bi_sys_timezone(args, input),
    // 310-329: Service & Daemon Management
    |args, input, _| bi_svc_list(args, input),
    |args, input, _| bi_svc_status(args, input),
    |args, input, _| bi_svc_start(args, input),
    |args, input, _| bi_svc_stop(args, input),
    |args, input, _| bi_svc_restart(args, input),
    |args, input, _| bi_svc_enable(args, input),
    |args, input, _| bi_svc_disable(args, input),
    |args, input, _| bi_svc_logs(args, input),
    |args, input, _| bi_svc_info(args, input),
    |args, input, _| bi_svc_create(args, input),
    |args, input, _| bi_svc_delete(args, input),
    |args, input, _| bi_cron_list(args, input),
    |args, input, _| bi_cron_add(args, input),
    |args, input, _| bi_cron_remove(args, input),
    |args, input, _| bi_cron_enable(args, input),
    |args, input, _| bi_cron_disable(args, input),
    |args, input, _| bi_at_schedule(args, input),
    |args, input, _| bi_at_list(args, input),
    |args, input, _| bi_at_remove(args, input),
    |args, input, _| bi_startup_list(args, input),
    // 330-349: Archive & Compression
    |args, input, _| bi_zip_create(args, input),
    |args, input, _| bi_zip_extract(args, input),
    |args, input, _| bi_zip_list(args, input),
    |args, input, _| bi_zip_add(args, input),
    |args, input, _| bi_tar_create(args, input),
    |args, input, _| bi_tar_extract(args, input),
    |args, input, _| bi_tar_list(args, input),
    |args, input, _| bi_gzip_compress(args, input),
    |args, input, _| bi_gzip_decompress(args, input),
    |args, input, _| bi_bzip2_compress(args, input),
    |args, input, _| bi_bzip2_decompress(args, input),
    |args, input, _| bi_xz_compress(args, input),
    |args, input, _| bi_xz_decompress(args, input),
    |args, input, _| bi_zstd_compress(args, input),
    |args, input, _| bi_zstd_decompress(args, input),
    |args, input, _| bi_archive_info(args, input),
    |args, input, _| bi_archive_test(args, input),
    // 347-349: reserved slots. No name is registered at these indices, so
    // dispatch never reaches them; they keep the numbering of the entries after.
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // 350-369: User & Permission Management
    |args, input, _| bi_user_list(args, input),
    |args, input, _| bi_user_add(args, input),
    |args, input, _| bi_user_del(args, input),
    |args, input, _| bi_user_mod(args, input),
    |args, input, _| bi_user_passwd(args, input),
    |args, input, _| bi_user_lock(args, input),
    |args, input, _| bi_user_unlock(args, input),
    |args, input, _| bi_group_list(args, input),
    |args, input, _| bi_group_add(args, input),
    |args, input, _| bi_group_del(args, input),
    |args, input, _| bi_group_mod(args, input),
    |args, input, _| bi_group_members(args, input),
    |args, input, _| bi_perm_get(args, input),
    |args, input, _| bi_perm_set(args, input),
    |args, input, _| bi_perm_check(args, input),
    |args, input, _| bi_acl_get(args, input),
    |args, input, _| bi_acl_set(args, input),
    |args, input, _| bi_sudo_check(args, input),
    |args, input, _| bi_sudo_exec(args, input),
    |args, input, _| bi_capabilities(args, input),
    // 370-389: Package Management
    |args, input, _| bi_pkg_list(args, input),
    |args, input, _| bi_pkg_search(args, input),
    |args, input, _| bi_pkg_info(args, input),
    |args, input, _| bi_pkg_install(args, input),
    |args, input, _| bi_pkg_remove(args, input),
    |args, input, _| bi_pkg_update(args, input),
    |args, input, _| bi_pkg_upgrade(args, input),
    |args, input, _| bi_pkg_clean(args, input),
    |args, input, _| bi_pkg_sources(args, input),
    |args, input, _| bi_pkg_add_source(args, input),
    |args, input, _| bi_pkg_files(args, input),
    |args, input, _| bi_pkg_owner(args, input),
    |args, input, _| bi_pkg_verify(args, input),
    |args, input, _| bi_pkg_deps(args, input),
    |args, input, _| bi_pkg_rdeps(args, input),
    |args, input, _| bi_pkg_changelog(args, input),
    |args, input, _| bi_pkg_hold(args, input),
    |args, input, _| bi_pkg_unhold(args, input),
    |args, input, _| bi_pkg_autoremove(args, input),
    |args, input, _| bi_pkg_history(args, input),
    // 390-399: Hardware & Device Info
    |args, input, _| bi_hw_cpu(args, input),
    |args, input, _| bi_hw_memory(args, input),
    |args, input, _| bi_hw_disk(args, input),
    |args, input, _| bi_hw_gpu(args, input),
    |args, input, _| bi_hw_network(args, input),
    |args, input, _| bi_hw_usb(args, input),
    |args, input, _| bi_hw_pci(args, input),
    |args, input, _| bi_hw_audio(args, input),
    |args, input, _| bi_hw_battery(args, input),
    |args, input, _| bi_hw_sensors(args, input),
    // 400-429: GUI Automation
    |args, input, _| bi_gui_list_windows(args, input),
    |args, input, _| bi_gui_focus_window(args, input),
    |args, input, _| bi_gui_minimize_window(args, input),
    |args, input, _| bi_gui_maximize_window(args, input),
    |args, input, _| bi_gui_close_window(args, input),
    |args, input, _| bi_gui_move_window(args, input),
    |args, input, _| bi_gui_resize_window(args, input),
    |args, input, _| bi_gui_screenshot(args, input),
    |args, input, _| bi_gui_screenshot_window(args, input),
    |args, input, _| bi_gui_mouse_move(args, input),
    |args, input, _| bi_gui_mouse_click(args, input),
    |args, input, _| bi_gui_mouse_double_click(args, input),
    |args, input, _| bi_gui_mouse_drag(args, input),
    |args, input, _| bi_gui_mouse_scroll(args, input),
    |args, input, _| bi_gui_mouse_position(args, input),
    |args, input, _| bi_gui_key_press(args, input),
    |args, input, _| bi_gui_key_combo(args, input),
    |args, input, _| bi_gui_type_text(args, input),
    |args, input, _| bi_gui_get_active_window(args, input),
    |args, input, _| bi_gui_screen_size(args, input),
    |args, input, _| bi_gui_find_image(args, input),
    |args, input, _| bi_gui_ocr(args, input),
    |args, input, _| bi_gui_notify(args, input),
    |args, input, _| bi_gui_dialog_message(args, input),
    |args, input, _| bi_gui_dialog_input(args, input),
    |args, input, _| bi_gui_dialog_file_open(args, input),
    |args, input, _| bi_gui_dialog_file_save(args, input),
    |args, input, _| bi_gui_dialog_folder(args, input),
    |args, input, _| bi_gui_wait(args, input),
    |args, input, _| bi_gui_color_picker(args, input),
    // 430-459: Web Automation
    |args, input, _| bi_web_open_url(args, input),
    |args, input, _| bi_web_fetch(args, input),
    |args, input, _| bi_web_get(args, input),
    |args, input, _| bi_web_post(args, input),
    |args, input, _| bi_web_json_get(args, input),
    |args, input, _| bi_web_json_post(args, input),
    |args, input, _| bi_web_scrape(args, input),
    |args, input, _| bi_web_download(args, input),
    |args, input, _| bi_web_browser_open(args, input),
    |args, input, _| bi_web_parse_url(args, input),
    |args, input, _| bi_web_encode_url(args, input),
    |args, input, _| bi_web_decode_url(args, input),
    |args, input, _| bi_web_parse_query(args, input),
    |args, input, _| bi_web_build_query(args, input),
    |args, input, _| bi_web_headers(args, input),
    |args, input, _| bi_web_cookies(args, input),
    |args, input, _| bi_web_form_submit(args, input),
    |args, input, _| bi_web_upload_file(args, input),
    |args, input, _| bi_web_rest_api(args, input),
    |args, input, _| bi_web_websocket(args, input),
    |args, input, _| bi_web_graphql(args, input),
    |args, input, _| bi_web_check_url(args, input),
    |args, input, _| bi_web_robots_txt(args, input),
    |args, input, _| bi_web_sitemap(args, input),
    |args, input, _| bi_web_extract_emails(args, input),
    |args, input, _| bi_web_extract_phones(args, input),
    |args, input, _| bi_web_html_to_text(args, input),
    |args, input, _| bi_web_html_to_markdown(args, input),
    |args, input, _| bi_web_json_path(args, input),
    |args, input, _| bi_web_xpath(args, input),
    // 460-479: Clipboard & Input
    |args, input, _| bi_clipboard_get(args, input),
    |args, input, _| bi_clipboard_set(args, input),
    |args, input, _| bi_clipboard_clear(args, input),
    |args, input, _| bi_clipboard_has_text(args, input),
    |args, input, _| bi_clipboard_get_image(args, input),
    |args, input, _| bi_clipboard_set_image(args, input),
    |args, input, _| bi_clipboard_history(args, input),
    |args, input, _| bi_input_read_line(args, input),
    |args, input, _| bi_input_read_password(args, input),
    |args, input, _| bi_input_read_char(args, input),
    |args, input, _| bi_input_confirm(args, input),
    |args, input, _| bi_input_select(args, input),
    |args, input, _| bi_input_multiselect(args, input),
    |args, input, _| bi_input_editor(args, input),
    |args, input, _| bi_input_autocomplete(args, input),
    |args, input, _| bi_input_spinner(args, input),
    |args, input, _| bi_input_progress(args, input),
    |args, input, _| bi_input_table(args, input),
    |args, input, _| bi_input_form(args, input),
    |args, input, _| bi_input_date(args, input),
    // 480-499: Security & Crypto
    |args, input, _| bi_crypto_hash(args, input),
    |args, input, _| bi_crypto_hash_file(args, input),
    |args, input, _| bi_crypto_hmac(args, input),
    |args, input, _| bi_crypto_random_bytes(args, input),
    |args, input, _| bi_crypto_uuid(args, input),
    |args, input, _| bi_crypto_base64_encode(args, input),
    |args, input, _| bi_crypto_base64_decode(args, input),
    |args, input, _| bi_crypto_hex_encode(args, input),
    |args, input, _| bi_crypto_hex_decode(args, input),
    |args, input, _| bi_crypto_encrypt(args, input),
    |args, input, _| bi_crypto_decrypt(args, input),
    |args, input, _| bi_crypto_password_hash(args, input),
    |args, input, _| bi_crypto_password_verify(args, input),
    |args, input, _| bi_crypto_cert_info(args, input),
    |args, input, _| bi_crypto_cert_verify(args, input),
    |args, input, _| bi_crypto_generate_key(args, input),
    |args, input, _| bi_crypto_sign(args, input),
    |args, input, _| bi_crypto_verify_signature(args, input),
    |args, input, _| bi_crypto_checksum(args, input),
    |args, input, _| bi_crypto_jwt_decode(args, input),
    // 500-519: Database
    |args, input, _| bi_db_sqlite_open(args, input),
    |args, input, _| bi_db_sqlite_query(args, input),
    |args, input, _| bi_db_sqlite_exec(args, input),
    |args, input, _| bi_db_sqlite_tables(args, input),
    |args, input, _| bi_db_sqlite_schema(args, input),
    |args, input, _| bi_db_sqlite_insert(args, input),
    |args, input, _| bi_db_sqlite_update(args, input),
    |args, input, _| bi_db_sqlite_delete(args, input),
    |args, input, _| bi_db_sqlite_count(args, input),
    |args, input, _| bi_db_sqlite_create_table(args, input),
    |args, input, _| bi_db_sqlite_drop_table(args, input),
    |args, input, _| bi_db_sqlite_backup(args, input),
    |args, input, _| bi_db_sqlite_vacuum(args, input),
    |args, input, _| bi_db_sqlite_dump(args, input),
    |args, input, _| bi_db_sqlite_import(args, input),
    |args, input, _| bi_db_csv_to_sqlite(args, input),
    |args, input, _| bi_db_sqlite_to_csv(args, input),
    |args, input, _| bi_db_json_to_sqlite(args, input),
    |args, input, _| bi_db_sqlite_to_json(args, input),
    |args, input, _| bi_db_kv_store(args, input),
    // 520-527: File Editing (for AI agents)
    |args, input, _| bi_file_write(args, input),
    |args, input, _| bi_file_append(args, input),
    |args, input, _| bi_file_patch(args, input),
    |args, input, _| bi_file_replace(args, input),
    |args, input, _| bi_file_insert(args, input),
    |args, input, _| bi_file_delete_lines(args, input),
    |args, input, _| bi_file_edit(args, input),
    |args, input, _| bi_file_diff(args, input),
    // 528-532: Additional file operations
    |args, input, _| bi_file_backup(args, input),
    |args, input, _| bi_file_copy(args, input),
    |args, input, _| bi_file_move(args, input),
    |args, input, _| bi_file_exists(args, input),
    // 532: `mkdir` / `mkdirp` / `file_mkdir`.
    //
    // This slot was a placeholder, and the three names were registered into it —
    // the comment below said the reserved range began at 533 when the first
    // placeholder was at 532, an off-by-one that put an advertised builtin on a
    // stub. `mkdir` returned `Ok(Value::Null)` for every input and created
    // nothing, while `bi_file_mkdir` sat in the file fully written and never
    // referenced.
    //
    // Nothing caught it. `catalog_reachability` asks whether an advertised name
    // dispatches, and this one did — to `|_, _, _| Ok(Value::Null)`. A silent
    // no-op is worse than a missing builtin, because the caller is handed a
    // success value.
    |args, input, _| bi_file_mkdir(args, input),
    // 533-539: Reserved/placeholder
    |_, _, _| Ok(Value::Null),
    |_, _, _| Ok(Value::Null),
    |_, _, _| Ok(Value::Null),
    |_, _, _| Ok(Value::Null),
    |_, _, _| Ok(Value::Null),
    |_, _, _| Ok(Value::Null),
    // 540-547: A2A (Agent-to-Agent) Protocol
    |args, input, _| bi_a2a_send(args, input),
    |args, input, _| bi_a2a_receive(args, input),
    |args, input, _| bi_a2a_broadcast(args, input),
    |args, input, _| bi_a2a_discover(args, input),
    |args, input, _| bi_a2a_register(args, input),
    |args, input, _| bi_a2a_unregister(args, input),
    |args, input, _| bi_a2a_status(args, input),
    |args, input, _| bi_a2a_agents(args, input),
    // 548-549: Reserved
    |_, _, _| Ok(Value::Null),
    |_, _, _| Ok(Value::Null),
    // 550-556: NANDA (Consensus) Protocol
    |args, input, _| bi_nanda_propose(args, input),
    |args, input, _| bi_nanda_vote(args, input),
    |args, input, _| bi_nanda_commit(args, input),
    |args, input, _| bi_nanda_abort(args, input),
    |args, input, _| bi_nanda_status(args, input),
    |args, input, _| bi_nanda_consensus(args, input),
    |args, input, _| bi_nanda_quorum(args, input),
    // 556: tmux_kill (a reserved slot). Reserved (557-559)
    |args, input, _| bi_tmux_kill(args, input), // 556
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Git (560-586)
    |args, input, _| bi_git_status(args, input),
    |args, input, _| bi_git_diff(args, input),
    |args, input, _| bi_git_diff_staged(args, input),
    |args, input, _| bi_git_log(args, input),
    |args, input, _| bi_git_blame(args, input),
    |args, input, _| bi_git_branch(args, input),
    |args, input, _| bi_git_branches(args, input),
    |args, input, _| bi_git_checkout(args, input),
    |args, input, _| bi_git_commit(args, input),
    |args, input, _| bi_git_add(args, input),
    |args, input, _| bi_git_reset(args, input),
    |args, input, _| bi_git_stash(args, input),
    |args, input, _| bi_git_stash_pop(args, input),
    |args, input, _| bi_git_stash_list(args, input),
    |args, input, _| bi_git_remote(args, input),
    |args, input, _| bi_git_fetch(args, input),
    |args, input, _| bi_git_pull(args, input),
    |args, input, _| bi_git_push(args, input),
    |args, input, _| bi_git_merge(args, input),
    |args, input, _| bi_git_rebase(args, input),
    |args, input, _| bi_git_cherry_pick(args, input),
    |args, input, _| bi_git_tags(args, input),
    |args, input, _| bi_git_show(args, input),
    |args, input, _| bi_git_rev_parse(args, input),
    |args, input, _| bi_git_root(args, input),
    |args, input, _| bi_git_ignore(args, input),
    |args, input, _| bi_git_clean(args, input),
    // Reserved (587-589)
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Code (590-606)
    |args, input, _| bi_code_parse(args, input),
    |args, input, _| bi_code_symbols(args, input),
    |args, input, _| bi_code_outline(args, input),
    |args, input, _| bi_code_references(args, input),
    |args, input, _| bi_code_definition(args, input),
    |args, input, _| bi_code_imports(args, input),
    |args, input, _| bi_code_exports(args, input),
    |args, input, _| bi_code_dependencies(args, input),
    |args, input, _| bi_code_callers(args, input),
    |args, input, _| bi_code_callees(args, input),
    |args, input, _| bi_code_hover(args, input),
    |args, input, _| bi_code_signature(args, input),
    |args, input, _| bi_code_completions(args, input),
    |args, input, _| bi_code_format(args, input),
    |args, input, _| bi_code_language(args, input),
    |args, input, _| bi_code_comments(args, input),
    |args, input, _| bi_code_todos(args, input),
    // Reserved (607-609)
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Project (610-626)
    |args, input, _| bi_project_type(args, input),
    |args, input, _| bi_project_root(args, input),
    |args, input, _| bi_project_name(args, input),
    |args, input, _| bi_project_version(args, input),
    |args, input, _| bi_project_dependencies(args, input),
    |args, input, _| bi_project_dev_dependencies(args, input),
    |args, input, _| bi_project_scripts(args, input),
    |args, input, _| bi_project_structure(args, input),
    |args, input, _| bi_project_entry_points(args, input),
    |args, input, _| bi_project_test_files(args, input),
    |args, input, _| bi_project_config_files(args, input),
    |args, input, _| bi_project_readme(args, input),
    |args, input, _| bi_project_license(args, input),
    |args, input, _| bi_project_gitignore(args, input),
    |args, input, _| bi_project_languages(args, input),
    |args, input, _| bi_project_loc(args, input),
    |args, input, _| bi_project_size(args, input),
    // Reserved (627-629)
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Search (630-643)
    |args, input, _| bi_search_code(args, input),
    |args, input, _| bi_search_grep(args, input),
    |args, input, _| bi_search_regex(args, input),
    |args, input, _| bi_search_symbols(args, input),
    |args, input, _| bi_search_files(args, input),
    |args, input, _| bi_search_recent(args, input),
    |args, input, _| bi_search_modified(args, input),
    |args, input, _| bi_search_by_type(args, input),
    |args, input, _| bi_search_by_size(args, input),
    |args, input, _| bi_search_duplicates(args, input),
    |args, input, _| bi_search_todos(args, input),
    |args, input, _| bi_search_fixmes(args, input),
    |args, input, _| bi_search_semantic(args, input),
    |args, input, _| bi_search_similar(args, input),
    // Reserved (644-649)
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Test (650-661)
    |args, input, _| bi_test_run(args, input),
    |args, input, _| bi_test_run_file(args, input),
    |args, input, _| bi_test_run_function(args, input),
    |args, input, _| bi_test_list(args, input),
    |args, input, _| bi_test_coverage(args, input),
    |args, input, _| bi_test_failing(args, input),
    |args, input, _| bi_test_passing(args, input),
    |args, input, _| bi_test_skipped(args, input),
    |args, input, _| bi_test_watch(args, input),
    |args, input, _| bi_test_bench(args, input),
    |args, input, _| bi_test_snapshot(args, input),
    |args, input, _| bi_test_generate(args, input),
    // Reserved (662-669)
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Diagnostics (670-678)
    |args, input, _| bi_diag_check(args, input),
    |args, input, _| bi_diag_lint(args, input),
    |args, input, _| bi_diag_errors(args, input),
    |args, input, _| bi_diag_warnings(args, input),
    |args, input, _| bi_diag_all(args, input),
    |args, input, _| bi_diag_fix(args, input),
    |args, input, _| bi_diag_explain(args, input),
    |args, input, _| bi_diag_suppress(args, input),
    |args, input, _| bi_diag_config(args, input),
    // Reserved (679)
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Refactor (680-691)
    |args, input, _| bi_refactor_rename(args, input),
    |args, input, _| bi_refactor_rename_file(args, input),
    |args, input, _| bi_refactor_extract_function(args, input),
    |args, input, _| bi_refactor_extract_variable(args, input),
    |args, input, _| bi_refactor_extract_constant(args, input),
    |args, input, _| bi_refactor_inline(args, input),
    |args, input, _| bi_refactor_move_to_file(args, input),
    |args, input, _| bi_refactor_change_signature(args, input),
    |args, input, _| bi_refactor_add_parameter(args, input),
    |args, input, _| bi_refactor_remove_parameter(args, input),
    |args, input, _| bi_refactor_organize_imports(args, input),
    |args, input, _| bi_refactor_remove_unused(args, input),
    // Reserved (692-699)
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Session (700-712)
    |args, input, _| bi_session_start(args, input),
    |args, input, _| bi_session_end(args, input),
    |args, input, _| bi_session_id(args, input),
    |args, input, _| bi_session_history(args, input),
    |args, input, _| bi_session_undo(args, input),
    |args, input, _| bi_session_redo(args, input),
    |args, input, _| bi_session_checkpoint(args, input),
    |args, input, _| bi_session_restore(args, input),
    |args, input, _| bi_session_checkpoints(args, input),
    |args, input, _| bi_session_diff_since(args, input),
    |args, input, _| bi_session_changes(args, input),
    |args, input, _| bi_session_rollback(args, input),
    |args, input, _| bi_session_export(args, input),
    // Reserved (713-719)
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Docs (720-727)
    |args, input, _| bi_docs_generate(args, input),
    |args, input, _| bi_docs_search(args, input),
    |args, input, _| bi_docs_api(args, input),
    |args, input, _| bi_docs_readme(args, input),
    |args, input, _| bi_docs_changelog(args, input),
    |args, input, _| bi_docs_examples(args, input),
    |args, input, _| bi_docs_types(args, input),
    |args, input, _| bi_docs_signatures(args, input),
    // Reserved (728-729)
    |_, _, _| Err(reserved_slot()),
    |_, _, _| Err(reserved_slot()),
    // AI Coding Assistant - Environment (730-747)
    |args, input, _| bi_env_detect(args, input),
    |args, input, _| bi_env_python(args, input),
    |args, input, _| bi_env_node(args, input),
    |args, input, _| bi_env_rust(args, input),
    |args, input, _| bi_env_go(args, input),
    |args, input, _| bi_env_java(args, input),
    |args, input, _| bi_env_dotnet(args, input),
    |args, input, _| bi_env_ruby(args, input),
    |args, input, _| bi_env_shell(args, input),
    |args, input, _| bi_env_path(args, input),
    |args, input, _| bi_env_var(args, input),
    |args, input, _| bi_env_vars(args, input),
    |args, input, _| bi_env_set(args, input),
    |args, input, _| bi_env_unset(args, input),
    |args, input, _| bi_env_docker(args, input),
    |args, input, _| bi_env_container(args, input),
    |args, input, _| bi_env_venv(args, input),
    |args, input, _| bi_env_activate(args, input),
    // Platform versioning module (748-785)
    |args, input, _| bi_platform_snapshot(args, input),
    |args, input, _| bi_platform_os_version(args, input),
    |args, input, _| bi_platform_kernel(args, input),
    |args, input, _| bi_platform_build(args, input),
    |args, input, _| bi_platform_arch(args, input),
    |args, input, _| bi_platform_hostname(args, input),
    |args, input, _| bi_platform_machine_id(args, input),
    |args, input, _| bi_platform_tool_version(args, input),
    |args, input, _| bi_platform_tool_versions(args, input),
    |args, input, _| bi_platform_detect_tools(args, input),
    |args, input, _| bi_platform_has_tool(args, input),
    |args, input, _| bi_platform_capabilities(args, input),
    |args, input, _| bi_platform_has_admin(args, input),
    |args, input, _| bi_platform_has_sudo(args, input),
    |args, input, _| bi_platform_has_gui(args, input),
    |args, input, _| bi_platform_has_network(args, input),
    |args, input, _| bi_platform_has_container(args, input),
    |args, input, _| bi_platform_pkg_managers(args, input),
    |args, input, _| bi_platform_normalize_path(args, input),
    |args, input, _| bi_platform_normalize_output(args, input),
    |args, input, _| bi_platform_path_sep(args, input),
    |args, input, _| bi_platform_line_ending(args, input),
    |args, input, _| bi_platform_shell_type(args, input),
    |args, input, _| bi_platform_require(args, input),
    |args, input, _| bi_platform_check_reqs(args, input),
    |args, input, _| bi_platform_satisfies(args, input),
    |args, input, _| bi_platform_diff(args, input),
    |args, input, _| bi_platform_compatible(args, input),
    |args, input, _| bi_platform_db_init(args, input),
    |args, input, _| bi_platform_db_store(args, input),
    |args, input, _| bi_platform_db_load(args, input),
    |args, input, _| bi_platform_db_list(args, input),
    |args, input, _| bi_platform_db_delete(args, input),
    |args, input, _| bi_platform_db_compare(args, input),
    |args, input, _| bi_platform_db_export(args, input),
    |args, input, _| bi_platform_db_import(args, input),
    |args, input, _| bi_platform_fingerprint(args, input),
    |args, input, _| bi_platform_hash(args, input),
    // Platform categorized tools (786-795)
    |args, input, _| bi_platform_compilers(args, input),
    |args, input, _| bi_platform_build_systems(args, input),
    |args, input, _| bi_platform_runtimes(args, input),
    |args, input, _| bi_platform_pkg_lang(args, input),
    |args, input, _| bi_platform_containers(args, input),
    |args, input, _| bi_platform_cloud_clis(args, input),
    |args, input, _| bi_platform_databases(args, input),
    |args, input, _| bi_platform_linters(args, input),
    |args, input, _| bi_platform_vcs(args, input),
    |args, input, _| bi_platform_iac_tools(args, input),
    // Platform library detection (796-803)
    |args, input, _| bi_platform_libs(args, input),
    |args, input, _| bi_platform_lib_version(args, input),
    |args, input, _| bi_platform_system_libs(args, input),
    |args, input, _| bi_platform_sdk_version(args, input),
    |args, input, _| bi_platform_libc(args, input),
    |args, input, _| bi_platform_libcpp(args, input),
    |args, input, _| bi_platform_ssl_version(args, input),
    |args, input, _| bi_platform_cuda_version(args, input),
    // Platform hardware detection (804-815)
    |args, input, _| bi_platform_cpu(args, input),
    |args, input, _| bi_platform_cpu_count(args, input),
    |args, input, _| bi_platform_cpu_freq(args, input),
    |args, input, _| bi_platform_memory(args, input),
    |args, input, _| bi_platform_memory_total(args, input),
    |args, input, _| bi_platform_memory_free(args, input),
    |args, input, _| bi_platform_disks(args, input),
    |args, input, _| bi_platform_disk_usage(args, input),
    |args, input, _| bi_platform_gpus(args, input),
    |args, input, _| bi_platform_gpu_memory(args, input),
    |args, input, _| bi_platform_network_interfaces(args, input),
    |args, input, _| bi_platform_hardware_summary(args, input),
    // Proactive monitoring & alerting (816-835)
    |args, input, _| bi_htop_snapshot(args, input),
    |args, input, _| bi_iotop_snapshot(args, input),
    |args, input, _| bi_nmon_snapshot(args, input),
    |args, input, _| bi_nethogs_info(args, input),
    |args, input, _| bi_iftop_info(args, input),
    |args, input, _| bi_glances_info(args, input),
    |args, input, _| bi_tcpdump_capture(args, input),
    |args, input, _| bi_ss_info(args, input),
    |args, input, _| bi_ip_addr(args, input),
    |args, input, _| bi_ip_route(args, input),
    |args, input, _| bi_ip_link(args, input),
    |args, input, _| bi_ethtool_info(args, input),
    |args, input, _| bi_perf_stat(args, input),
    |args, input, _| bi_perf_record(args, input),
    |args, input, _| bi_free_mem(args, input),
    |args, input, _| bi_uptime_extended(args, input),
    |args, input, _| bi_who_users(args, input),
    |args, input, _| bi_last_logins(args, input),
    |args, input, _| bi_syslog_search(args, input),
    |args, input, _| bi_dstat_info(args, input),
    // Proactive alerting (836-843)
    |args, input, _| bi_health_check(args, input),
    |args, input, _| bi_alert_create(args, input),
    |args, input, _| bi_alert_list(args, input),
    |args, input, _| bi_alert_history(args, input),
    |args, input, _| bi_alert_remove(args, input),
    |args, input, _| bi_watch_cpu(args, input),
    |args, input, _| bi_watch_memory(args, input),
    |args, input, _| bi_watch_disk(args, input),
    // Cloud & Scale (844-878)
    // Cloud platform (844-851)
    |args, input, _| bi_cloud_deploy(args, input), // 844
    |args, input, _| bi_cloud_instances(args, input), // 845
    |args, input, _| bi_cloud_instance_create(args, input), // 846
    |args, input, _| bi_cloud_instance_destroy(args, input), // 847
    |args, input, _| bi_cloud_instance_status(args, input), // 848
    |args, input, _| bi_cloud_instance_connect(args, input), // 849
    |args, input, _| bi_cloud_regions(args, input), // 850
    |args, input, _| bi_cloud_config(args, input), // 851
    // Remote REPL (852-856)
    |args, input, _| bi_repl_serve(args, input),    // 852
    |args, input, _| bi_repl_connect(args, input),  // 853
    |args, input, _| bi_repl_sessions(args, input), // 854
    |args, input, _| bi_repl_disconnect(args, input), // 855
    |args, input, _| bi_repl_broadcast(args, input), // 856
    // Team workspaces (857-864)
    |args, input, _| bi_workspace_create(args, input), // 857
    |args, input, _| bi_workspace_list(args, input),   // 858
    |args, input, _| bi_workspace_join(args, input),   // 859
    |args, input, _| bi_workspace_leave(args, input),  // 860
    |args, input, _| bi_workspace_members(args, input), // 861
    |args, input, _| bi_workspace_share_agent(args, input), // 862
    |args, input, _| bi_workspace_agents(args, input), // 863
    |args, input, _| bi_workspace_sync(args, input),   // 864
    // Marketplace (865-872)
    |args, input, _| bi_marketplace_publish(args, input), // 865
    |args, input, _| bi_marketplace_search(args, input),  // 866
    |args, input, _| bi_marketplace_install(args, input), // 867
    |args, input, _| bi_marketplace_uninstall(args, input), // 868
    |args, input, _| bi_marketplace_list(args, input),    // 869
    |args, input, _| bi_marketplace_info(args, input),    // 870
    |args, input, _| bi_marketplace_rate(args, input),    // 871
    |args, input, _| bi_marketplace_update(args, input),  // 872
    // Telemetry (873-878)
    |args, input, _| bi_telemetry_enable(args, input), // 873
    |args, input, _| bi_telemetry_disable(args, input), // 874
    |args, input, _| bi_telemetry_status(args, input), // 875
    |args, input, _| bi_telemetry_report(args, input), // 876
    |args, input, _| bi_telemetry_events(args, input), // 877
    |args, input, _| bi_telemetry_reset(args, input),  // 878
    // ── CLI Tool Wrappers (879-987) ──────────────────────────
    // SSH (879-883)
    |args, input, _| bi_ssh_exec(args, input),    // 879
    |args, input, _| bi_ssh_tunnel(args, input),  // 880
    |args, input, _| bi_ssh_keygen(args, input),  // 881
    |args, input, _| bi_ssh_copy_id(args, input), // 882
    |args, input, _| bi_ssh_config(args, input),  // 883
    // rsync (884)
    |args, input, _| bi_rsync_sync(args, input), // 884
    // scp (885-886)
    |args, input, _| bi_scp_upload(args, input),   // 885
    |args, input, _| bi_scp_download(args, input), // 886
    // openssl (887-888)
    |args, input, _| bi_openssl_cert_info(args, input), // 887
    |args, input, _| bi_openssl_genrsa(args, input),    // 888
    // gpg (889-891)
    |args, input, _| bi_gpg_list_keys(args, input), // 889
    |args, input, _| bi_gpg_encrypt(args, input),   // 890
    |args, input, _| bi_gpg_decrypt(args, input),   // 891
    // Docker (892-911)
    |args, input, _| bi_docker_ps(args, input),      // 892
    |args, input, _| bi_docker_images(args, input),  // 893
    |args, input, _| bi_docker_run(args, input),     // 894
    |args, input, _| bi_docker_exec(args, input),    // 895
    |args, input, _| bi_docker_logs(args, input),    // 896
    |args, input, _| bi_docker_stop(args, input),    // 897
    |args, input, _| bi_docker_rm(args, input),      // 898
    |args, input, _| bi_docker_build(args, input),   // 899
    |args, input, _| bi_docker_pull(args, input),    // 900
    |args, input, _| bi_docker_push(args, input),    // 901
    |args, input, _| bi_docker_inspect(args, input), // 902
    |args, input, _| bi_docker_volumes(args, input), // 903
    |args, input, _| bi_docker_networks(args, input), // 904
    |args, input, _| bi_docker_compose_up(args, input), // 905
    |args, input, _| bi_docker_compose_down(args, input), // 906
    |args, input, _| bi_docker_compose_ps(args, input), // 907
    |args, input, _| bi_docker_stats(args, input),   // 908
    |args, input, _| bi_docker_top(args, input),     // 909
    |args, input, _| bi_docker_cp(args, input),      // 910
    |args, input, _| bi_docker_tag(args, input),     // 911
    // Podman (912-920)
    |args, input, _| bi_podman_ps(args, input),     // 912
    |args, input, _| bi_podman_images(args, input), // 913
    |args, input, _| bi_podman_run(args, input),    // 914
    |args, input, _| bi_podman_exec(args, input),   // 915
    |args, input, _| bi_podman_logs(args, input),   // 916
    |args, input, _| bi_podman_stop(args, input),   // 917
    |args, input, _| bi_podman_rm(args, input),     // 918
    |args, input, _| bi_podman_build(args, input),  // 919
    |args, input, _| bi_podman_pull(args, input),   // 920
    // Kubernetes / kubectl (921-943)
    |args, input, _| bi_k8s_get(args, input),         // 921
    |args, input, _| bi_k8s_apply(args, input),       // 922
    |args, input, _| bi_k8s_delete(args, input),      // 923
    |args, input, _| bi_k8s_describe(args, input),    // 924
    |args, input, _| bi_k8s_logs(args, input),        // 925
    |args, input, _| bi_k8s_exec(args, input),        // 926
    |args, input, _| bi_k8s_pods(args, input),        // 927
    |args, input, _| bi_k8s_services(args, input),    // 928
    |args, input, _| bi_k8s_deployments(args, input), // 929
    |args, input, _| bi_k8s_namespaces(args, input),  // 930
    |args, input, _| bi_k8s_nodes(args, input),       // 931
    |args, input, _| bi_k8s_events(args, input),      // 932
    |args, input, _| bi_k8s_configmaps(args, input),  // 933
    |args, input, _| bi_k8s_secrets(args, input),     // 934
    |args, input, _| bi_k8s_ingresses(args, input),   // 935
    |args, input, _| bi_k8s_rollout_status(args, input), // 936
    |args, input, _| bi_k8s_rollout_restart(args, input), // 937
    |args, input, _| bi_k8s_scale(args, input),       // 938
    |args, input, _| bi_k8s_top_pods(args, input),    // 939
    |args, input, _| bi_k8s_top_nodes(args, input),   // 940
    |args, input, _| bi_k8s_context(args, input),     // 941
    |args, input, _| bi_k8s_contexts(args, input),    // 942
    |args, input, _| bi_k8s_cluster_info(args, input), // 943
    // Helm (944-950)
    |args, input, _| bi_helm_list(args, input),      // 944
    |args, input, _| bi_helm_install(args, input),   // 945
    |args, input, _| bi_helm_upgrade(args, input),   // 946
    |args, input, _| bi_helm_uninstall(args, input), // 947
    |args, input, _| bi_helm_repos(args, input),     // 948
    |args, input, _| bi_helm_search(args, input),    // 949
    |args, input, _| bi_helm_status(args, input),    // 950
    // Terraform (951-958)
    |args, input, _| bi_terraform_init(args, input), // 951
    |args, input, _| bi_terraform_plan(args, input), // 952
    |args, input, _| bi_terraform_apply(args, input), // 953
    |args, input, _| bi_terraform_destroy(args, input), // 954
    |args, input, _| bi_terraform_state(args, input), // 955
    |args, input, _| bi_terraform_output(args, input), // 956
    |args, input, _| bi_terraform_workspace(args, input), // 957
    |args, input, _| bi_terraform_validate(args, input), // 958
    // Ansible (959-962)
    |args, input, _| bi_ansible_playbook(args, input), // 959
    |args, input, _| bi_ansible_inventory(args, input), // 960
    |args, input, _| bi_ansible_galaxy(args, input),   // 961
    |args, input, _| bi_ansible_vault(args, input),    // 962
    // journalctl (963)
    |args, input, _| bi_journalctl(args, input), // 963
    // lsof (964)
    |args, input, _| bi_lsof(args, input), // 964
    // ── New cross-platform tool implementations (965-987) ────
    // wget (965)
    |args, input, _| bi_wget_download(args, input), // 965
    // age encryption (966-968)
    |args, input, _| bi_age_encrypt(args, input), // 966
    |args, input, _| bi_age_decrypt(args, input), // 967
    |args, input, _| bi_age_keygen(args, input),  // 968
    // ripgrep (969)
    |args, input, _| bi_rg_search(args, input), // 969
    // fd (970)
    |args, input, _| bi_fd_find(args, input), // 970
    // sed (971)
    |args, input, _| bi_sed_replace(args, input), // 971
    // awk (972)
    |args, input, _| bi_awk_process(args, input), // 972
    // cut (973)
    |args, input, _| bi_cut_columns(args, input), // 973
    // xargs (974)
    |args, input, _| bi_xargs_exec(args, input), // 974
    // jq (975-976)
    |args, input, _| bi_jq_query(args, input),  // 975
    |args, input, _| bi_jq_filter(args, input), // 976
    // yq (977)
    |args, input, _| bi_yq_query(args, input), // 977
    // pager/less (978)
    |args, input, _| bi_pager(args, input), // 978
    // tee (979)
    |args, input, _| bi_tee_output(args, input), // 979
    // make (980-981)
    |args, input, _| bi_make_run(args, input),     // 980
    |args, input, _| bi_make_targets(args, input), // 981
    // cmake (982-983)
    |args, input, _| bi_cmake_configure(args, input), // 982
    |args, input, _| bi_cmake_build(args, input),     // 983
    // ninja (984)
    |args, input, _| bi_ninja_build(args, input), // 984
    // netstat (985)
    |args, input, _| bi_netstat_info(args, input), // 985
    // nmap (986-987)
    |args, input, _| bi_nmap_scan(args, input),  // 986
    |args, input, _| bi_nmap_quick(args, input), // 987
    // ============================================================
    // CLI Tool Wrappers — Tools 51-150 (indices 988-1103)
    // ============================================================
    // Dead-code activations (988-994)
    |args, input, _| bi_file_type(args, input),    // 988
    |args, input, _| bi_dd_copy(args, input),      // 989
    |args, input, _| bi_lsblk(args, input),        // 990
    |args, input, _| bi_blkid(args, input),        // 991
    |args, input, _| bi_strace_cmd(args, input),   // 992
    |args, input, _| bi_mount_info(args, input),   // 993
    |args, input, _| bi_top_snapshot(args, input), // 994
    // tmux (995-998)
    |args, input, _| bi_tmux_new(args, input),    // 995
    |args, input, _| bi_tmux_list(args, input),   // 996
    |args, input, _| bi_tmux_attach(args, input), // 997
    |args, input, _| bi_tmux_send(args, input),   // 998
    // screen (999-1001)
    |args, input, _| bi_screen_new(args, input),    // 999
    |args, input, _| bi_screen_list(args, input),   // 1000
    |args, input, _| bi_screen_attach(args, input), // 1001
    // timeout (1002)
    |args, input, _| bi_timeout_cmd(args, input), // 1002
    // pkill (1003)
    |args, input, _| bi_pkill(args, input), // 1003
    // pgrep (1004)
    |args, input, _| bi_pgrep(args, input), // 1004
    // lnav (1005)
    |args, input, _| bi_lnav_open(args, input), // 1005
    // multitail (1006)
    |args, input, _| bi_multitail_open(args, input), // 1006
    // logrotate (1007)
    |args, input, _| bi_logrotate_run(args, input), // 1007
    // ltrace (1008)
    |args, input, _| bi_ltrace_cmd(args, input), // 1008
    // valgrind (1009-1010)
    |args, input, _| bi_valgrind_run(args, input), // 1009
    |args, input, _| bi_valgrind_memcheck(args, input), // 1010
    // gdb (1011-1012)
    |args, input, _| bi_gdb_run(args, input), // 1011
    |args, input, _| bi_gdb_bt(args, input),  // 1012
    // lldb (1013)
    |args, input, _| bi_lldb_run(args, input), // 1013
    // objdump (1014-1015)
    |args, input, _| bi_objdump_disasm(args, input), // 1014
    |args, input, _| bi_objdump_headers(args, input), // 1015
    // nm (1016)
    |args, input, _| bi_nm_symbols(args, input), // 1016
    // readelf (1017-1018)
    |args, input, _| bi_readelf_headers(args, input), // 1017
    |args, input, _| bi_readelf_sections(args, input), // 1018
    // strings (1019)
    |args, input, _| bi_strings_extract(args, input), // 1019
    // chgrp (1020)
    |args, input, _| bi_chgrp(args, input), // 1020
    // mtr (1021)
    |args, input, _| bi_mtr_trace(args, input), // 1021
    // host (1022)
    |args, input, _| bi_host_lookup(args, input), // 1022
    // nc/netcat (1023-1024)
    |args, input, _| bi_nc_connect(args, input), // 1023
    |args, input, _| bi_nc_listen(args, input),  // 1024
    // socat (1025)
    |args, input, _| bi_socat_relay(args, input), // 1025
    // iperf3 (1026-1027)
    |args, input, _| bi_iperf3_server(args, input), // 1026
    |args, input, _| bi_iperf3_client(args, input), // 1027
    // bat (1028)
    |args, input, _| bi_bat_view(args, input), // 1028
    // eza (1029)
    |args, input, _| bi_eza_list(args, input), // 1029
    // zoxide (1030-1031)
    |args, input, _| bi_zoxide_add(args, input),   // 1030
    |args, input, _| bi_zoxide_query(args, input), // 1031
    // delta (1032)
    |args, input, _| bi_delta_diff(args, input), // 1032
    // lazygit (1033)
    |args, input, _| bi_lazygit_open(args, input), // 1033
    // fzf (1034)
    |args, input, _| bi_fzf_select(args, input), // 1034
    // rga (1035)
    |args, input, _| bi_rga_search(args, input), // 1035
    // sd (1036)
    |args, input, _| bi_sd_replace(args, input), // 1036
    // hyperfine (1037)
    |args, input, _| bi_hyperfine_bench(args, input), // 1037
    // tokei (1038)
    |args, input, _| bi_tokei_count(args, input), // 1038
    // entr (1039)
    |args, input, _| bi_entr_watch(args, input), // 1039
    // watchexec (1040)
    |args, input, _| bi_watchexec_run(args, input), // 1040
    // just (1041-1042)
    |args, input, _| bi_just_run(args, input),  // 1041
    |args, input, _| bi_just_list(args, input), // 1042
    // task (1043-1044)
    |args, input, _| bi_task_run(args, input),  // 1043
    |args, input, _| bi_task_list(args, input), // 1044
    // direnv (1045-1046)
    |args, input, _| bi_direnv_allow(args, input), // 1045
    |args, input, _| bi_direnv_status(args, input), // 1046
    // asdf (1047-1048)
    |args, input, _| bi_asdf_list(args, input),    // 1047
    |args, input, _| bi_asdf_install(args, input), // 1048
    // mise (1049-1050)
    |args, input, _| bi_mise_use(args, input),  // 1049
    |args, input, _| bi_mise_list(args, input), // 1050
    // uv (1051-1053)
    |args, input, _| bi_uv_run(args, input),  // 1051
    |args, input, _| bi_uv_pip(args, input),  // 1052
    |args, input, _| bi_uv_venv(args, input), // 1053
    // pipx (1054-1055)
    |args, input, _| bi_pipx_install(args, input), // 1054
    |args, input, _| bi_pipx_list(args, input),    // 1055
    // poetry (1056-1057)
    |args, input, _| bi_poetry_run(args, input), // 1056
    |args, input, _| bi_poetry_install(args, input), // 1057
    // node (1058)
    |args, input, _| bi_node_run(args, input), // 1058
    // npm (1059-1060)
    |args, input, _| bi_npm_run(args, input),     // 1059
    |args, input, _| bi_npm_install(args, input), // 1060
    // pnpm (1061-1062)
    |args, input, _| bi_pnpm_run(args, input),     // 1061
    |args, input, _| bi_pnpm_install(args, input), // 1062
    // yarn (1063-1064)
    |args, input, _| bi_yarn_run(args, input),     // 1063
    |args, input, _| bi_yarn_install(args, input), // 1064
    // cargo (1065-1067)
    |args, input, _| bi_cargo_run(args, input), // 1065
    |args, input, _| bi_cargo_build_cmd(args, input), // 1066
    |args, input, _| bi_cargo_test_cmd(args, input), // 1067
    // rustup (1068-1069)
    |args, input, _| bi_rustup_show(args, input), // 1068
    |args, input, _| bi_rustup_update(args, input), // 1069
    // go (1070-1072)
    |args, input, _| bi_go_run(args, input),   // 1070
    |args, input, _| bi_go_build(args, input), // 1071
    |args, input, _| bi_go_test(args, input),  // 1072
    // mage (1073)
    |args, input, _| bi_mage_run(args, input), // 1073
    // bun (1074-1075)
    |args, input, _| bi_bun_run(args, input),     // 1074
    |args, input, _| bi_bun_install(args, input), // 1075
    // deno (1076-1077)
    |args, input, _| bi_deno_run(args, input),  // 1076
    |args, input, _| bi_deno_task(args, input), // 1077
    // gh (1078-1080)
    |args, input, _| bi_gh_pr(args, input),       // 1078
    |args, input, _| bi_gh_issue(args, input),    // 1079
    |args, input, _| bi_gh_repo_cmd(args, input), // 1080
    // glab (1081-1082)
    |args, input, _| bi_glab_mr(args, input),    // 1081
    |args, input, _| bi_glab_issue(args, input), // 1082
    // act (1083)
    |args, input, _| bi_act_run(args, input), // 1083
    // pre-commit (1084-1085)
    |args, input, _| bi_pre_commit_run(args, input), // 1084
    |args, input, _| bi_pre_commit_install(args, input), // 1085
    // buildah (1086-1087)
    |args, input, _| bi_buildah_build(args, input), // 1086
    |args, input, _| bi_buildah_images(args, input), // 1087
    // skopeo (1088-1089)
    |args, input, _| bi_skopeo_copy(args, input), // 1088
    |args, input, _| bi_skopeo_inspect(args, input), // 1089
    // trivy (1090-1091)
    |args, input, _| bi_trivy_scan(args, input),  // 1090
    |args, input, _| bi_trivy_image(args, input), // 1091
    // hadolint (1092)
    |args, input, _| bi_hadolint_check(args, input), // 1092
    // shellcheck (1093)
    |args, input, _| bi_shellcheck_check(args, input), // 1093
    // shfmt (1094)
    |args, input, _| bi_shfmt_format(args, input), // 1094
    // yamllint (1095)
    |args, input, _| bi_yamllint_check(args, input), // 1095
    // prettier (1096)
    |args, input, _| bi_prettier_format(args, input), // 1096
    // eslint (1097)
    |args, input, _| bi_eslint_check(args, input), // 1097
    // ruff (1098-1099)
    |args, input, _| bi_ruff_check(args, input),  // 1098
    |args, input, _| bi_ruff_format(args, input), // 1099
    // black (1100)
    |args, input, _| bi_black_format(args, input), // 1100
    // mypy (1101)
    |args, input, _| bi_mypy_check(args, input), // 1101
    // pytest (1102)
    |args, input, _| bi_pytest_run(args, input), // 1102
    // nodemon (1103)
    |args, input, _| bi_nodemon_run(args, input), // 1103
    // safety: approval + audit verification (1104-1105)
    |args, input, _| bi_approve(args, input),      // 1104
    |args, input, _| bi_audit_verify(args, input), // 1105
    // safety: RBAC principal authorization (1106-1108)
    |args, input, _| bi_rbac_principal(args, input), // 1106
    |args, input, _| bi_rbac_grant(args, input),     // 1107
    |args, input, _| bi_rbac_can(args, input),       // 1108
    // output economy: compact rendering + token estimate (1109-1110)
    |args, input, _| bi_aecon(args, input),  // 1109
    |args, input, _| bi_tokens(args, input), // 1110
    // progressive ontology disclosure (1111-1112)
    |args, input, _| bi_ontology_manifest(args, input), // 1111
    |args, input, _| bi_ontology_describe(args, input), // 1112
    // deterministic canonical serialization (1113)
    |args, input, _| bi_canonical(args, input), // 1113
    // filesystem transactions / checkpoints (1114-1117)
    |args, input, _| bi_tx_begin(args, input),    // 1114
    |args, input, _| bi_tx_commit(args, input),   // 1115
    |args, input, _| bi_tx_rollback(args, input), // 1116
    |args, input, _| bi_tx_status(args, input),   // 1117
    // output budgeting / paging (1118)
    |args, input, _| bi_budget(args, input), // 1118
    // plan / apply (1119-1120)
    |args, input, _| bi_plan(args, input),  // 1119
    |args, input, _| bi_apply(args, input), // 1120
    // safety introspection (1121)
    |args, input, _| bi_safety_status(args, input), // 1121
    // stateful sessions (1122-1125)
    |args, input, _| bi_sess_open(args, input),  // 1122
    |args, input, _| bi_sess_eval(args, input),  // 1123
    |args, input, _| bi_sess_close(args, input), // 1124
    |args, input, _| bi_sess_usage(args, input), // 1125
    // audit review (1126)
    |args, input, _| bi_audit_tail(args, input), // 1126
    // output economy: structural digest (1127)
    |args, input, _| bi_digest(args, input), // 1127
    // output economy: source-side field projection (1128)
    |args, input, _| bi_pick(args, input), // 1128
    // output economy: AECON decoder — reverses the tabular encoding (1129)
    |args, input, _| bi_aecon_decode(args, input), // 1129
    // persistent key-value store (sqlite-backed; transactional via db_sqlite_exec)
    |args, input, _| bi_db_kv_get(args, input),    // 1130
    |args, input, _| bi_db_kv_set(args, input),    // 1131
    |args, input, _| bi_db_kv_delete(args, input), // 1132
    |args, input, _| bi_db_kv_keys(args, input),   // 1133
    |args, input, _| bi_db_kv_store(args, input),  // 1134
    // transactions: named savepoints (partial rollback)
    |args, input, _| bi_tx_savepoint(args, input), // 1135
    |args, input, _| bi_tx_rollback_to(args, input), // 1136
    // resource governors (§7.6)
    |args, input, _| bi_governor_status(args, input), // 1137
    |args, input, _| bi_governor_reset(args, input),  // 1138
    // self-healing: minimal repair context + rollback-bracketed attempts
    |args, input, _| bi_diagnose(args, input),      // 1139
    bi_try_repair,                                  // 1140
    |args, input, _| bi_plan_diff(args, input),     // 1141
    |args, input, _| bi_rm(args, input),            // 1142
    |args, input, _| bi_rmdir(args, input),         // 1143
    |args, input, _| bi_touch(args, input),         // 1144
    |args, input, _| bi_cd(args, input),            // 1145
    |args, input, _| bi_rbac_register(args, input), // 1146
    |args, input, _| bi_rbac_login(args, input),    // 1147
    |args, input, _| bi_rbac_logout(args, input),   // 1148
    |args, input, _| bi_rbac_session(args, input),  // 1149
    // Appended, never inserted. A row added mid-table shifts every index after
    // it and silently re-points every `map.insert` above it -- the failure mode
    // that left `mkdir` on a placeholder. New rows go on the end.
    |args, input, _| bi_db_csv_query(args, input), // 1150
    |args, input, _| bi_db_json_query(args, input), // 1151
    |args, input, _| bi_db_json_to_csv(args, input), // 1152
    |args, input, _| bi_clipboard_types(args, input), // 1153
    |args, input, _| bi_crypto_random_string(args, input), // 1154
    |args, input, _| bi_input_number(args, input), // 1155
    |args, input, _| bi_input_timeout(args, input), // 1156
    |args, input, _| bi_whoami(args, input),       // 1157
    |args, input, _| bi_named_hash("md5", args, input), // 1158
    |args, input, _| bi_named_hash("sha256", args, input), // 1159
    |args, input, _| bi_error(args, input),        // 1160
    |args, input, _| bi_args(args, input),         // 1161
    |args, input, _| bi_int(args, input),          // 1162
    |args, input, _| bi_float(args, input),        // 1163
    |args, input, _| bi_now_iso(args, input),      // 1164
    |args, input, _| bi_regex_match(args, input),  // 1165
    |args, input, _| bi_regex_find(args, input),   // 1166
    |args, input, _| bi_regex_find_all(args, input), // 1167
    |args, input, _| bi_regex_replace(args, input), // 1168
    |args, input, _| bi_pad_left(args, input),     // 1169
    |args, input, _| bi_pad_right(args, input),    // 1170
    |args, input, _| bi_date_parse(args, input),   // 1171
    |args, input, _| bi_date_diff(args, input),    // 1172
    |args, input, _| bi_date_format(args, input),  // 1173
    |args, input, _| bi_date_add(args, input),     // 1174
    |args, input, _| bi_to_toml(args, input),      // 1175
    |args, input, _| bi_from_toml(args, input),    // 1176
    // Records and number text (1177-1178)
    |args, input, _| bi_merge(args, input),         // 1177
    |args, input, _| bi_format_number(args, input), // 1178
    // Paths (1179-1186), in src/path_builtins.rs
    |args, input, _| bi_path_join(args, input),     // 1179
    |args, input, _| bi_path_basename(args, input), // 1180
    |args, input, _| bi_path_dirname(args, input),  // 1181
    |args, input, _| bi_path_extension(args, input), // 1182
    |args, input, _| bi_path_stem(args, input),     // 1183
    |args, input, _| bi_path_normalize(args, input), // 1184
    |args, input, _| bi_path_is_absolute(args, input), // 1185
    |args, input, _| bi_path_split(args, input),    // 1186
    |args, input, _| bi_chunk(args, input),         // 1187
    |args, input, _| bi_url_encode(args, input),    // 1188
    |args, input, _| bi_url_decode(args, input),    // 1189
    |args, input, _| bi_get(args, input),           // 1190
    |args, input, _| bi_has(args, input),           // 1191
    |args, input, _| bi_to_entries(args, input),    // 1192
    |args, input, _| bi_from_entries(args, input),  // 1193
    // Text (1194-1197), in the string section
    |args, input, _| bi_title(args, input),      // 1194
    |args, input, _| bi_capitalize(args, input), // 1195
    |args, input, _| bi_repeat(args, input),     // 1196
    |args, input, _| bi_words(args, input),      // 1197
    // Logarithms and exp (1198-1202), beside sqrt
    |args, input, _| bi_log(args, input),   // 1198
    |args, input, _| bi_ln(args, input),    // 1199
    |args, input, _| bi_log10(args, input), // 1200
    |args, input, _| bi_log2(args, input),  // 1201
    |args, input, _| bi_exp(args, input),   // 1202
    // Epoch seconds (1203-1204), in the date section
    |args, input, _| bi_from_epoch(args, input), // 1203
    |args, input, _| bi_to_epoch(args, input),   // 1204
    // Statistics (1205-1208), beside avg
    |args, input, _| bi_median(args, input),     // 1205
    |args, input, _| bi_variance(args, input),   // 1206
    |args, input, _| bi_stddev(args, input),     // 1207
    |args, input, _| bi_percentile(args, input), // 1208
    // Substring position (1209-1210) and regex split (1211), in the string section
    |args, input, _| bi_index_of(args, input),      // 1209
    |args, input, _| bi_last_index_of(args, input), // 1210
    |args, input, _| bi_regex_split(args, input),   // 1211
    // The PowerShell transpiler's `+`
    |args, input, _| bi_ps_add(args, input), // 1212
];

/// The dispatch row that serves `name`, if the fast table has one.
fn fast_index(name: &str) -> Option<usize> {
    BUILTIN_LOOKUP
        .get(name)
        .copied()
        .filter(|&i| i < BUILTIN_DISPATCH.len())
}

/// Run a fast-table builtin by its row. The one place `BUILTIN_DISPATCH` is
/// indexed, reached only from `call_with_input_inner` after the gate
/// (`tests/one_door.rs`). It takes a resolved row rather than a name so the
/// caller can decide before giving up its arguments, which then move.
fn fast_builtin_lookup(
    index: usize,
    args: Vec<Value>,
    input: Option<Value>,
    env: &mut Env,
) -> Result<Value> {
    BUILTIN_DISPATCH[index](args, input, env)
}

// --------------- Public entry points ---------------

/// Edit distance (optimal string alignment: an insertion, a deletion, a
/// substitution or a swap of two neighbouring letters each cost 1), bounded by
/// `max`: returns `None` as soon as no alignment can come within it. The bound
/// is what makes scanning the whole builtin table on a *failed* call cheap. A
/// swap counts once because it is the commonest slip: `file.raed` is one edit
/// from `file.read`, not two.
fn edit_distance_within(a: &str, b: &str, max: usize) -> Option<usize> {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let (la, lb) = (a.len(), b.len());
    if la.abs_diff(lb) > max {
        return None;
    }
    let mut before: Vec<usize> = vec![0; lb + 1];
    let mut prev: Vec<usize> = (0..=lb).collect();
    let mut cur = vec![0usize; lb + 1];
    let mut prev_best = 0;
    for i in 0..la {
        cur[0] = i + 1;
        let mut row_best = cur[0];
        for j in 0..lb {
            let cost = usize::from(a[i] != b[j]);
            let mut d = (prev[j] + cost).min(prev[j + 1] + 1).min(cur[j] + 1);
            if i > 0 && j > 0 && a[i] == b[j - 1] && a[i - 1] == b[j] {
                d = d.min(before[j - 1] + 1);
            }
            cur[j + 1] = d;
            row_best = row_best.min(d);
        }
        // A swap reaches back two rows, so stop only when both of the last two
        // rows are already over the bound.
        if row_best > max && prev_best > max {
            return None;
        }
        prev_best = row_best;
        std::mem::swap(&mut before, &mut prev);
        std::mem::swap(&mut prev, &mut cur);
    }
    let d = prev[lb];
    if d <= max {
        Some(d)
    } else {
        None
    }
}

/// The nearest **real** builtin names to `name`, closest first (at most 3).
///
/// Searched against the live `BUILTIN_LOOKUP` table rather than a hand-written
/// list, so it cannot drift out of date as builtins are added, and it never
/// falls back to a default guess: when nothing is within the edit budget the
/// result is empty. The budget scales with name length (1 for very short names,
/// where every neighbour is a different command; up to 3 for long dotted ones).
pub fn did_you_mean(name: &str) -> Vec<String> {
    did_you_mean_among(name, std::iter::empty())
}

/// `did_you_mean` for a bare name that may also be a bound variable: `extra`
/// are the variable names, searched alongside the builtins. An explicit
/// mapping (`date` -> `now_iso`, `redo` -> `session_redo`) is the whole answer:
/// a nearby name offered beside it (`sed` for `redo`) is noise. Only a name
/// with no mapping gets the module spelling and the edit-distance guesses.
pub fn did_you_mean_among<'a>(name: &str, extra: impl Iterator<Item = &'a str>) -> Vec<String> {
    let mapped = mapped_spelling(name);
    if !mapped.is_empty() {
        return mapped;
    }
    let mut out: Vec<String> = Vec::new();
    // The module spelling comes next. `file_read` is not a builtin, but
    // `file.read` is the call an agent meant, and an edit-distance guess
    // (`file_rename`) is a worse answer than that one. It is offered only when
    // the module really has that member.
    if let Some((module, func)) = name.split_once('_') {
        let spelled = format!("{module}.{func}");
        if crate::modules::is_module_member(module, func) && !out.contains(&spelled) {
            out.push(spelled);
        }
    }
    for near in nearest_names(name, extra.chain(BUILTIN_LOOKUP.keys().copied())) {
        if out.len() == 3 {
            break;
        }
        if !out.contains(&near) {
            out.push(near);
        }
    }
    out
}

/// The builtins a misspelt name is named for outright, from other languages
/// and other shells: a spelling the edit-distance search cannot reach, such as
/// `to_int` (four edits from `int`), is listed here instead.
fn mapped_spelling(name: &str) -> Vec<String> {
    match name {
        "to_int" | "parse_int" | "as_int" => vec!["int".to_string()],
        "to_float" | "parse_float" | "as_float" => vec!["float".to_string()],
        "number" | "to_number" | "parse_number" => {
            vec!["int".to_string(), "float".to_string()]
        }
        // Date and time names have no builtin of their own; the clock one is.
        "date_iso" | "iso_date" | "today" | "date" | "datetime" | "timestamp_iso" => {
            vec!["now_iso".to_string()]
        }
        // Raising an error is `error(message)`, or the `throw` statement.
        "raise" | "fail" => vec!["error".to_string(), "throw".to_string()],
        "throw" => vec!["error".to_string()],
        // Dates: parse and format are date_parse and date_format.
        "parse_date" | "strptime" => vec!["date_parse".to_string()],
        "strftime" => vec!["date_format".to_string()],
        // Regular expressions: regex_find, and regex_match for a yes or no.
        "re_find" | "re_search" | "regex_search" => vec!["regex_find".to_string()],
        "re_match" => vec!["regex_match".to_string()],
        // Padding: pad_left and pad_right, which take a width and a fill.
        "lpad" | "rjust" => vec!["pad_left".to_string()],
        "rpad" | "ljust" => vec!["pad_right".to_string()],
        "center" => vec!["pad_left".to_string(), "pad_right".to_string()],
        // TOML: from_toml reads a document and to_toml writes one.
        "toml" => vec!["from_toml".to_string(), "to_toml".to_string()],
        "parse_toml" => vec!["from_toml".to_string()],
        // A filter is where: the rows that pass the test.
        "filter" => vec!["where".to_string()],
        // Names agents guess that IronShell does not have. The real name is
        // listed first. There is no `file_read` or `read_file`: reading a file is
        // read_text, or the file.read module call.
        "file_read" | "read_file" | "readfile" => {
            vec!["read_text".to_string(), "file.read".to_string()]
        }
        "exists_file" => vec!["exists".to_string()],
        // Deleting a file is rm, which takes the path. No builtin is named delete.
        "delete" | "remove" | "unlink" | "file_delete" | "file_remove" | "remove_file"
        | "delete_file" => vec!["rm".to_string()],
        // Repetition is repeat(text, count); a Python or JavaScript spelling is
        // named for it.
        "str_repeat" => vec!["repeat".to_string()],
        // Redo re-applies the step undo took back: session_redo. Without this a
        // nearby name (sed) was offered instead.
        "redo" => vec!["session_redo".to_string()],
        // A bare `get` is an HTTP GET: http_get, which http.get calls. Its
        // nearest name is wget, a program, not a builtin.
        "get" => vec!["http_get".to_string()],
        // Substrings: slice(s, start, end) takes characters. `str.substring` and
        // `str.substr` are JavaScript's and Python-adjacent spellings of it.
        "substring" | "substr" | "slice" => vec!["slice".to_string()],
        // Dropping the first elements, or keeping the rest, is slice:
        // slice(xs, 1) or xs | slice(1).
        "skip" | "drop" | "rest" => vec!["slice".to_string()],
        // No builtin tests for one key: keys lists a record's names, which is
        // what a test of one key reads. `has` is that test, and `get` returns a
        // field with a default.
        "has_key" => vec!["has".to_string()],
        // Paths: the text-only path_* builtins. `abspath` has no pure form:
        // path_is_absolute tests it, and fs_realpath resolves it on disk.
        "basename" | "fs_basename" | "file_basename" => vec!["path_basename".to_string()],
        "dirname" | "fs_dirname" | "file_dirname" => vec!["path_dirname".to_string()],
        "extname" | "extension" | "fs_extension" | "file_extension" => {
            vec!["path_extension".to_string()]
        }
        "file_stem" | "fs_stem" => vec!["path_stem".to_string()],
        "splitext" => vec!["path_stem".to_string(), "path_extension".to_string()],
        "normpath" => vec!["path_normalize".to_string()],
        "abspath" => vec!["path_is_absolute".to_string(), "fs_realpath".to_string()],
        "join_path" | "joinpath" | "path_combine" => vec!["path_join".to_string()],
        _ => Vec::new(),
    }
}

/// The spellings another library uses for a member of a module, such as
/// `json.loads` or `re.findall`, that name IronShell's own builtin. Empty when
/// there is none. Used both for a module that exists (`json`) and for a module
/// that does not (`re`, `regex`, `toml`), where it replaces the nearest-name
/// guess: `re` is one edit from the `rg` and `rl` modules, which are not what
/// `re.findall` means.
pub fn mapped_module_spelling(module: &str, member: &str) -> Vec<String> {
    let names: &[&str] = match (module, member) {
        ("json", "loads") => &["json.parse"],
        ("json", "dumps") => &["json.stringify"],
        ("toml", "parse" | "loads") => &["from_toml"],
        ("toml", "dumps") => &["to_toml"],
        ("regex" | "re", "match") => &["regex_match"],
        ("regex" | "re", "search") => &["regex_find"],
        ("regex" | "re", "findall" | "find_all") => &["regex_find_all"],
        ("regex" | "re", "sub") => &["regex_replace"],
        ("path", "exists" | "isfile" | "isdir") => &["path_exists"],
        ("path", "realpath" | "abspath" | "resolve" | "canonicalize") => &["fs_realpath"],
        ("path", "normpath" | "normalize") => &["path_normalize"],
        // `path` is not a module, so a script may bind a variable named `path`;
        // the pathlib / os.path spellings name the path_* builtins instead.
        ("path", "join") => &["path_join"],
        ("path", "basename" | "name") => &["path_basename"],
        ("path", "dirname" | "parent") => &["path_dirname"],
        ("path", "extension" | "suffix" | "extname" | "splitext") => &["path_extension"],
        ("path", "stem") => &["path_stem"],
        ("path", "isabs" | "is_absolute") => &["path_is_absolute"],
        ("path", "split" | "parts") => &["path_split"],
        ("path", _) => &["path_join", "path_basename", "path_exists"],
        _ => &[],
    };
    names.iter().map(|name| name.to_string()).collect()
}

/// The edit budget for a suggestion to `name`: a third of its length, from 1 up
/// to 3. For a short name every neighbour is a different command, so only a
/// one-letter slip is a real suggestion. It was 2 for names of 4 to 7 letters,
/// which offered `None`, `node` and `Some` for `nope`.
fn edit_budget(name: &str) -> usize {
    (name.chars().count() / 3).clamp(1, 3)
}

/// The nearest names to `name` from an arbitrary candidate set, closest first
/// (at most 3), or empty when nothing is within the edit budget.
///
/// Generic over the candidates so the same matching serves both misspelled
/// builtins and misspelled *record fields* — which is how module functions
/// (`file.read`) resolve, and therefore how most agent typos actually present.
pub fn nearest_names<'a>(name: &str, candidates: impl Iterator<Item = &'a str>) -> Vec<String> {
    let lower = name.to_lowercase();
    let len = lower.chars().count();
    // A slip is fewer edits than the name has letters: `a` is not a typo of
    // `b`, however close they sit, so a one-letter name suggests nothing.
    let budget = edit_budget(name).min(len.saturating_sub(1));
    let mut scored: Vec<(usize, &'a str)> = candidates
        .filter_map(|cand| {
            let cand_lower = cand.to_lowercase();
            // `Some` and `None` are value constructors, not calls an agent
            // mistyped: `nope` is not a slip of `None`. A capitalised candidate
            // is offered only for a capitalised name, or a case-only difference.
            if cand.chars().next().is_some_and(char::is_uppercase)
                && !name.chars().next().is_some_and(char::is_uppercase)
                && cand_lower != lower
            {
                return None;
            }
            // A name of a very different length is not a slip of this one.
            if cand_lower.chars().count().abs_diff(len) > 2 {
                return None;
            }
            edit_distance_within(&lower, &cand_lower, budget).map(|d| (d, cand))
        })
        .collect();
    // Deterministic: distance first, then name, so the same typo always yields
    // the same suggestions (an agent replaying a repair must see stable output).
    scored.sort_unstable_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(b.1)));
    // A name offered by two sources (a bound variable and a builtin both called
    // `yq`) is one candidate. Equal names sort together, so they are adjacent.
    scored.dedup_by(|a, b| a.1 == b.1);
    scored.truncate(3);
    scored.into_iter().map(|(_, n)| n.to_string()).collect()
}

/// Suggestions for `module.field` where the module has no such member.
///
/// The module's own members come first, nearest first. A global builtin is
/// added only when its name contains the typed member or the reverse, or it is
/// one edit away: an unrelated global (`str.padd` -> `pwd`) is worse than no
/// suggestion. At most three in all.
pub fn module_member_candidates(module: &str, field: &str, members: &[&str]) -> Vec<String> {
    // A member is near when its whole name or one of its `_` parts is: `padd`
    // and `lpad` both reach `pad_left` through its `pad` part.
    let typed = field.to_lowercase();
    let budget = edit_budget(field);
    let mut near: Vec<(usize, &str)> = members
        .iter()
        .filter_map(|m| {
            std::iter::once(*m)
                .chain(m.split('_'))
                .filter_map(|part| edit_distance_within(&typed, &part.to_lowercase(), budget))
                .min()
                .map(|d| (d, *m))
        })
        .collect();
    near.sort_unstable_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(b.1)));
    near.dedup_by(|a, b| a.1 == b.1);
    // A spelling another language uses for a builtin here (`str.rjust` is
    // pad_right) comes first, as it does for a bare name.
    // `json.loads` is `json.parse`, from another library, and is named first.
    let mut out: Vec<String> = mapped_module_spelling(module, field);
    for spelled in mapped_spelling(field) {
        if !out.contains(&spelled) {
            out.push(spelled);
        }
    }
    // An explicit mapping is the whole answer, as it is for a bare name: a
    // nearby member beside it (`str.in` for `str.substring`) is noise.
    if !out.is_empty() {
        return out;
    }
    for (_, m) in near {
        if out.len() == 3 {
            break;
        }
        let spelled = format!("{module}.{m}");
        if !out.contains(&spelled) {
            out.push(spelled);
        }
    }
    let mut globals: Vec<(usize, &str)> = BUILTIN_LOOKUP
        .keys()
        .copied()
        .filter_map(|g| {
            let lower = g.to_lowercase();
            // A short global inside a long typed name is chance, not kinship:
            // `math.variance` contains `nc`. Substrings count from 4 characters.
            let related = (lower.contains(&typed) || typed.contains(&lower))
                && typed.chars().count().min(lower.chars().count()) >= 4;
            let distance = edit_distance_within(
                &typed,
                &lower,
                typed.chars().count() + lower.chars().count(),
            )?;
            (related || distance <= 1).then_some((distance, g))
        })
        .collect();
    globals.sort_unstable_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(b.1)));
    for (_, global) in globals {
        if out.len() == 3 {
            break;
        }
        if !out.iter().any(|o| o == global) {
            out.push(global.to_string());
        }
    }
    out
}

pub fn call(name: &str, args: Vec<Value>, env: &mut Env) -> Result<Value> {
    call_with_input(name, args, None, env)
}

/// Call a builtin with optional piped input.
///
/// This is the single boundary where a builtin failure becomes an agent-visible
/// error, so it is also where every failure is guaranteed a stable code
/// (`safety::ensure_structured`): a builtin that returned bare `anyhow` prose
/// surfaces as `E_UNKNOWN` with `retryable: false` rather than as an
/// unbranchable string. Errors that already carry a specific code pass through
/// untouched.
pub fn call_with_input(
    name: &str,
    args: Vec<Value>,
    input: Option<Value>,
    env: &mut Env,
) -> Result<Value> {
    refuse_irreversible_in_transaction(name)
        .map_err(|e| crate::safety::ensure_structured(name, e))?;

    // A builtin with a declared signature is checked before its body runs, so
    // it cannot answer a call it could not honour. Undeclared builtins are
    // unaffected — see `crate::signature` for why this exists and why the
    // migration is incremental.
    crate::signature::validate(name, &args, input.as_ref())
        .map_err(|e| crate::safety::ensure_structured(name, e))?;

    call_with_input_inner(name, args, input, env)
        .map_err(|e| crate::safety::ensure_structured(name, e))
}

lazy_static::lazy_static! {
    /// The dispatch indices of `tx::IRREVERSIBLE`, so every spelling of a
    /// listed implementation is refused, not only the listed one.
    static ref TX_IRREVERSIBLE_INDICES: rustc_hash::FxHashSet<usize> = crate::tx::IRREVERSIBLE
        .iter()
        .filter_map(|name| BUILTIN_LOOKUP.get(name).copied())
        .collect();
    /// The function each listed fallback name's arm calls. A fallback-only
    /// spelling is refused when its arm calls one of these, as a table
    /// spelling is refused by its dispatch index.
    static ref TX_IRREVERSIBLE_CALLEES: rustc_hash::FxHashSet<&'static str> = FALLBACK_BUILTINS
        .iter()
        .filter(|(name, _)| crate::tx::IRREVERSIBLE.contains(name))
        .map(|(_, callee)| *callee)
        .collect();
}

/// Refuse a builtin a rollback cannot undo while a transaction is active
/// (`E_POLICY_DENY`), before anything runs.
fn refuse_irreversible_in_transaction(name: &str) -> Result<()> {
    let listed = match BUILTIN_LOOKUP.get(name) {
        Some(idx) => TX_IRREVERSIBLE_INDICES.contains(idx),
        None => FALLBACK_BUILTINS
            .binary_search_by_key(&name, |(n, _)| n)
            .is_ok_and(|i| TX_IRREVERSIBLE_CALLEES.contains(FALLBACK_BUILTINS[i].1)),
    };
    if listed && crate::tx::is_active() {
        return Err(crate::safety::policy_deny(
            name,
            format!(
                "{name}: cannot run inside a filesystem transaction: a rollback cannot undo what it does; NOTHING WAS CHANGED"
            ),
            "commit or roll back the open transaction (tx_commit or tx_rollback), then run it outside",
        ));
    }
    Ok(())
}

/// Every name served by the fallback `match` in [`call_with_input_inner`],
/// paired with the function that arm calls, sorted by name.
///
/// The dispatcher has two halves. `BUILTIN_LOOKUP` is a table, so it can be
/// asked what it serves and which names share an implementation; the fallback is
/// a literal `match`, so it can do neither. That asymmetry made the second half
/// invisible to everything reasoning about "the set of names an agent can call"
/// — `tests/effect_ratchet.rs` skipped it, and `eval::is_effect_free` treated all
/// 113 fallback-only names as unknown.
///
/// The function name is carried because *aliasing* is the part that matters for
/// safety: `"vault-convert" | "vault_convert" => bi_vault_convert(..)` is one
/// arm serving two names, and `safety::effect_of` classifies by name. Without
/// this pairing there was no way for `src/` to know the two were the same call.
///
/// Hand-written *and* drift-proof: `tests/fallback_dispatch.rs` parses the arms
/// out of this file's own source and asserts equality, so an arm added without a
/// matching entry here fails the build. That mechanical check is the difference
/// between a second source of truth and a second place to forget.
///
/// Three of these names (`ai_backends`, `type_of`, `typeof`) are also in
/// `BUILTIN_LOOKUP`, which wins, so their arms are unreachable. They are listed
/// anyway because this mirrors the *match*, not the reachable subset — keeping
/// the equality exact is what makes the drift test simple enough to trust.
pub const FALLBACK_BUILTINS: &[(&str, &str)] = &[
    ("ForEach-Object", "bi_foreach_object"),
    ("Get-Content", "bi_get_content"),
    ("Get-Files", "bi_get_files"),
    ("Group-Object", "bi_group_object"),
    ("Measure-Object", "bi_measure_object"),
    ("Select-Object", "bi_select_object"),
    ("Sort-Object", "bi_sort_object"),
    ("Where-Object", "bi_where_object"),
    ("agent", "bi_agent"),
    ("ai", "bi_ai"),
    ("ai-add-route", "bi_ai_add_route"),
    ("ai-backends", "bi_ai_backends"),
    ("ai-complete", "bi_ai_complete"),
    ("ai-convert-model", "bi_ai_convert_model"),
    ("ai-cost", "bi_ai_cost"),
    ("ai-detect", "bi_ai_detect"),
    ("ai-detect-format", "bi_ai_detect_format"),
    ("ai-explain", "bi_ai_explain"),
    ("ai-fix", "bi_ai_fix"),
    ("ai-gateway", "bi_ai_gateway"),
    ("ai-gpu-memory", "bi_ai_gpu_memory"),
    ("ai-load-balancing", "bi_ai_load_balancing"),
    ("ai-local-backends", "bi_ai_local_backends"),
    ("ai-local-embed", "bi_ai_local_embed"),
    ("ai-local-generate", "bi_ai_local_generate"),
    ("ai-local-load", "bi_ai_local_load"),
    ("ai-local-unload", "bi_ai_local_unload"),
    ("ai-model-fits", "bi_ai_model_fits"),
    ("ai-providers", "bi_ai_providers"),
    ("ai-registry-stats", "bi_ai_registry_stats"),
    ("ai-reset-usage", "bi_ai_reset_usage"),
    ("ai-routes", "bi_ai_routes"),
    ("ai-set-default", "bi_ai_set_default"),
    ("ai-set-load-balancing", "bi_ai_set_load_balancing"),
    ("ai-suggest", "bi_ai_suggest"),
    ("ai-supported-conversions", "bi_ai_supported_conversions"),
    ("ai-usage", "bi_ai_usage"),
    ("ai_add_route", "bi_ai_add_route"),
    ("ai_backends", "bi_ai_backends"),
    ("ai_convert_model", "bi_ai_convert_model"),
    ("ai_cost", "bi_ai_cost"),
    ("ai_detect", "bi_ai_detect"),
    ("ai_detect_format", "bi_ai_detect_format"),
    ("ai_gateway", "bi_ai_gateway"),
    ("ai_gpu_memory", "bi_ai_gpu_memory"),
    ("ai_load_balancing", "bi_ai_load_balancing"),
    ("ai_local_backends", "bi_ai_local_backends"),
    ("ai_local_embed", "bi_ai_local_embed"),
    ("ai_local_generate", "bi_ai_local_generate"),
    ("ai_local_load", "bi_ai_local_load"),
    ("ai_local_unload", "bi_ai_local_unload"),
    ("ai_model_fits", "bi_ai_model_fits"),
    ("ai_providers", "bi_ai_providers"),
    ("ai_registry_stats", "bi_ai_registry_stats"),
    ("ai_reset_usage", "bi_ai_reset_usage"),
    ("ai_routes", "bi_ai_routes"),
    ("ai_set_default", "bi_ai_set_default"),
    ("ai_set_load_balancing", "bi_ai_set_load_balancing"),
    ("ai_supported_conversions", "bi_ai_supported_conversions"),
    ("ai_usage", "bi_ai_usage"),
    ("columns", "bi_columns"),
    ("complete", "bi_ai_complete"),
    ("csv_columns", "bi_csv_columns"),
    ("describe", "bi_describe"),
    ("enumerate", "bi_enumerate"),
    ("explain", "bi_ai_explain"),
    ("explain_effects", "bi_explain_effects"),
    ("fix", "bi_ai_fix"),
    ("foreach", "bi_foreach_object"),
    ("foreach-object", "bi_foreach_object"),
    ("from-csv", "bi_from_csv"),
    ("from-json", "bi_from_json"),
    ("from-yaml", "bi_from_yaml"),
    ("from_csv", "bi_from_csv"),
    ("from_json", "bi_from_json"),
    ("from_yaml", "bi_from_yaml"),
    ("get-content", "bi_get_content"),
    ("get-files", "bi_get_files"),
    ("group", "bi_group_object"),
    ("group-object", "bi_group_object"),
    ("group_by", "bi_group_object"),
    ("handle", "bi_handle"),
    ("handle_drop", "bi_handle_drop"),
    ("handles", "bi_handles"),
    ("irongate", "bi_ai_gateway"),
    ("is_type", "bi_is_type"),
    ("journal", "bi_journal"),
    ("journal_clear", "bi_journal_clear"),
    ("json_set", "bi_json_set"),
    ("lines", "bi_lines"),
    ("measure", "bi_measure_object"),
    ("measure-object", "bi_measure_object"),
    ("ontology_json", "bi_ontology_json"),
    ("ontology_jsonld", "bi_ontology_jsonld"),
    ("ontology_owl", "bi_ontology_owl"),
    ("ontology_shacl", "bi_ontology_shacl"),
    ("open", "bi_open"),
    ("record_summary", "bi_record_summary"),
    ("rewind", "bi_undo"),
    ("select", "bi_select_object"),
    ("select-object", "bi_select_object"),
    ("sort-object", "bi_sort_object"),
    ("sql_value", "bi_sql_value"),
    ("str", "bi_str"),
    ("suggest", "bi_ai_suggest"),
    ("swarm", "bi_swarm"),
    ("to-csv", "bi_to_csv"),
    ("to-json", "bi_to_json"),
    ("to-yaml", "bi_to_yaml"),
    ("to_csv", "bi_to_csv"),
    ("to_json", "bi_to_json"),
    ("to_string", "bi_str"),
    ("to_yaml", "bi_to_yaml"),
    ("type_fields", "bi_type_fields"),
    ("type_name", "bi_type_name"),
    ("type_of", "bi_typeof"),
    ("type_schema", "bi_type_schema"),
    ("typeof", "bi_typeof"),
    ("undo", "bi_undo"),
    ("vault-conversions", "bi_vault_conversions"),
    ("vault-convert", "bi_vault_convert"),
    ("vault-models", "bi_vault_models"),
    ("vault_conversions", "bi_vault_conversions"),
    ("vault_convert", "bi_vault_convert"),
    ("vault_models", "bi_vault_models"),
    ("where-object", "bi_where_object"),
];

/// Whether the builtin dispatcher serves `name` — either half of it.
///
/// A name this answers `false` for is not a builtin: it may be a user-defined
/// function, a module member, or nothing at all. Callers reasoning about safety
/// must treat `false` as *unknown*, never as *harmless*.
pub fn is_dispatched(name: &str) -> bool {
    BUILTIN_LOOKUP.contains_key(name)
        || FALLBACK_BUILTINS
            .binary_search_by_key(&name, |(n, _)| n)
            .is_ok()
}

/// Whether some implementation answers a call to `name`: the dispatcher's own
/// tables, the workflow engine, or a plugin's manifest builtin. Asked before a
/// call is classified, so a name nothing serves is unknown rather than gated.
pub fn is_served(name: &str) -> bool {
    is_dispatched(name)
        || crate::workflow_builtins::serves(name)
        || crate::plugins::is_manifest_builtin(name)
}

/// Names that reach the same implementation, grouped — across both halves of
/// the dispatcher.
///
/// `BUILTIN_LOOKUP` aliases share a dispatch index (`ls` and `list` are both 8);
/// fallback aliases share an arm. Dispatch is by implementation while
/// `safety::effect_of` classifies by *name*, so wherever a group's spellings are
/// classified differently, the weakest one is the one an agent will reach for.
/// This is what lets `safety` close that gap without a second hand-written list.
///
/// Groups of one are omitted: they cannot disagree with anything.
pub fn alias_groups() -> Vec<Vec<&'static str>> {
    let mut by_impl: HashMap<String, Vec<&'static str>> = HashMap::new();
    for (name, idx) in BUILTIN_LOOKUP.iter() {
        by_impl.entry(format!("#{idx}")).or_default().push(name);
    }
    for (name, callee) in FALLBACK_BUILTINS {
        // A name the fast table also serves is dispatched there, so it belongs
        // with that implementation, not with the arm it shadows.
        if BUILTIN_LOOKUP.contains_key(name) {
            continue;
        }
        by_impl.entry((*callee).to_string()).or_default().push(name);
    }
    let mut out: Vec<Vec<&'static str>> = by_impl
        .into_values()
        .filter(|names| names.len() > 1)
        .map(|mut names| {
            names.sort_unstable();
            names.dedup();
            names
        })
        .filter(|names| names.len() > 1)
        .collect();
    out.sort();
    out
}

fn call_with_input_inner(
    name: &str,
    args: Vec<Value>,
    input: Option<Value>,
    env: &mut Env,
) -> Result<Value> {
    // A name nothing serves is unknown, and it is reported as unknown before any
    // gate. `exec` is classified `Exec` by name, so without this `exec("x")` was
    // refused for approval, for a builtin that does not exist. Only a name no
    // implementation serves is answered here; a served name is gated as before.
    if !is_served(name) {
        return Err(crate::safety::unknown_builtin_hinted(
            name,
            did_you_mean(name),
            crate::module_loader::unexported_hint(name),
        ));
    }

    // Enforce policy before the builtin runs. `effect_of` only ever *described*
    // an operation's danger; this is where the description starts to constrain.
    // Builtins that guard themselves are skipped so one action is not admitted
    // twice. The read jail comes first, so no approval token is issued for a
    // path the jail refuses.
    crate::security::read_jail_dispatch(name, &args, input.is_some())?;
    crate::safety::guard_dispatch(name, &args)?;

    // Capture what a mutating call is about to overwrite, so the session can be
    // rewound. This is the one place every builtin passes through, which is why
    // it is here rather than at ~300 call sites — the same reason this function
    // is already the single boundary for error structuring.
    //
    // Agent surface only. The comment here used to say the common path cost
    // one `matches!`; in fact `mark()` locked the journal and, while it was
    // empty, listed the session directory on disk -- every builtin call, in
    // every mode. With journalling off (the human default) nothing is marked,
    // and `rollback_to(usize::MAX)` below is a no-op.
    //
    // Only a call that can write is journalled (`record_before` ignores the
    // rest), so only such a call needs to know whether journalling is on --
    // which is three environment reads, 27% of a `len([x])` call when every
    // call asked. Skipping the mark for a non-writing builtin also stops a
    // failing `map` from rolling back the entry for a write its lambda did
    // make.
    let effect = crate::safety::effect_of(name);
    let journal_on = matches!(
        effect,
        crate::safety::Effect::WriteLocal | crate::safety::Effect::Destructive
    ) && crate::journal::enabled();
    let journal_mark = if journal_on {
        let m = crate::journal::mark();
        crate::journal::record_before(name, effect, &args);
        m
    } else {
        usize::MAX
    };

    // Try fast lookup first. Decide *which* table serves the name before
    // handing the arguments over, so they move instead of being copied: this
    // cloned the whole pipe input on every call -- twice for a builtin in the
    // fallback match -- and `cat("src/*.rs") | lines | len` spent most of its
    // time deep-copying 128,000 strings it was about to count.
    if let Some(index) = fast_index(name) {
        let result = fast_builtin_lookup(index, args, input, env);
        // A call that failed changed nothing, so it must leave nothing behind to
        // undo. Without this a write refused by the workspace jail still left an
        // entry, and `undo()` answered `complete: false` about an operation that
        // never ran. A call that succeeded but reported no change (a `file_patch`
        // whose pattern was not found) is the same case: its step is dropped too.
        // A successful call has its steps sealed with the state it left; a failed
        // one, or one that reported no change, leaves no step (see journal::settle).
        if journal_on {
            crate::journal::settle(journal_mark, result.is_ok());
        }
        return result;
    }

    // The workflow engine's own surface. It lives in its own module because it
    // is the one family of builtins that has to bridge to an async engine, and
    // that bridge has to know which kind of runtime it was called from.
    if crate::workflow_builtins::serves(name) {
        let result = crate::workflow_builtins::dispatch(name, args, input);
        if journal_on {
            crate::journal::settle(journal_mark, result.is_ok());
        }
        return result;
    }

    // Fall back to the comprehensive match for functions not in fast lookup.
    // Its result is settled the same way as the fast table's, so a fallback
    // writer (file_insert, for one) leaves a sealed step, or none on failure.
    let result = match name {
        // PowerShell-style cmdlets (not in fast lookup)
        "Get-Files" | "get-files" => bi_get_files(args, input),
        "Get-Content" | "get-content" => bi_get_content(args, input),
        "Select-Object" | "select-object" | "select" => bi_select_object(args, input),
        "Where-Object" | "where-object" => bi_where_object(args, input, env),
        "ForEach-Object" | "foreach-object" | "foreach" => bi_foreach_object(args, input, env),
        "Sort-Object" | "sort-object" => bi_sort_object(args, input),
        "Group-Object" | "group-object" | "group" | "group_by" => bi_group_object(args, input, env),
        "Measure-Object" | "measure-object" | "measure" => bi_measure_object(args, input),

        // Nushell-style data commands (not in fast lookup)
        "from-json" | "from_json" => bi_from_json(args, input),
        "sql_value" => bi_sql_value(args, input),
        "lines" => bi_lines(args, input),
        "open" => bi_open(args, input),
        "explain_effects" => bi_explain_effects(args),
        "to-json" | "to_json" => bi_to_json(args, input),
        "from-csv" | "from_csv" => bi_from_csv(args, input),
        "to-csv" | "to_csv" => bi_to_csv(args, input),
        "csv_columns" => bi_csv_columns(args, input),
        "enumerate" => bi_enumerate(args, input),
        "json_set" => bi_json_set(args, input),
        "from-yaml" | "from_yaml" => bi_from_yaml(args, input),
        "to-yaml" | "to_yaml" => bi_to_yaml(args, input),
        "columns" => bi_columns(args, input),
        "describe" => bi_describe(args, input),

        // AI-enhanced commands (not in fast lookup)
        "ai" => bi_ai(args, input, env),
        "ai-suggest" | "suggest" => bi_ai_suggest(args, input, env),
        "ai-explain" | "explain" => bi_ai_explain(args, input, env),
        "ai-complete" | "complete" => bi_ai_complete(args, input, env),
        "ai-fix" | "fix" => bi_ai_fix(args, input, env),

        // AI/Agents (not in fast lookup)
        "agent" => bi_agent(args, input, env),
        "swarm" => bi_swarm(args, input, env),

        // AI Backend Detection (not in fast lookup)
        "ai_backends" | "ai-backends" => bi_ai_backends(args, input),
        "ai_detect" | "ai-detect" => bi_ai_detect(args, input),

        // AI Cost Tracking
        "ai_usage" | "ai-usage" => bi_ai_usage(),
        "ai_cost" | "ai-cost" => bi_ai_cost(),
        "ai_reset_usage" | "ai-reset-usage" => bi_ai_reset_usage(input),

        // GPU Memory Management
        "ai_gpu_memory" | "ai-gpu-memory" => bi_ai_gpu_memory(input),
        "ai_model_fits" | "ai-model-fits" => bi_ai_model_fits(args, input),

        // Provider Routing & Registry
        "ai_providers" | "ai-providers" => bi_ai_providers(),
        "ai_routes" | "ai-routes" => bi_ai_routes(),
        "ai_add_route" | "ai-add-route" => bi_ai_add_route(args, input),
        "ai_set_default" | "ai-set-default" => bi_ai_set_default(args, input),
        "ai_registry_stats" | "ai-registry-stats" => bi_ai_registry_stats(),
        "ai_set_load_balancing" | "ai-set-load-balancing" => bi_ai_set_load_balancing(args, input),
        "ai_load_balancing" | "ai-load-balancing" => bi_ai_load_balancing(),

        // Model Format Conversion
        "ai_convert_model" | "ai-convert-model" => bi_ai_convert_model(args, input),
        // Kept on one line: tests/fallback_dispatch.rs reads each arm's callee
        // from its own line, and rustfmt would wrap this one into a block.
        #[rustfmt::skip]
        "ai_supported_conversions" | "ai-supported-conversions" => bi_ai_supported_conversions(input),
        "ai_detect_format" | "ai-detect-format" => bi_ai_detect_format(args),

        // The NERVOSYS stack: routing, inference, model store
        "ai_gateway" | "ai-gateway" | "irongate" => bi_ai_gateway(input),
        "vault_models" | "vault-models" => bi_vault_models(input),
        "vault_conversions" | "vault-conversions" => bi_vault_conversions(input),
        "vault_convert" | "vault-convert" => bi_vault_convert(args, input),

        // Local Inference
        "ai_local_backends" | "ai-local-backends" => bi_ai_local_backends(),
        "ai_local_load" | "ai-local-load" => bi_ai_local_load(args, input),
        "ai_local_generate" | "ai-local-generate" => bi_ai_local_generate(args, input),
        "ai_local_embed" | "ai-local-embed" => bi_ai_local_embed(args, input),
        "ai_local_unload" | "ai-local-unload" => bi_ai_local_unload(args, input),

        // Runtime Type Introspection
        "str" | "to_string" => bi_str(args, input),
        "typeof" | "type_of" => bi_typeof(args, input),
        "type_name" => bi_type_name(args, input),
        "type_fields" => bi_type_fields(args, input),
        "type_schema" => bi_type_schema(args, input),
        "is_type" => bi_is_type(args),

        // Ontology Export
        "ontology_json" => bi_ontology_json(),
        "ontology_jsonld" => bi_ontology_jsonld(),
        "ontology_owl" => bi_ontology_owl(),
        "ontology_shacl" => bi_ontology_shacl(),

        // Result handles (§ see crate::handles). Registered here rather than in
        // BUILTIN_LOOKUP because that table is index-coupled to BUILTIN_DISPATCH;
        // reachability is identical and the handle summary carries its own usage
        // hint, so discovery does not depend on the ontology listing.
        "handle" => bi_handle(args, input),
        "handles" => bi_handles(),
        "handle_drop" => bi_handle_drop(args),

        // Reversible sessions (see crate::journal).
        "undo" | "rewind" => bi_undo(args, input),
        "journal" => bi_journal(),
        "record_summary" => bi_record_summary(args, input),
        "journal_clear" => bi_journal_clear(input),

        // A `[builtins]` entry of a loaded plugin (see crate::plugins). Core names
        // are matched above and a plugin cannot register one, so this never
        // shadows a builtin.
        _ if crate::plugins::is_manifest_builtin(name) => {
            crate::plugins::call_manifest_builtin(name, args, input)
        }
        _ => Err(crate::safety::unknown_builtin_hinted(
            name,
            did_you_mean(name),
            crate::module_loader::unexported_hint(name),
        )),
    };
    if journal_on {
        crate::journal::settle(journal_mark, result.is_ok());
    }
    result
}

// --------------- Helpers: type extraction ---------------

fn expect_array<'a>(name: &str, v: &'a Value) -> Result<&'a [Value]> {
    if let Value::Array(a) = v {
        Ok(a.as_slice())
    } else {
        Err(crate::safety::bad_arg(name, "an array", v.type_name()))
    }
}

fn expect_int(name: &str, v: &Value) -> Result<i64> {
    match v {
        Value::Int(n) => Ok(*n),
        Value::Float(f) if f.fract() == 0.0 => Ok(*f as i64),
        _ => Err(crate::safety::bad_arg(name, "an integer", v.type_name())),
    }
}

/// A lookup key: a name, id, token or query. A string, or an integer id;
/// anything else was stringified and looked up, so `job_status({})` answered
/// "no such job" and `user_roles([1])` answered "no roles" at exit 0.
fn key_arg(builtin: &str, v: Value) -> Result<String> {
    match v {
        Value::Str(s) => Ok(s),
        Value::Int(n) => Ok(n.to_string()),
        other => Err(crate::safety::bad_arg(
            builtin,
            "a string or integer id",
            other.type_name(),
        )),
    }
}

/// Refuse a piped subject for a builtin that does not document one.
///
/// Without this, `"x" | mcp_servers()` ran as if the pipe were not there: the
/// body never looked at its input, and nothing said so.
fn refuse_piped(name: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            name,
            "no piped subject (a direct call)",
            "a piped value",
        ));
    }
    Ok(())
}

/// A catalogue tool that ran and failed, as the coded `E_TOOL_FAILED`.
///
/// `tool_failed` takes an exit status; an MCP tool result carries only text,
/// so this builds the same error without inventing a status.
fn mcp_tool_failed(tool: &str, text: &str) -> anyhow::Error {
    let said = text.trim();
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::ToolFailed,
        message: format!(
            "mcp_call: tool `{tool}` failed{}",
            if said.is_empty() {
                " and printed nothing".to_string()
            } else {
                format!(": {said}")
            }
        ),
        builtin: "mcp_call".to_string(),
        hint: format!(
            "the tool `{tool}` rejected this call; check its arguments against mcp_tools()"
        ),
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("`{tool}` to succeed"),
        got: "a failure".to_string(),
        extra: serde_json::Map::new(),
    })
}

fn expect_string<'a>(name: &str, v: &'a Value) -> Result<&'a str> {
    if let Value::Str(s) = v {
        Ok(s.as_str())
    } else {
        Err(crate::safety::bad_arg(name, "a string", v.type_name()))
    }
}

fn need_lambda<'a>(v: &'a Value, name: &str) -> Result<&'a Lambda> {
    if let Value::Lambda(l) = v {
        Ok(l)
    } else {
        Err(crate::safety::bad_arg(name, "a lambda", v.type_name()))
    }
}

/// Fetch a required positional argument, or return a structured `E_BAD_ARG`
/// naming what was expected when it is missing — the arity counterpart to the
/// `expect_*` type helpers. Lets a builtin surface a catchable, branchable
/// missing-argument error instead of ad-hoc prose (or an index panic).
#[allow(dead_code)]
fn arg<'a>(builtin: &str, args: &'a [Value], idx: usize, expected: &str) -> Result<&'a Value> {
    args.get(idx)
        .ok_or_else(|| crate::safety::bad_arg(builtin, expected, "nothing"))
}

/// Gate a network-egress builtin through the safety guard with the `Network`
/// effect, so the resource governor (`IRONSHELL_MAX_NET`) bounds egress and the
/// audit log records the request. `Network` is policy-`allow` in agent mode, so
/// this meters and audits rather than prompting.
///
/// Egress containment lives in `safety::guard`, which every `Network` call
/// reaches, not only these: `IRONSHELL_NET_ALLOW` (hosts and their subdomains,
/// `;`- or `,`-separated, `*` for any) refuses other destinations with
/// `E_POLICY_DENY`, and in agent mode with no allowlist a request needs
/// approval.
pub(crate) fn guard_network(builtin: &str, url: &str) -> Result<()> {
    // Every one of these builtins hands the URL to `curl` or `wget` in a
    // positional slot, so a leading `-` is read as an option rather than an
    // address — and `curl -K<file>` reads a config file that can set `output`
    // and `url`, which turns a fetch into an arbitrary write. Checking it here
    // rather than at each of the fourteen call sites is the point: this is the
    // one door every network builtin already goes through, so a site added
    // later inherits the check instead of having to remember it. No legitimate
    // URL begins with `-`.
    crate::safety::reject_option_like(builtin, &[url.to_string()])?;

    crate::safety::guard(crate::safety::GuardCtx {
        builtin,
        effect: crate::safety::Effect::Network,
        what: "request",
        targets: vec![url.to_string()],
        blast_radius: serde_json::json!({ "url": url }),
        reversible: true,
        fs_paths: false,
    })?;
    Ok(())
}

/// Jail a caller-supplied path that the builtin is about to write, exactly as
/// `file_write` does — resolve it workspace-relative, then guard it as
/// `WriteLocal` with `fs_paths: true`.
///
/// A download has two effects and the effect taxonomy carries one. `web_download`,
/// `wget_download` and `web_upload_file` are classified `Network` by the `web_*`
/// prefix rule, they call [`guard_network`] on the URL, and they are in
/// `SELF_GUARDED` — so they look fully gated at every place a reader would check.
/// None of that touches the file. `guard_network` passes `fs_paths: false` and
/// `Effect::Network`, and the jail in `safety::guard` fires only when the effect
/// `is_filesystem()` *and* `fs_paths` is set, so the path went through no check
/// at all: `web.download <url> C:\outside\workspace\x` wrote there in agent mode
/// while `file.write` to the identical path was refused.
///
/// Returns the workspace-resolved path, so a relative path lands inside the jail
/// rather than beside the process's working directory — the same treatment
/// `file_write` gives it, and it also removes the option-injection question,
/// since a resolved absolute path cannot begin with `-`.
fn guard_local_write(builtin: &str, path: &str) -> Result<String> {
    let path = crate::safety::resolve_path_str(path);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin,
        effect: crate::safety::Effect::WriteLocal,
        what: "write",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({ "path": path }),
        reversible: true,
        fs_paths: true,
    })?;
    Ok(path)
}

/// The `Destructive` counterpart of [`guard_local_write`], for a move.
///
/// `fs::rename` removes the source and can overwrite the destination, so it is
/// not the same promise as a write — `Destructive` is `approve` in agent mode
/// rather than `allow`. That is a real change in what an agent may do without
/// asking, and it is the honest one: `file_delete_lines` is already
/// `Destructive` for altering a file in place, and moving one over another is
/// not the smaller act.
///
/// Both ends go through one `guard` call, so a move is one action with one
/// approval token. The token is hashed over both targets, so it approves this
/// source-to-destination pair and no other. Guarding each end separately gave
/// two tokens, and a re-run with the first one asked for the second.
fn guard_local_move(builtin: &str, from: &str, to: &str) -> Result<(String, String)> {
    let from = crate::safety::resolve_path_str(from);
    let to = crate::safety::resolve_path_str(to);
    // A move onto an existing path replaces it, and the approval says so. The
    // destination is not probed when it names a remote share (see safety).
    let mut blast_radius = serde_json::json!({ "from": from, "to": to });
    if !crate::safety::names_a_remote_share(&to) && std::path::Path::new(&to).exists() {
        blast_radius["overwrites"] = serde_json::json!(true);
    }
    crate::safety::guard(crate::safety::GuardCtx {
        builtin,
        effect: crate::safety::Effect::Destructive,
        what: "move",
        targets: vec![from.clone(), to.clone()],
        blast_radius,
        reversible: false,
        fs_paths: true,
    })?;
    Ok((from, to))
}

// There is deliberately no read counterpart for `web_upload_file`. The jail in
// `safety::guard` fires only for `WriteLocal` and `Destructive` — `ReadLocal` is
// unjailed by design, and `file.read` of a path outside the workspace followed
// by `web.post` is already an allowed pair. Jailing the upload would be a policy
// change invented here rather than an inconsistency being corrected, so it is
// left as it is and named instead. `tests/network_write_jail.rs` pins the
// distinction so it stays a decision rather than an oversight.

/// Evaluate a lambda with N positional arguments by temporarily binding its `params`
/// in the environment, then `eval_expr` on its body. Restores env afterwards.
fn call_lambda(lam: &Lambda, args: &[Value], env: &mut Env) -> Result<Value> {
    // Finding 13: unbounded self-recursion used to overflow the stack and abort
    // the process, which no error handling could catch. The guard is held for
    // the whole call, so the depth unwinds even when an inner call returns Err.
    let _depth = crate::safety::enter_call()?;

    let params = &lam.params;
    if params.len() != args.len() {
        return Err(crate::safety::arg_err(format!(
            "lambda expected {} args, got {}",
            params.len(),
            args.len()
        )));
    }

    // Save and clear pipe input to prevent it from leaking into lambda
    // evaluation.
    //
    // This used to *clone* the pipe input rather than take it, and that clone
    // was the single largest cost in the shell. In `xs | map(fn(x) => ...)`
    // the pipe input at this point is the whole of `xs`, so the collection was
    // deep-copied once per element: 500 records of GitHub issue data cost
    // 237 ms for a closure that ignored its argument entirely, and `map` over
    // N integers ran in O(N^2) -- 10,000 elements took 515 ms where jq took 7.
    // Taking the value moves it; `set_input` below puts it back, so the
    // observable behaviour is identical.
    let saved_pipe = env.take_input();

    let (result, _) = bind_eval_unbind(lam, args.to_vec(), env, false);
    // Restore pipe input
    env.set_input(saved_pipe);
    result
}

/// Call a lambda with arguments it may keep: they are moved into the
/// parameter bindings instead of cloned, and, with `give_back`, taken out again
/// afterwards and returned. A lambda body is one expression with no way to
/// rebind a parameter, so what comes back is what went in -- which is what
/// lets `where` test an element without copying it first.
pub(crate) fn call_lambda_owned(
    lam: &Lambda,
    args: Vec<Value>,
    env: &mut Env,
    give_back: bool,
) -> Result<(Value, Vec<Value>)> {
    let _depth = crate::safety::enter_call()?;
    if lam.params.len() != args.len() {
        return Err(crate::safety::arg_err(format!(
            "lambda expected {} args, got {}",
            lam.params.len(),
            args.len()
        )));
    }
    let saved_pipe = env.take_input();
    let (result, back) = bind_eval_unbind(lam, args, env, give_back);
    env.set_input(saved_pipe);
    result.map(|r| (r, back))
}

/// `call_lambda_owned` for the one-parameter lambda, which is nearly every
/// `map`/`where` predicate: the same binding discipline with no vectors, so a
/// call allocates nothing beyond the parameter's name.
pub(crate) fn call_lambda_one(
    lam: &Lambda,
    arg: Value,
    env: &mut Env,
    give_back: bool,
) -> Result<(Value, Option<Value>)> {
    let _depth = crate::safety::enter_call()?;
    let [p] = lam.params.as_slice() else {
        return Err(crate::safety::arg_err(format!(
            "lambda expected {} args, got 1",
            lam.params.len()
        )));
    };
    // Captured free variables go in under the parameter (a parameter of the
    // same name wins) and come out after it: without them a curried lambda,
    // `fn(n) => fn(x) => x * n`, called from map or where saw `n` unbound.
    let restore_caps = crate::eval::install_captured(&lam.captured, env);
    let saved_pipe = env.take_input();
    let prev = env.replace_param(p, arg);
    let result = eval_expr(&lam.body, env);
    let cur = env.restore_param(p, prev);
    env.set_input(saved_pipe);
    crate::eval::restore_captured(restore_caps, env);
    result.map(|r| (r, if give_back { cur } else { None }))
}

/// Bind `args` to the lambda's parameters, evaluate its body, and restore
/// whatever those names were bound to before. Previous bindings are moved
/// out and back rather than cloned.
fn bind_eval_unbind(
    lam: &Lambda,
    args: Vec<Value>,
    env: &mut Env,
    give_back: bool,
) -> (Result<Value>, Vec<Value>) {
    // Captured free variables first, under the parameters; see call_lambda_one.
    let restore_caps = crate::eval::install_captured(&lam.captured, env);
    let mut saved: Vec<Option<Value>> = Vec::with_capacity(args.len());
    for (p, a) in lam.params.iter().zip(args) {
        saved.push(env.replace_param(p, a));
    }
    // A caller that wants the parameters back must see them unchanged; one
    // that does not lets the body consume them (see eval_body_consuming_params).
    let result = if give_back {
        eval_expr(&lam.body, env)
    } else {
        crate::eval::eval_body_consuming_params(&lam.body, &lam.params, env)
    };
    let mut back = Vec::new();
    for (p, prev) in lam.params.iter().zip(saved).rev() {
        let cur = env.restore_param(p, prev);
        if give_back {
            back.push(cur.unwrap_or(Value::Null));
        }
    }
    back.reverse();
    crate::eval::restore_captured(restore_caps, env);
    (result, back)
}

/// Allocate parameter names once for a collection, not once per element.
/// Restore shadowed values on success and on errors, including nested calls.
fn with_param_slots<T>(
    lam: &Lambda,
    env: &mut Env,
    run: impl FnOnce(&mut Env) -> Result<T>,
) -> Result<T> {
    let saved: Vec<_> = lam
        .params
        .iter()
        .map(|name| env.replace_param(name, Value::Null))
        .collect();
    let result = run(env);
    for (name, old) in lam.params.iter().zip(saved).rev() {
        env.restore_param(name, old);
    }
    result
}

// --------------- General builtins ---------------

/// help() is the short reference; help("name") is ontology_describe("name").
fn bi_help_entry(args: Vec<Value>) -> Result<Value> {
    // Documentation is read whole; a handle to it is a round trip for nothing.
    crate::handles::show_next_whole();
    if args.is_empty() {
        bi_help()
    } else {
        bi_ontology_describe(args, None)
    }
}

fn bi_help() -> Result<Value> {
    let txt = r#"Æther (æ) built-ins:
- help                         # this help
- clear                        # clear screen (prints ANSI)
- echo <...values>             # echo stringified values
- print <value>                # pretty-print value (returns text)

Data / pipelines:
- map    <array> <fn(x)=> expr>             # map over array
- where  <array> <fn(x)=> predicate>        # filter array
- reduce <array> <fn(x,y)=> expr> <init>    # fold array
- take   <array> <n>                        # take first n elements
- first  <array>                            # get first element
- last   <array>                            # get last element
- any    <array> [fn(x)=> pred]             # check if any match
- all    <array> [fn(x)=> pred]             # check if all match
- keys   <record>                           # get record keys
- len    <array|record|string>              # get length
- type_of <value>                           # get type name

String functions:
- split      <string> <delimiter>           # split into array
- join       <array> <delimiter>            # join into string
- trim       <string>                       # remove whitespace
- upper      <string>                       # to uppercase
- lower      <string>                       # to lowercase
- replace    <string> <old> <new>           # replace substring
- contains   <string> <substring>           # check if contains
- starts_with <string> <prefix>             # check prefix
- ends_with  <string> <suffix>              # check suffix

Array functions:
- flatten    <array>                        # flatten nested arrays
- reverse    <array|string>                 # reverse order
- slice      <array|string> <start> [end]   # extract slice
- range      <end>  OR  <start> <end> [step] # generate range
- zip        <array1> <array2>              # zip into pairs
- push       <array> <item>                 # append item
- concat     <array1> <array2>              # concatenate
- sort       <array>                        # sort array
- uniq       <array>                        # unique values

Math functions:
- abs        <number>                       # absolute value
- min        <a> <b>                        # minimum
- max        <a> <b>                        # maximum
- floor      <number>                       # round down
- ceil       <number>                       # round up
- round      <number>                       # round nearest
- sqrt       <number>                       # square root
- pow        <base> <exponent>              # power

Utility functions:
- exit       [code]                         # exit program
- env        <key>                          # get env variable
- set_env    <key> <value>                  # set env variable
- sleep      <seconds>                      # sleep duration
- time       ()                             # current timestamp
- json_parse <json_string>                  # parse JSON
- json_stringify <value>                    # to JSON string

File system:
- ls         [path]                         # list directory
- pwd        ()                             # current directory
- cat        <file>                         # read file
- read_text  <file>                         # read file (alias)
- head       <file> [n]                     # first n lines
- tail       <file> [n]                     # last n lines
- find       <path> [pattern]               # find files
- grep       <pattern> [file]               # search lines (of file, or of piped text)
- wc         <file|array>                   # count lines

HTTP:
- http_get <url>                # fetch URL → {url,status,headers,body}

AI Backend Detection:
- ai_backends                   # list available AI backends with details
- ai_detect                     # auto-select best available AI backend

MCP Server Integration (Discovery):
- mcp_servers                   # list available MCP servers and tools
- mcp_detect [endpoint]         # find specific MCP server or first available
- mcp_cache_clear               # clear MCP detection cache
- mcp_cache_status              # get cache status info

MCP Server/Client (Enhanced):
- mcp_server [config]           # create local MCP server for AI tools
- mcp_tools  [filter]           # list MCP tools with schemas
- mcp_call   <name> [args]      # call MCP tool by name
- mcp_resources [type]          # list MCP resources
- mcp_prompts [name]            # list prompts or get specific one
- mcp_connect <endpoint>        # connect to external MCP server

OS Tools (40+ tools for AI agents):
- tools       [category]        # list available OS tools
- tool_info   <name>            # get detailed tool information
- tool_search <query>           # search tools by keyword
- tool_schema <name>            # get tool input schema
- tool_exec   <name> [args]     # execute tool

Syntax Knowledge Base:
- syntax_get      <id>                      # get syntax entry by ID
- syntax_list     [category]                # list all syntax IDs (optional filter)
- syntax_search   <query>                   # search entries by keyword
- syntax_add      <record>                  # add new syntax entry
- syntax_categories ()                      # list all categories
- ab_encode       <msg_type> <opcode> <payload>  # encode AgenticBinary message
- ab_decode       <bytes>                   # decode AgenticBinary message

AI / Agents (require ai module present):
- agent <goal> [tools...] [max_steps] [dry_run]
- swarm <json-config|record>  OR  <goal> [tools...] [max_steps] [dry_run]

Recursive Language Models (RLM):
- rlm_agent <goal> [tools] [config]         # run agent that can spawn subagents
- rlm_config {opts}                         # create RLM configuration
- rlm_stats  ()                             # get hierarchy statistics
- rlm_spawn  <name> <goal> [tools]          # spawn a single subagent

RLM Configuration Options:
  {max_depth: 5, max_agents: 50, timeout: 60, trace: true}

Examples:
  # Pipelines
  [1,2,3] | map(fn(x)=> x*2) | reduce(fn(a,b)=> a+b, 0)
  [5,4,3,2,1] | where(fn(x)=> x>2) | take(2) | print
  
  # String operations
  "hello,world" | split(",") | map(fn(s)=> s | upper()) | join("-")
  
  # Array operations
  range(10) | where(fn(x)=> x % 2 == 0) | print
  [[1,2],[3,4]] | flatten() | reverse()
  
  # Math
  range(1, 11) | map(fn(x)=> pow(x, 2)) | reduce(fn(a,b)=> a+b, 0)
  
  # JSON
  {name: "Alice", age: 30} | json_stringify() | json_parse()
  
AI & MCP Integration:
  model = ai_detect()            # auto-detect AI backend
  server = mcp_detect()          # find MCP server
  agent("task", model, server.tools)  # use both together

One builtin in full (signature, effect, parameters, examples): help("name")
Every category and its builtins: ontology_manifest(), then ontology_describe("category")
"#;
    Ok(Value::Str(txt.to_string()))
}

fn bi_clear() -> Result<Value> {
    // CSI 2J (clear screen) + CSI H (cursor home)
    Ok(Value::Str("\u{1b}[2J\u{1b}[H".to_string()))
}

fn bi_echo(args: &[Value], input: Option<Value>) -> Result<Value> {
    // `"hello" | echo()` answered "": the dispatch row dropped the pipe
    // input, so a piped value vanished. With no arguments, echo the subject.
    if args.is_empty() {
        if let Some(v) = input {
            return Ok(Value::Str(format_value_one_line(&v)));
        }
    }
    let mut s = String::new();
    for (i, v) in args.iter().enumerate() {
        if i > 0 {
            s.push(' ');
        }
        s.push_str(&format_value_one_line(v));
    }
    Ok(Value::Str(s))
}

fn bi_print(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Determine the target Value (either piped input or first arg).
    let target = if let Some(v) = input {
        v
    } else {
        args.into_iter()
            .next()
            .ok_or_else(|| crate::safety::arg_err("print expects a value"))?
    };

    // (Removed an unused strip_ansi helper; tests have their own)

    // Print the pretty display to stdout. `display_full`, not
    // `display_inline`: the latter caps at 80 characters, which silently threw
    // away the tail of anything longer that a script tried to print.
    // A String is written as its text. The pretty display quotes it, which is
    // right for showing a value and wrong for printing one: `print("x")` wrote
    // `"x"`, and a newline escape in the text was shown, not written.
    let pretty = match &target {
        Value::Str(s) => s.clone(),
        other => {
            crate::value::pretty::display_full(other, &crate::value::pretty::Theme::for_stdout())
        }
    };
    println!("{}", pretty);

    // Helper to strip ANSI color sequences from a string
    fn strip_ansi(s: &str) -> String {
        let mut out = String::new();
        let mut it = s.chars().peekable();
        while let Some(ch) = it.next() {
            if ch == '\x1b' {
                if let Some('[') = it.peek() {
                    it.next();
                    while let Some(&c) = it.peek() {
                        it.next();
                        if c == 'm' {
                            break;
                        }
                    }
                    continue;
                }
            }
            out.push(ch);
        }
        out
    }

    // Return behavior: always return the pretty inline display (ANSI stripped)
    // as a `Str`. This keeps the REPL and tests consistent regardless of
    // whether the input was a bare string or another value. The runner
    // compares a final value with this text to tell an echo from a print.
    let printed = strip_ansi(&pretty);
    record_print(&printed);
    Ok(Value::Str(printed))
}

thread_local! {
    /// How many print calls have run on this thread, and the text the last one
    /// returned. The runner reads both around its final statement: a value that
    /// is exactly the text a print of that statement returned is not echoed.
    static PRINTS: std::cell::RefCell<(usize, String)> =
        const { std::cell::RefCell::new((0, String::new())) };
}

fn record_print(text: &str) {
    PRINTS.with(|p| {
        let mut p = p.borrow_mut();
        p.0 += 1;
        p.1 = text.to_string();
    });
}

/// The print count on this thread, and the text the last print returned.
pub fn print_mark() -> (usize, String) {
    PRINTS.with(|p| p.borrow().clone())
}

/// http_get — fetch one http(s) URL. Usage: http_get(url) or url | http_get.
/// Returns {url, status, headers, body}. The URL passes the network guard and
/// the SSRF rules, and each redirect target passes the same rules before it is
/// followed, at most 5 of them. A non-2xx status is an answer, not a failure.
/// The body is read up to 16 MiB; more is E_BUDGET_EXCEEDED. A request that gets
/// no answer is a coded E_IO, never an empty body. Invalid UTF-8 is replaced.
fn bi_http_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use std::io::Read as _;
    net_refuse_in_transaction("http_get")?;
    if args.len() > 1 {
        return Err(crate::safety::arg_err(format!(
            "http_get takes one URL, got {}",
            args.len()
        )));
    }
    let url_val = match (input, args.into_iter().next()) {
        (Some(_), Some(_)) => {
            return Err(crate::safety::arg_err(
                "http_get takes its URL either as an argument or piped in, not both",
            ))
        }
        (Some(v), None) | (None, Some(v)) => v,
        (None, None) => return Err(crate::safety::arg_err("http_get expects URL string/uri")),
    };
    let url = match url_val {
        Value::Str(s) | Value::Uri(s) => s,
        other => {
            return Err(crate::safety::bad_arg(
                "http_get",
                "a URL String",
                other.type_name(),
            ))
        }
    };
    guard_network("http_get", &url)?;
    // Each hop is checked, and connected to at the address its check accepted,
    // so neither the first URL nor a redirect target is resolved twice.
    let first = crate::security::check_http_url("http_get", &url)?;
    let validated_url = first.url.clone();
    let mut hop = first;
    let mut answer = None;
    for _ in 0..=HTTP_MAX_REDIRECTS {
        let client = crate::security::create_hop_client(Some(&hop))?;
        let sent = client
            .get(&hop.url)
            .send()
            .map_err(|e| net_io_error("http_get", "request", &e))?;
        let location = sent
            .headers()
            .get(reqwest::header::LOCATION)
            .and_then(|v| v.to_str().ok())
            .map(str::to_string);
        match crate::security::judged_redirect(
            "http_get",
            &hop.url,
            sent.status().as_u16(),
            location.as_deref(),
        )? {
            Some(next) => hop = next,
            None => {
                answer = Some(sent);
                break;
            }
        }
    }
    let mut resp = answer.ok_or_else(|| {
        crate::safety::budget_exceeded(
            "http_get",
            format!("more than {HTTP_MAX_REDIRECTS} redirects"),
            "request the final URL directly",
        )
    })?;
    let status = i64::from(resp.status().as_u16());
    let mut headers_rec = BTreeMap::<String, Value>::new();
    for (k, v) in resp.headers().iter() {
        headers_rec.insert(
            k.to_string(),
            Value::Str(String::from_utf8_lossy(v.as_bytes()).into_owned()),
        );
    }
    let mut bytes = Vec::new();
    std::io::Read::take(&mut resp, HTTP_BODY_MAX + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| net_io_error("http_get", "reading the body", &e))?;
    if bytes.len() as u64 > HTTP_BODY_MAX {
        return Err(crate::safety::budget_exceeded(
            "http_get",
            format!("the body is more than {HTTP_BODY_MAX} bytes"),
            "fetch a smaller resource",
        ));
    }
    let mut out = BTreeMap::<String, Value>::new();
    out.insert("url".into(), Value::Str(validated_url));
    out.insert("status".into(), Value::Int(status));
    out.insert("headers".into(), Value::Record(headers_rec));
    out.insert(
        "body".into(),
        Value::Str(String::from_utf8_lossy(&bytes).into_owned()),
    );
    Ok(Value::Record(out))
}

fn bi_call(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    // call <name> [args...]
    let name_val = args
        .first()
        .cloned()
        .ok_or_else(|| crate::safety::bad_arg("call", "a builtin name", "nothing"))?;
    let name = match name_val {
        Value::Str(s) | Value::Uri(s) => s,
        other => {
            return Err(crate::safety::arg_err(format!(
                "call: expected String builtin name, got {:?}",
                other
            )));
        }
    };
    // remaining args (after name)
    let mut rem: Vec<Value> = Vec::new();
    for v in args.into_iter().skip(1) {
        rem.push(v);
    }
    // If input was provided, pass it as pipe input to the called builtin
    call_with_input(&name, rem, input, env)
}

// --------------- Data / pipeline builtins ---------------

fn bi_map(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    let piped = input.is_some();
    let lam_val = if piped {
        arg("map", &args, 0, "a lambda")?
    } else {
        arg("map", &args, 1, "a lambda")?
    };
    let lam = need_lambda(lam_val, "map")?;
    // The array is owned here -- piped or the first argument -- so it is
    // consumed, not copied. This cloned the whole input before starting and
    // then every element again for the lambda.
    let arr_val = match input {
        Some(v) => v,
        None => args
            .first()
            .cloned()
            .ok_or_else(|| crate::safety::bad_arg("map", "an array", "nothing"))?,
    };
    expect_array("map", &arr_val)?;
    let Value::Array(items) = arr_val else {
        unreachable!("expect_array accepted it")
    };
    // Both `fn(x, i)` and `fn(x)` are supported. This used to be discovered by
    // calling with two arguments and retrying with one on failure, which made
    // three copies of every element (`.cloned()`, `v_clone`, and the call's
    // own `v.clone()`) to keep the retry path alive. The lambda knows its own
    // arity, so ask it once.
    let two_arg = lam.params.len() == 2;
    let mut out = Vec::with_capacity(items.len());
    if items.is_empty() {
        return Ok(Value::Array(out));
    }
    with_param_slots(lam, env, |env| {
        for (i, v) in items.into_iter().enumerate() {
            let y = if two_arg {
                call_lambda_owned(lam, vec![v, Value::Int(i as i64)], env, false)?.0
            } else {
                call_lambda_one(lam, v, env, false)?.0
            };
            out.push(y);
        }
        Ok(Value::Array(out))
    })
}

fn bi_where(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    let piped = input.is_some();
    let lam_val = if piped {
        arg("where", &args, 0, "a lambda")?
    } else {
        arg("where", &args, 1, "a lambda")?
    };
    let lam = need_lambda(lam_val, "where")?;
    // See `bi_map`: the array is consumed. Each element is moved into the
    // predicate and handed back, so a kept element is never copied.
    let arr_val = match input {
        Some(v) => v,
        None => args
            .first()
            .cloned()
            .ok_or_else(|| crate::safety::bad_arg("where", "an array", "nothing"))?,
    };
    expect_array("where", &arr_val)?;
    let Value::Array(items) = arr_val else {
        unreachable!("expect_array accepted it")
    };
    // See `bi_map`: ask the lambda its arity once instead of calling twice and
    // keeping three copies of each element alive to make the retry possible.
    let two_arg = lam.params.len() == 2;
    let mut out = Vec::new();
    if items.is_empty() {
        return Ok(Value::Array(out));
    }
    with_param_slots(lam, env, |env| {
        for (i, v) in items.into_iter().enumerate() {
            let (keep_val, v) = if two_arg {
                let (k, mut back) =
                    call_lambda_owned(lam, vec![v, Value::Int(i as i64)], env, true)?;
                (k, back.swap_remove(0))
            } else {
                let (k, back) = call_lambda_one(lam, v, env, true)?;
                (k, back.unwrap_or(Value::Null))
            };
            match keep_val {
                Value::Bool(true) => out.push(v),
                Value::Bool(false) => {}
                other => {
                    // Plain display, not Debug: "got Int 0", not "got Int(0)".
                    let got = match &other {
                        Value::Null | Value::Int(_) | Value::Float(_) | Value::Bool(_) => {
                            format!("{} {}", other.type_name(), other.to_display_string())
                        }
                        _ => other.type_name().to_string(),
                    };
                    return Err(crate::safety::bad_arg_in(
                        "where",
                        format!("where predicate must return Bool, got {got}"),
                        "return a Bool from the predicate, e.g. fn(x) => x != 0",
                    ));
                }
            }
        }
        Ok(Value::Array(out))
    })
}

fn bi_reduce(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    // Cases:
    //  - piping:  [1,2,3] | reduce fn(a,b)=>... 0
    //  - direct:  reduce [1,2,3] fn(a,b)=>... 0
    // Determine arr, lambda index and init index without moving `input`
    let piped = input.is_some();
    if !piped && args.len() < 3 {
        return Err(crate::safety::bad_arg(
            "reduce",
            "<array> <fn(acc,x)> <init>",
            "nothing",
        ));
    }
    let (lam_idx, init_idx) = if piped {
        (0usize, 1usize)
    } else {
        (1usize, 2usize)
    };

    let lam = need_lambda(arg("reduce", &args, lam_idx, "a lambda")?, "reduce")?;
    let init = arg("reduce", &args, init_idx, "an initial value")?.clone();
    // Select arity before running the body. Retrying on any error copied the
    // accumulator and hid an indexed lambda's body error behind an arity error.
    let indexed = lam.params.len() == 3;
    let arr_val = input.unwrap_or_else(|| args[0].clone());
    expect_array("reduce", &arr_val)?;
    let Value::Array(arr) = arr_val else {
        unreachable!("expect_array accepted it")
    };

    let mut acc = init;
    if arr.is_empty() {
        return Ok(acc);
    }
    with_param_slots(lam, env, |env| {
        for (i, v) in arr.into_iter().enumerate() {
            let mut values = vec![acc, v];
            if indexed {
                values.push(Value::Int(i as i64));
            }
            acc = call_lambda_owned(lam, values, env, false)?.0;
        }
        Ok(acc)
    })
}

fn bi_take(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (arr_val, n_idx) = if let Some(input_val) = input {
        // SECURITY: Replace .unwrap() with explicit match (CVSS 7.1)
        (input_val, 0usize)
    } else {
        if args.len() < 2 {
            return Err(crate::safety::bad_arg("take", "<array> <n>", "nothing"));
        }
        (args[0].clone(), 1usize)
    };

    let n = expect_int(
        "take",
        args.get(n_idx)
            .ok_or_else(|| crate::safety::arg_err("take missing n"))?,
    )?;
    let arr = expect_array("take", &arr_val)?;

    // A negative count was taken as 0 and returned [] with no error, which is
    // the silent wrong answer; head and tail refuse it the same way.
    if n < 0 {
        return Err(crate::safety::arg_err(
            "take count must be a nonnegative Int",
        ));
    }
    Ok(Value::Array(arr.iter().take(n as usize).cloned().collect()))
}

fn bi_keys(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err(
            "keys: requires a Record as input or argument",
        ));
    };

    match val {
        Value::Record(map) => {
            let keys: Vec<Value> = map.keys().map(|k| Value::Str(k.clone())).collect();
            Ok(Value::Array(keys))
        }
        _ => Err(crate::safety::arg_err(format!(
            "keys: requires a Record, got {:?}",
            val
        ))),
    }
}

fn bi_values(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err(
            "values: requires a Record as input or argument",
        ));
    };

    match val {
        Value::Record(map) => {
            let values: Vec<Value> = map.values().cloned().collect();
            Ok(Value::Array(values))
        }
        _ => Err(crate::safety::arg_err(format!(
            "values: requires a Record, got {:?}",
            val
        ))),
    }
}

fn bi_sum(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let arr = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err(
            "sum: requires an Array as input or argument",
        ));
    };

    match arr {
        Value::Array(items) => {
            let mut int_sum: i64 = 0;
            let mut float_sum: f64 = 0.0;
            let mut has_float = false;

            for item in items {
                match item {
                    Value::Int(n) => {
                        if has_float {
                            float_sum += n as f64;
                        } else {
                            int_sum += n;
                        }
                    }
                    Value::Float(f) => {
                        if !has_float {
                            float_sum = int_sum as f64;
                            has_float = true;
                        }
                        float_sum += f;
                    }
                    _ => {
                        return Err(crate::safety::arg_err(format!(
                            "sum: array must contain only numbers, got {:?}",
                            item
                        )))
                    }
                }
            }

            if has_float {
                Ok(Value::Float(float_sum))
            } else {
                Ok(Value::Int(int_sum))
            }
        }
        _ => Err(crate::safety::arg_err(format!(
            "sum: requires an Array, got {:?}",
            arr
        ))),
    }
}

/// unique(array) - Remove every duplicate, keeping the first of each, in order.
/// The subject is an Array, piped or as the first argument. A String is
/// refused (the signature check gives the hint: lines or split("") first).
///
/// Example:
///   [1, 2, 1, 3] | unique          # [1, 2, 3]
///   unique(["b", "a", "b"])        # ["b", "a"]
fn bi_unique(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let subject = match (input, args.first()) {
        (Some(input), _) => input,
        (None, Some(first)) => first.clone(),
        (None, None) => {
            return Err(crate::safety::bad_arg(
                "unique",
                "a piped Array",
                "a direct call with no subject",
            ))
        }
    };
    let array = match subject {
        Value::Array(arr) => arr,
        other => {
            return Err(crate::safety::bad_arg(
                "unique",
                "an Array as the subject",
                other.type_name(),
            ))
        }
    };

    // True unique - removes all duplicates (not just consecutive)
    let mut seen = std::collections::HashSet::new();
    let mut unique = Vec::new();

    for item in array {
        let key = format!("{:?}", item);
        if seen.insert(key) {
            unique.push(item);
        }
    }

    Ok(Value::Array(unique))
}

fn bi_avg(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let arr = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err(
            "avg: requires an Array as input or argument",
        ));
    };

    match arr {
        Value::Array(items) => {
            // An empty mean is undefined, as min and max of nothing are: NaN
            // answered it at exit 0.
            if items.is_empty() {
                return Err(crate::safety::bad_arg_in(
                    "avg",
                    "avg of an empty array is undefined",
                    "check the array is not empty first, such as with len, or give a default for the empty case",
                ));
            }

            let mut sum: f64 = 0.0;
            for item in &items {
                match item {
                    Value::Int(n) => sum += *n as f64,
                    Value::Float(f) => sum += *f,
                    _ => {
                        return Err(crate::safety::arg_err(format!(
                            "avg: array must contain only numbers, got {:?}",
                            item
                        )))
                    }
                }
            }

            Ok(Value::Float(sum / items.len() as f64))
        }
        _ => Err(crate::safety::arg_err(format!(
            "avg: requires an Array, got {:?}",
            arr
        ))),
    }
}

/// The numbers of an array argument or piped array, and the arguments after
/// it, for the statistics builtins (`median`, `variance`, `stddev`,
/// `percentile`). An Int is promoted to a Float.
fn stats_subject(
    name: &str,
    args: Vec<Value>,
    input: Option<Value>,
) -> Result<(Vec<f64>, Vec<Value>)> {
    let first_is_array = matches!(args.first(), Some(Value::Array(_)));
    let (items, rest) = if first_is_array {
        let mut args = args;
        let first = args.remove(0);
        match first {
            Value::Array(items) => (items, args),
            _ => unreachable!("checked above"),
        }
    } else if let Some(Value::Array(items)) = input {
        (items, args)
    } else {
        return Err(crate::safety::bad_arg_in(
            name,
            format!("{name}: requires an Array of numbers as input or first argument"),
            "pass an array such as [1, 2, 3]",
        ));
    };
    let mut numbers = Vec::with_capacity(items.len());
    for item in &items {
        match item {
            Value::Int(n) => numbers.push(*n as f64),
            Value::Float(f) => numbers.push(*f),
            other => {
                return Err(crate::safety::bad_arg_in(
                    name,
                    format!(
                        "{name}: array must contain only numbers, found {}",
                        other.type_name()
                    ),
                    "pass an array of Ints and Floats",
                ))
            }
        }
    }
    Ok((numbers, rest))
}

/// A statistic's result as a Float, refused when it overflowed.
fn stats_result(name: &str, x: f64) -> Result<Value> {
    if x.is_finite() {
        Ok(Value::Float(x))
    } else {
        Err(crate::safety::value_not_representable(
            name,
            format!("{name}: float overflow"),
            "the values are too large for their statistic to be a finite number",
        ))
    }
}

/// median(numbers) - the middle value; the mean of the two middle values of
/// an even-length array. Always a Float.
fn bi_median(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (mut v, rest) = stats_subject("median", args, input)?;
    if !rest.is_empty() {
        return Err(arity_error("median", "one array", rest.len() + 1));
    }
    if v.is_empty() {
        return Err(crate::safety::bad_arg_in(
            "median",
            "median of an empty array is undefined",
            "check the array is not empty first, such as with len",
        ));
    }
    v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let n = v.len();
    let m = if n % 2 == 1 {
        v[n / 2]
    } else {
        v[n / 2 - 1] + (v[n / 2] - v[n / 2 - 1]) / 2.0
    };
    stats_result("median", m)
}

/// The sample variance (n - 1 divisor) of a number array.
fn sample_variance(name: &str, args: Vec<Value>, input: Option<Value>) -> Result<f64> {
    let (v, rest) = stats_subject(name, args, input)?;
    if !rest.is_empty() {
        return Err(arity_error(name, "one array", rest.len() + 1));
    }
    if v.len() < 2 {
        return Err(crate::safety::bad_arg_in(
            name,
            format!("{name} needs at least 2 values, got {}", v.len()),
            "the sample variance divides by n - 1, so one value has none",
        ));
    }
    let n = v.len() as f64;
    let mean = v.iter().sum::<f64>() / n;
    // Two passes with a compensation term: the deviations from the rounded mean
    // do not sum to exactly 0, and sum((x - m)^2) - (sum(x - m))^2 / n removes
    // that error (the corrected two-pass algorithm).
    let ss: f64 = v.iter().map(|x| (x - mean) * (x - mean)).sum();
    let drift: f64 = v.iter().map(|x| x - mean).sum();
    Ok((ss - drift * drift / n) / (n - 1.0))
}

/// variance(numbers) - the sample variance (n - 1), as Python's
/// `statistics.variance`.
fn bi_variance(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    stats_result("variance", sample_variance("variance", args, input)?)
}

/// stddev(numbers) - the sample standard deviation (n - 1), as Python's
/// `statistics.stdev`.
fn bi_stddev(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    stats_result("stddev", sample_variance("stddev", args, input)?.sqrt())
}

/// percentile(numbers, p) - the p-th percentile, p in 0..=100, by linear
/// interpolation between closest ranks (numpy's default).
fn bi_percentile(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (mut v, rest) = stats_subject("percentile", args, input)?;
    if rest.len() != 1 {
        return Err(arity_error(
            "percentile",
            "an array and a percentage",
            rest.len() + 1,
        ));
    }
    let p = match &rest[0] {
        Value::Int(n) => *n as f64,
        Value::Float(f) => *f,
        other => {
            return Err(crate::safety::bad_arg(
                "percentile",
                "a number from 0 to 100",
                other.type_name(),
            ))
        }
    };
    if !(0.0..=100.0).contains(&p) {
        return Err(crate::safety::bad_arg_in(
            "percentile",
            format!(
                "percentile: {} is not between 0 and 100",
                float_for_message(p)
            ),
            "pass p as a percentage from 0 to 100",
        ));
    }
    if v.is_empty() {
        return Err(crate::safety::bad_arg_in(
            "percentile",
            "percentile of an empty array is undefined",
            "check the array is not empty first, such as with len",
        ));
    }
    v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let rank = p / 100.0 * (v.len() - 1) as f64;
    let lo = rank.floor() as usize;
    let hi = rank.ceil() as usize;
    let result = v[lo] + (v[hi] - v[lo]) * (rank - lo as f64);
    stats_result("percentile", result)
}

fn bi_product(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let arr = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err(
            "product: requires an Array as input or argument",
        ));
    };

    match arr {
        Value::Array(items) => {
            let mut int_product: i64 = 1;
            let mut float_product: f64 = 1.0;
            let mut has_float = false;

            for item in items {
                match item {
                    Value::Int(n) => {
                        if has_float {
                            float_product *= n as f64;
                        } else {
                            int_product = int_product.checked_mul(n).ok_or_else(|| {
                                crate::safety::bad_arg(
                                    "product",
                                    "a product within Int range",
                                    "integer overflow",
                                )
                            })?;
                        }
                    }
                    Value::Float(f) => {
                        if !has_float {
                            float_product = int_product as f64;
                            has_float = true;
                        }
                        float_product *= f;
                    }
                    _ => {
                        return Err(crate::safety::bad_arg(
                            "product",
                            "an array of numbers",
                            item.type_name(),
                        ))
                    }
                }
            }

            if has_float {
                Ok(Value::Float(float_product))
            } else {
                Ok(Value::Int(int_product))
            }
        }
        _ => Err(crate::safety::arg_err(format!(
            "product: requires an Array, got {:?}",
            arr
        ))),
    }
}

// --------------- Configuration builtins ---------------

/// Get the entire configuration as a Record
fn bi_config(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let config = get_config();
    let mut map = BTreeMap::new();

    // Shell settings
    let mut shell = BTreeMap::new();
    shell.insert(
        "show_banner".to_string(),
        Value::Bool(config.shell.show_banner),
    );
    shell.insert("show_tips".to_string(), Value::Bool(config.shell.show_tips));
    shell.insert("vi_mode".to_string(), Value::Bool(config.shell.vi_mode));
    shell.insert("auto_cd".to_string(), Value::Bool(config.shell.auto_cd));
    shell.insert(
        "glob_expansion".to_string(),
        Value::Bool(config.shell.glob_expansion),
    );
    shell.insert(
        "command_correction".to_string(),
        Value::Bool(config.shell.command_correction),
    );
    shell.insert(
        "bell_style".to_string(),
        Value::Str(config.shell.bell_style.clone()),
    );
    map.insert("shell".to_string(), Value::Record(shell));

    // Color settings
    let mut colors = BTreeMap::new();
    colors.insert("enabled".to_string(), Value::Bool(config.colors.enabled));
    colors.insert("theme".to_string(), Value::Str(config.colors.theme.clone()));
    colors.insert("force".to_string(), Value::Bool(config.colors.force));
    colors.insert(
        "true_color".to_string(),
        Value::Bool(config.colors.true_color),
    );
    map.insert("colors".to_string(), Value::Record(colors));

    // Prompt settings
    let mut prompt = BTreeMap::new();
    prompt.insert(
        "format".to_string(),
        Value::Str(config.prompt.format.clone()),
    );
    prompt.insert("show_git".to_string(), Value::Bool(config.prompt.show_git));
    prompt.insert(
        "show_time".to_string(),
        Value::Bool(config.prompt.show_time),
    );
    prompt.insert(
        "time_threshold_ms".to_string(),
        Value::Int(config.prompt.time_threshold_ms as i64),
    );
    map.insert("prompt".to_string(), Value::Record(prompt));

    // AI settings
    let mut ai = BTreeMap::new();
    ai.insert(
        "default_provider".to_string(),
        Value::Str(config.ai.default_provider.clone()),
    );
    ai.insert(
        "default_model".to_string(),
        Value::Str(config.ai.default_model.clone()),
    );
    ai.insert(
        "suggestions".to_string(),
        Value::Bool(config.ai.suggestions),
    );
    ai.insert(
        "max_tokens".to_string(),
        Value::Int(config.ai.max_tokens as i64),
    );
    ai.insert(
        "temperature".to_string(),
        Value::Float(config.ai.temperature as f64),
    );
    ai.insert("streaming".to_string(), Value::Bool(config.ai.streaming));
    ai.insert(
        "max_agent_steps".to_string(),
        Value::Int(config.ai.max_agent_steps as i64),
    );
    map.insert("ai".to_string(), Value::Record(ai));

    // History settings
    let mut history = BTreeMap::new();
    history.insert("enabled".to_string(), Value::Bool(config.history.enabled));
    history.insert(
        "max_size".to_string(),
        Value::Int(config.history.max_size as i64),
    );
    history.insert(
        "ignore_duplicates".to_string(),
        Value::Bool(config.history.ignore_duplicates),
    );
    history.insert(
        "ignore_space".to_string(),
        Value::Bool(config.history.ignore_space),
    );
    history.insert("share".to_string(), Value::Bool(config.history.share));
    history.insert(
        "timestamps".to_string(),
        Value::Bool(config.history.timestamps),
    );
    map.insert("history".to_string(), Value::Record(history));

    Ok(Value::Record(map))
}

/// Get a specific config value by path (e.g., "colors.theme" or "ai.default_model")
fn bi_config_get(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err(
            "config_get: requires a path argument (e.g., \"colors.theme\")",
        ));
    }

    let path = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "config_get",
                "path: String",
                other.type_name(),
            ))
        }
    };

    let config = get_config();
    let parts: Vec<&str> = path.split('.').collect();

    match parts.as_slice() {
        // Shell settings
        ["shell", "show_banner"] => Ok(Value::Bool(config.shell.show_banner)),
        ["shell", "show_tips"] => Ok(Value::Bool(config.shell.show_tips)),
        ["shell", "vi_mode"] => Ok(Value::Bool(config.shell.vi_mode)),
        ["shell", "auto_cd"] => Ok(Value::Bool(config.shell.auto_cd)),
        ["shell", "glob_expansion"] => Ok(Value::Bool(config.shell.glob_expansion)),
        ["shell", "command_correction"] => Ok(Value::Bool(config.shell.command_correction)),
        ["shell", "bell_style"] => Ok(Value::Str(config.shell.bell_style.clone())),

        // Color settings
        ["colors", "enabled"] => Ok(Value::Bool(config.colors.enabled)),
        ["colors", "theme"] => Ok(Value::Str(config.colors.theme.clone())),
        ["colors", "force"] => Ok(Value::Bool(config.colors.force)),
        ["colors", "true_color"] => Ok(Value::Bool(config.colors.true_color)),

        // Prompt settings
        ["prompt", "format"] => Ok(Value::Str(config.prompt.format.clone())),
        ["prompt", "show_git"] => Ok(Value::Bool(config.prompt.show_git)),
        ["prompt", "show_time"] => Ok(Value::Bool(config.prompt.show_time)),
        ["prompt", "time_threshold_ms"] => Ok(Value::Int(config.prompt.time_threshold_ms as i64)),

        // AI settings
        ["ai", "default_provider"] => Ok(Value::Str(config.ai.default_provider.clone())),
        ["ai", "default_model"] => Ok(Value::Str(config.ai.default_model.clone())),
        ["ai", "suggestions"] => Ok(Value::Bool(config.ai.suggestions)),
        ["ai", "max_tokens"] => Ok(Value::Int(config.ai.max_tokens as i64)),
        ["ai", "temperature"] => Ok(Value::Float(config.ai.temperature as f64)),
        ["ai", "streaming"] => Ok(Value::Bool(config.ai.streaming)),
        ["ai", "max_agent_steps"] => Ok(Value::Int(config.ai.max_agent_steps as i64)),

        // History settings
        ["history", "enabled"] => Ok(Value::Bool(config.history.enabled)),
        ["history", "max_size"] => Ok(Value::Int(config.history.max_size as i64)),
        ["history", "ignore_duplicates"] => Ok(Value::Bool(config.history.ignore_duplicates)),
        ["history", "ignore_space"] => Ok(Value::Bool(config.history.ignore_space)),
        ["history", "share"] => Ok(Value::Bool(config.history.share)),
        ["history", "timestamps"] => Ok(Value::Bool(config.history.timestamps)),

        _ => Err(crate::safety::not_found("config_get", "config path", &path)),
    }
}

/// Set a config value (saves to config file)
/// Note: This modifies the config file but changes only take effect after reload
/// The settable paths, for the refusal that names them.
const CONFIG_SETTABLE: &str = "colors.enabled|theme|force|true_color, shell.show_banner|show_tips|vi_mode|auto_cd, ai.default_model|default_provider|max_tokens|streaming, history.enabled|max_size";

/// Refuse a value the config path cannot hold, before the file is read. Every
/// settable path has a fixed type and range; `max_tokens` used to be cast with
/// `as u32`, so -1 became 4294967295 and was saved.
fn config_value_ok(path: &str, value: &Value) -> Result<()> {
    const B: &str = "config_set";
    const BOOL_PATHS: &[&str] = &[
        "colors.enabled",
        "colors.force",
        "colors.true_color",
        "shell.show_banner",
        "shell.show_tips",
        "shell.vi_mode",
        "shell.auto_cd",
        "ai.streaming",
        "history.enabled",
    ];
    let refuse = |expected: String| {
        crate::safety::bad_arg(
            B,
            &expected,
            &format!("{} {}", value.type_name(), value.to_display_string()),
        )
    };
    if BOOL_PATHS.contains(&path) {
        return match value {
            Value::Bool(_) => Ok(()),
            _ => Err(refuse(format!("{path}: Bool"))),
        };
    }
    match path {
        "colors.theme" => match value {
            Value::Str(s)
                if (1..=64).contains(&s.len())
                    && s.chars()
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') =>
            {
                Ok(())
            }
            _ => Err(refuse(
                "colors.theme: a String of 1 to 64 letters, digits, '_' or '-'".to_string(),
            )),
        },
        "ai.default_model" | "ai.default_provider" => match value {
            Value::Str(s)
                if !s.trim().is_empty() && s.len() <= 256 && !s.chars().any(char::is_control) =>
            {
                Ok(())
            }
            _ => Err(refuse(format!(
                "{path}: a non-blank String of at most 256 bytes without control characters"
            ))),
        },
        "ai.max_tokens" => match value {
            Value::Int(n) if (1..=i64::from(u32::MAX)).contains(n) => Ok(()),
            _ => Err(refuse(
                "ai.max_tokens: an Int in 1..=4294967295".to_string(),
            )),
        },
        "history.max_size" => match value {
            Value::Int(n) if (1..=1_000_000).contains(n) => Ok(()),
            _ => Err(refuse(
                "history.max_size: an Int in 1..=1000000".to_string(),
            )),
        },
        _ => Err(crate::safety::bad_arg(
            B,
            &format!("a settable path: {CONFIG_SETTABLE}"),
            path,
        )),
    }
}

// Keys config_set stores but nothing in the shell reads yet; its reply says so.
const CONFIG_NOT_APPLIED: &[&str] = &[
    "colors.force",
    "shell.show_tips",
    "shell.vi_mode",
    "shell.auto_cd",
    "ai.default_model",
    "ai.default_provider",
    "ai.max_tokens",
    "ai.streaming",
    "history.max_size",
];

/// config_set(path, value) - set one config value, save the config file that
/// `ShellConfig::config_file` names, and reload it into the running shell.
/// The path and value are checked before the file is read; a value of the
/// wrong type or outside its range is E_BAD_ARG and nothing is saved.
fn bi_config_set(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "config_set";
    k8s_no_input(B, &input)?;
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        Some(other) => return Err(crate::safety::bad_arg(B, "path: String", other.type_name())),
        None => {
            return Err(crate::safety::arg_err(
                "config_set requires path and value arguments",
            ))
        }
    };
    let value = args
        .get(1)
        .ok_or_else(|| crate::safety::arg_err("config_set requires path and value arguments"))?;
    config_value_ok(&path, value)?;

    let mut config = ShellConfig::load().map_err(|e| {
        crate::safety::bad_state(
            B,
            &format!("the config file could not be read: {e}"),
            "config_path",
        )
    })?;
    match (path.as_str(), value) {
        ("colors.enabled", Value::Bool(v)) => config.colors.enabled = *v,
        ("colors.theme", Value::Str(v)) => config.colors.theme = v.clone(),
        ("colors.force", Value::Bool(v)) => config.colors.force = *v,
        ("colors.true_color", Value::Bool(v)) => config.colors.true_color = *v,

        ("shell.show_banner", Value::Bool(v)) => config.shell.show_banner = *v,
        ("shell.show_tips", Value::Bool(v)) => config.shell.show_tips = *v,
        ("shell.vi_mode", Value::Bool(v)) => config.shell.vi_mode = *v,
        ("shell.auto_cd", Value::Bool(v)) => config.shell.auto_cd = *v,

        ("ai.default_model", Value::Str(v)) => config.ai.default_model = v.clone(),
        ("ai.default_provider", Value::Str(v)) => config.ai.default_provider = v.clone(),
        ("ai.max_tokens", Value::Int(v)) => config.ai.max_tokens = *v as u32,
        ("ai.streaming", Value::Bool(v)) => config.ai.streaming = *v,

        ("history.enabled", Value::Bool(v)) => config.history.enabled = *v,
        ("history.max_size", Value::Int(v)) => config.history.max_size = *v as usize,
        // config_value_ok admits only the pairs above; a refusal here would be
        // a coded one rather than a panic.
        _ => {
            return Err(crate::safety::bad_arg(
                B,
                &format!("a settable path: {CONFIG_SETTABLE}"),
                &path,
            ))
        }
    }

    config.save().map_err(|e| {
        crate::safety::bad_state(
            B,
            &format!("the config file could not be written: {e}"),
            "config_path",
        )
    })?;
    // Make the running shell use the saved value, as config_reload does.
    reload_config().map_err(|e| {
        crate::safety::bad_state_with_hint(
            B,
            &format!("the saved configuration could not be reloaded: {e}"),
            "fix the config file (see config_path()) and reload",
        )
    })?;
    let shown = match value {
        Value::Str(s) => s.clone(),
        Value::Bool(b) => b.to_string(),
        Value::Int(n) => n.to_string(),
        other => other.type_name().to_string(),
    };
    if CONFIG_NOT_APPLIED.contains(&path.as_str()) {
        return Ok(Value::Str(format!(
            "Config saved: {path} = {shown} (not applied: the shell stores this key but nothing acts on it yet)"
        )));
    }
    Ok(Value::Str(format!("Config saved: {path} = {shown}")))
}

/// Get config file paths
fn bi_config_path() -> Result<Value> {
    let mut map = BTreeMap::new();
    map.insert(
        "config_file".to_string(),
        Value::Str(ShellConfig::config_file().to_string_lossy().to_string()),
    );
    map.insert(
        "config_dir".to_string(),
        Value::Str(ShellConfig::config_dir().to_string_lossy().to_string()),
    );
    map.insert(
        "data_dir".to_string(),
        Value::Str(ShellConfig::data_dir().to_string_lossy().to_string()),
    );
    map.insert(
        "cache_dir".to_string(),
        Value::Str(ShellConfig::cache_dir().to_string_lossy().to_string()),
    );
    map.insert(
        "history_file".to_string(),
        Value::Str(ShellConfig::history_file().to_string_lossy().to_string()),
    );
    map.insert(
        "plugins_dir".to_string(),
        Value::Str(ShellConfig::plugins_dir().to_string_lossy().to_string()),
    );
    map.insert(
        "init_script".to_string(),
        Value::Str(ShellConfig::init_script().to_string_lossy().to_string()),
    );
    Ok(Value::Record(map))
}

/// Initialize config directories and create default config file
fn bi_config_init(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "config_init";
    // Takes no arguments (declared so) and no pipeline input.
    k8s_no_input(B, &input)?;
    if !args.is_empty() {
        return Err(crate::safety::bad_arg(
            B,
            "no arguments",
            &format!("{} argument(s)", args.len()),
        ));
    }
    ShellConfig::init_dirs().map_err(|e| {
        crate::safety::bad_state(
            B,
            &format!("the config directories could not be created: {e}"),
            "config_path",
        )
    })?;

    // The file the shell reads and `config_set` writes (IRONSHELL_CONFIG, or
    // the existing config file). `create_new` never overwrites one.
    let config_file = ShellConfig::config_file();
    if let Some(parent) = config_file.parent() {
        fs::create_dir_all(parent).map_err(|e| crate::safety::fs_error(B, parent, &e))?;
    }
    match fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&config_file)
    {
        Ok(mut file) => {
            use std::io::Write as _;
            file.write_all(ShellConfig::generate_default_config().as_bytes())
                .map_err(|e| crate::safety::fs_error(B, &config_file, &e))?;
            Ok(Value::Str(format!(
                "Created config file: {}",
                config_file.display()
            )))
        }
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(Value::Str(format!(
            "Config file already exists: {}",
            config_file.display()
        ))),
        Err(e) => Err(crate::safety::fs_error(B, &config_file, &e)),
    }
}

/// Reload configuration from disk
fn bi_config_reload() -> Result<Value> {
    // The failure was an uncoded string; success was the prose
    // "Configuration reloaded".
    reload_config().map_err(|e| {
        crate::safety::bad_state_with_hint(
            "config_reload",
            &format!("the configuration could not be reloaded: {e}"),
            "fix the config file (see config_path()) and reload",
        )
    })?;
    Ok(Value::Bool(true))
}

/// List all available color themes
fn bi_themes() -> Result<Value> {
    use crate::config::Theme;
    let themes: Vec<Value> = Theme::list()
        .iter()
        .map(|s| Value::Str(s.to_string()))
        .collect();
    Ok(Value::Array(themes))
}

// ===================== Plugin Builtins =====================

/// List all registered plugins
fn bi_plugins(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(crate::plugins::bi_plugins_list())
}

/// Get detailed information about a plugin
fn bi_plugin_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let plugin_id = if let Some(Value::Str(id)) = input {
        id
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(id) => id.clone(),
            _ => {
                return Err(crate::safety::arg_err(
                    "plugin_info: requires plugin ID string",
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err("plugin_info: requires plugin ID"));
    };

    // Null for an unknown id read as "no information about it".
    match crate::plugins::bi_plugin_info(&plugin_id) {
        Value::Null => Err(crate::safety::not_found(
            "plugin_info",
            "plugin",
            &plugin_id,
        )),
        info => Ok(info),
    }
}

/// Enable a plugin by ID
fn bi_plugin_enable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let plugin_id = if let Some(Value::Str(id)) = input {
        id
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(id) => id.clone(),
            _ => {
                return Err(crate::safety::arg_err(
                    "plugin_enable: requires plugin ID string",
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err("plugin_enable: requires plugin ID"));
    };

    crate::plugins::bi_plugin_enable(&plugin_id)
}

/// Disable a plugin by ID
fn bi_plugin_disable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let plugin_id = if let Some(Value::Str(id)) = input {
        id
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(id) => id.clone(),
            _ => {
                return Err(crate::safety::arg_err(
                    "plugin_disable: requires plugin ID string",
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err("plugin_disable: requires plugin ID"));
    };

    crate::plugins::bi_plugin_disable(&plugin_id)
}

/// Load a plugin from a manifest file path
fn bi_plugin_load(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let path = if let Some(Value::Str(p)) = input {
        p
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(p) => p.clone(),
            _ => return Err(crate::safety::arg_err("plugin_load: requires path string")),
        }
    } else {
        return Err(crate::safety::arg_err(
            "plugin_load: requires manifest path",
        ));
    };

    crate::plugins::load_plugin_from_manifest(&path)
}

/// Unload a plugin by ID
fn bi_plugin_unload(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let plugin_id = if let Some(Value::Str(id)) = input {
        id
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(id) => id.clone(),
            _ => {
                return Err(crate::safety::arg_err(
                    "plugin_unload: requires plugin ID string",
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err("plugin_unload: requires plugin ID"));
    };

    crate::plugins::unload_plugin(&plugin_id)
}

/// List all plugin categories
fn bi_plugin_categories() -> Result<Value> {
    Ok(crate::plugins::bi_plugin_categories())
}

fn bi_len(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err("len: requires input or argument"));
    };

    let length = match val {
        Value::Array(ref v) => v.len(),
        Value::Record(ref m) => m.len(),
        // Characters, not bytes: len("日本語") is 3, as slice counts them.
        Value::Str(ref s) => s.chars().count(),
        _ => {
            return Err(crate::safety::arg_err(format!(
                "len: requires Array, Record, or String, got {:?}",
                val
            )));
        }
    };

    Ok(Value::Int(length as i64))
}

/// `error(message[, extra])` — raise an error the script chose.
///
/// The error is `E_USER` with `message` as given. A Record `extra` adds its
/// fields to the caught error record, so a script can say which field was bad
/// without parsing the message. Catchable with try/catch; uncaught, it exits
/// non-zero like any other error.
///
/// Example:
///   try { error("boom") } catch e { e.message }                 # "boom"
///   try { error("bad", {field: "age"}) } catch e { e.field }   # "age"
fn bi_error(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Every refusal of error()'s own arguments is not retryable: the same
    // arguments are refused again. It is bad_value_in, which keeps the wire
    // code E_BAD_ARG that these refusals have always had.
    let message = match args.first().or(input.as_ref()) {
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_value_in(
                "error",
                format!(
                    "error: the message is {}, expected a String",
                    other.type_name()
                ),
                "give the reason as text, e.g. error(\"what went wrong\")",
            ))
        }
        None => {
            return Err(crate::safety::bad_value_in(
                "error",
                "error: the message is nothing, expected a String",
                "give the reason as text, e.g. error(\"what went wrong\")",
            ))
        }
    };
    // An error with no reason is not one an agent can act on, and it reads as
    // a failure with nothing wrong in it.
    if message.is_empty() {
        return Err(crate::safety::bad_value_in(
            "error",
            "error: the message is empty",
            "give the reason as text, e.g. error(\"what went wrong\")",
        ));
    }
    let mut extra = serde_json::Map::new();
    let mut hint = None;
    match args.get(1) {
        None => {}
        Some(Value::Record(fields)) => {
            // A field named like a standard error key would be dropped without
            // a word (`to_json` keeps the standard value), so refuse it here.
            // These refusals are not retryable: the same arguments fail again.
            let clashes: Vec<String> = fields
                .iter()
                .filter(|(key, _)| crate::safety::ERROR_RESERVED_KEYS.contains(&key.as_str()))
                .map(|(key, _)| format!("`{key}`"))
                .collect();
            if !clashes.is_empty() {
                return Err(crate::safety::bad_value_in(
                    "error",
                    format!(
                        "error: extra field {} is reserved: the standard error fields are {}",
                        clashes.join(", "),
                        crate::safety::ERROR_RESERVED_KEYS.join(", ")
                    ),
                    "rename the field, e.g. {user_code: 7}",
                ));
            }
            for (key, value) in fields {
                // A script's `hint` is the advice its caller reads, so it
                // replaces the default hint rather than sitting beside it.
                if key == "hint" {
                    let Value::Str(text) = value else {
                        return Err(crate::safety::bad_value_in(
                            "error",
                            format!(
                                "error: extra field `hint` is {}, expected a String",
                                value.type_name()
                            ),
                            "give the advice as text, e.g. {hint: \"retry after the sync\"}",
                        ));
                    };
                    hint = Some(text.clone());
                    continue;
                }
                extra.insert(key.clone(), value.to_json());
            }
        }
        Some(other) => {
            return Err(crate::safety::bad_value_in(
                "error",
                format!(
                    "error: the extra fields are {}, expected a Record or nothing",
                    other.type_name()
                ),
                "pass the extra fields as a Record, e.g. error(\"bad\", {field: \"age\"})",
            ))
        }
    }
    Err(crate::safety::user_error(message, extra, hint))
}

/// `str(v)` — render a value as the string a user would see.
///
/// The language had no way to do this. `"n: " + 1` worked by coercion, and no
/// longer does, so this is the conversion. There was no conversion function
/// before, so 41 sites across the shipped examples
/// called a `str()` that has never existed. `to_display_string` is the same
/// renderer `print` and string interpolation use, so the three agree.
fn bi_str(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(v) = input {
        v
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err("str: requires input or argument"));
    };
    Ok(Value::Str(val.to_display_string()))
}

fn bi_type_of(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err(
            "type_of: requires input or argument",
        ));
    };

    let type_str = match val {
        Value::Null => "Null",
        Value::Bool(_) => "Bool",
        Value::Int(_) => "Int",
        Value::Float(_) => "Float",
        Value::Str(_) => "String",
        Value::Uri(_) => "Uri",
        Value::Array(_) => "Array",
        Value::Record(_) => "Record",
        Value::Table(_) => "Table",
        Value::Lambda(_) => "Lambda",
        Value::AsyncLambda(_) => "AsyncLambda",
        Value::Future(_) => "Future",
        Value::Builtin(_) => "Builtin",
        Value::Error(_) => "Error",
    };

    Ok(Value::Str(type_str.to_string()))
}

/// is_error(value) - Check if a value is an Error
/// Args:
///   - value: Any value to check
/// Returns: Bool - true if the value is an Error, false otherwise
///
/// Example:
///   let e = throw "something went wrong"
///   is_error(e)  # Returns true
///   is_error(42) # Returns false
fn bi_is_error(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err(
            "is_error: requires input or argument",
        ));
    };

    // A caught error is a record whose `error` field holds the error's fields
    // (see eval's `caught_error_record`), so it counts as an error too.
    let is_err = match &val {
        Value::Error(_) => true,
        Value::Record(fields) => matches!(
            fields.get("error"),
            Some(Value::Record(inner)) if inner.contains_key("code")
        ),
        _ => false,
    };
    Ok(Value::Bool(is_err))
}

// --------------- Debugging Tools ---------------

/// debug(value) - Print value with its type and return the value for chaining
/// Args:
///   - value: Any value to debug
/// Returns: The same value (allows chaining in pipelines)
///
/// Example:
///   let x = debug(42)           # Prints: [DEBUG] Int: 42
///   [1,2,3] | debug | map(...)  # Debug intermediate pipeline values
fn bi_debug(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err("debug: requires input or argument"));
    };

    let type_str = val.type_name();
    let pretty =
        crate::value::pretty::display_inline(&val, &crate::value::pretty::Theme::for_stdout());
    eprintln!("[DEBUG] {}: {}", type_str, pretty);

    // Return the value unchanged for pipeline chaining
    Ok(val)
}

/// assert(condition, message?) - Assert that a condition is true
/// Args:
///   - condition: Boolean condition to check
///   - message: Optional error message (defaults to "assertion failed")
/// Returns: true if assertion passes
/// Throws: Error with message if condition is false
///
/// Example:
///   assert(x > 0, "x must be positive")
///   assert(len(arr) > 0)  # Uses default message
fn bi_assert(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (cond, msg) = if let Some(input_val) = input {
        // Piped: input is condition, arg 0 is message
        let message = args
            .first()
            .and_then(|v| match v {
                Value::Str(s) => Some(s.clone()),
                _ => None,
            })
            .map_or_else(
                || "assertion failed".to_string(),
                |m| format!("assertion failed: {m}"),
            );
        (input_val, message)
    } else if !args.is_empty() {
        // Args: arg 0 is condition, arg 1 is message
        let message = args
            .get(1)
            .and_then(|v| match v {
                Value::Str(s) => Some(s.clone()),
                _ => None,
            })
            .map_or_else(
                || "assertion failed".to_string(),
                |m| format!("assertion failed: {m}"),
            );
        (args[0].clone(), message)
    } else {
        return Err(crate::safety::arg_err(
            "assert: requires condition argument",
        ));
    };

    // Check if condition is truthy
    let is_truthy = match &cond {
        Value::Bool(b) => *b,
        Value::Null => false,
        Value::Error(_) => false,
        Value::Int(n) => *n != 0,
        Value::Float(f) => *f != 0.0,
        Value::Str(s) => !s.is_empty(),
        Value::Array(arr) => !arr.is_empty(),
        Value::Record(rec) => !rec.is_empty(),
        _ => true,
    };

    if is_truthy {
        Ok(Value::Bool(true))
    } else {
        Err(crate::safety::assertion_failed(msg))
    }
}

/// trace(label, value) - Print a labeled value for tracing and return the value
/// Args:
///   - label: String label to identify the trace point
///   - value: Value to trace (can also be piped)
/// Returns: The value unchanged (allows chaining)
///
/// Example:
///   let result = trace("input", x) | map(fn(n) => n * 2) | trace("output")
///   trace("step1", calculate())
fn bi_trace(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // A label must be a string; a trace line is for a human, so a label that
    // is not one is refused rather than rendered as Debug text.
    let label_of = |v: &Value| -> Result<String> {
        match v {
            Value::Str(s) if s.len() <= 256 => Ok(s.clone()),
            other => Err(crate::safety::bad_arg(
                "trace",
                "a label: a string of at most 256 bytes",
                other.type_name(),
            )),
        }
    };
    let (label, val) = if let Some(input_val) = input {
        // Piped: input is the value, and at most one argument (the label).
        if args.len() > 1 {
            return Err(crate::safety::bad_arg(
                "trace",
                "with piped input, at most one argument: the label",
                &format!("{} arguments", args.len()),
            ));
        }
        let label = match args.first() {
            Some(v) => label_of(v)?,
            None => "trace".to_string(),
        };
        (label, input_val)
    } else if args.len() == 2 {
        // Two args: label, value
        (label_of(&args[0])?, args[1].clone())
    } else if args.len() == 1 {
        // One arg: use default label
        ("trace".to_string(), args[0].clone())
    } else {
        return Err(crate::safety::bad_arg(
            "trace",
            "a value, or a label and a value",
            &format!("{} arguments", args.len()),
        ));
    };

    let type_str = val.type_name();
    let pretty =
        crate::value::pretty::display_inline(&val, &crate::value::pretty::Theme::for_stdout());
    // A trace line is not a dump: a large value is cut with an explicit marker
    // instead of flooding stderr.
    const MAX_TRACE_CHARS: usize = 4096;
    let pretty = if pretty.chars().count() > MAX_TRACE_CHARS {
        let head: String = pretty.chars().take(MAX_TRACE_CHARS).collect();
        format!("{head}… [trace truncated]")
    } else {
        pretty
    };
    eprintln!("[TRACE {}] {}: {}", label, type_str, pretty);

    // Return the value unchanged for pipeline chaining
    Ok(val)
}

/// type_assert(value, expected_type) - Assert that a value has the expected type
/// Args:
///   - value: Any value to check
///   - expected_type: String name of expected type ("Int", "String", "Array", etc.)
/// Returns: The value if type matches
/// Throws: Error if type doesn't match
///
/// Example:
///   type_assert(x, "Int")           # Passes if x is an Int
///   data | type_assert("Array")     # Piped: asserts data is Array
fn bi_type_assert(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (val, expected) = if let Some(input_val) = input {
        // Piped: input is value, arg 0 is expected type
        let expected = args.first().ok_or_else(|| {
            crate::safety::arg_err("type_assert: requires expected type argument")
        })?;
        let expected_str = match expected {
            Value::Str(s) => s.clone(),
            other => {
                return Err(crate::safety::bad_arg(
                    "type_assert",
                    "expected type: String",
                    other.type_name(),
                ))
            }
        };
        (input_val, expected_str)
    } else if args.len() >= 2 {
        // Two args: value, expected_type
        let expected_str = match &args[1] {
            Value::Str(s) => s.clone(),
            other => {
                return Err(crate::safety::bad_arg(
                    "type_assert",
                    "expected type: String",
                    other.type_name(),
                ))
            }
        };
        (args[0].clone(), expected_str)
    } else {
        return Err(crate::safety::arg_err(
            "type_assert: requires value and expected type arguments",
        ));
    };

    let actual_type = val.type_name();

    // Normalize type names for comparison (case-insensitive)
    let expected_normalized = expected.to_lowercase();
    let actual_normalized = actual_type.to_lowercase();

    if expected_normalized == actual_normalized {
        Ok(val)
    } else {
        Ok(Value::Error(format!(
            "type assertion failed: expected {}, got {}",
            expected, actual_type
        )))
    }
}

/// inspect(value) - Get detailed inspection of a value's structure
/// Args:
///   - value: Any value to inspect
/// Returns: Record with detailed information about the value
///
/// Example:
///   inspect([1,2,3])  # Returns {type: "Array", length: 3, items: [...]}
///   inspect({a: 1})   # Returns {type: "Record", keys: ["a"], values: [...]}
fn bi_inspect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input_val) = input {
        input_val
    } else if !args.is_empty() {
        args[0].clone()
    } else {
        return Err(crate::safety::arg_err(
            "inspect: requires input or argument",
        ));
    };

    let mut info = BTreeMap::<String, Value>::new();
    info.insert("type".to_string(), Value::Str(val.type_name().to_string()));

    match &val {
        Value::Null => {
            info.insert("value".to_string(), Value::Null);
        }
        Value::Bool(b) => {
            info.insert("value".to_string(), Value::Bool(*b));
        }
        Value::Int(n) => {
            info.insert("value".to_string(), Value::Int(*n));
            info.insert("is_negative".to_string(), Value::Bool(*n < 0));
            info.insert("is_zero".to_string(), Value::Bool(*n == 0));
        }
        Value::Float(f) => {
            info.insert("value".to_string(), Value::Float(*f));
            info.insert("is_nan".to_string(), Value::Bool(f.is_nan()));
            info.insert("is_infinite".to_string(), Value::Bool(f.is_infinite()));
            info.insert("is_negative".to_string(), Value::Bool(*f < 0.0));
        }
        Value::Str(s) => {
            info.insert("value".to_string(), Value::Str(s.clone()));
            info.insert("length".to_string(), Value::Int(s.len() as i64));
            info.insert("is_empty".to_string(), Value::Bool(s.is_empty()));
            info.insert(
                "char_count".to_string(),
                Value::Int(s.chars().count() as i64),
            );
        }
        Value::Uri(u) => {
            info.insert("value".to_string(), Value::Str(u.clone()));
            info.insert("length".to_string(), Value::Int(u.len() as i64));
        }
        Value::Array(arr) => {
            info.insert("length".to_string(), Value::Int(arr.len() as i64));
            info.insert("is_empty".to_string(), Value::Bool(arr.is_empty()));
            if !arr.is_empty() {
                info.insert("first".to_string(), arr[0].clone());
                info.insert("last".to_string(), arr[arr.len() - 1].clone());
                // Collect unique types in the array using a Vec with dedup
                let mut type_strs: Vec<String> =
                    arr.iter().map(|v| v.type_name().to_string()).collect();
                type_strs.sort();
                type_strs.dedup();
                let types: Vec<Value> = type_strs.into_iter().map(Value::Str).collect();
                info.insert("element_types".to_string(), Value::Array(types));
            }
            info.insert("elements".to_string(), Value::Array(arr.clone()));
        }
        Value::Record(rec) => {
            info.insert("length".to_string(), Value::Int(rec.len() as i64));
            info.insert("is_empty".to_string(), Value::Bool(rec.is_empty()));
            info.insert(
                "keys".to_string(),
                Value::Array(rec.keys().map(|k| Value::Str(k.clone())).collect()),
            );
            info.insert(
                "values".to_string(),
                Value::Array(rec.values().cloned().collect()),
            );
            info.insert("entries".to_string(), Value::Record(rec.clone()));
        }
        Value::Table(table) => {
            info.insert("row_count".to_string(), Value::Int(table.rows.len() as i64));
            info.insert("is_empty".to_string(), Value::Bool(table.rows.is_empty()));
            info.insert(
                "columns".to_string(),
                Value::Array(table.schema.iter().map(|k| Value::Str(k.clone())).collect()),
            );
            info.insert(
                "column_count".to_string(),
                Value::Int(table.schema.len() as i64),
            );
        }
        Value::Lambda(lambda) => {
            info.insert(
                "param_count".to_string(),
                Value::Int(lambda.params.len() as i64),
            );
            info.insert(
                "params".to_string(),
                Value::Array(
                    lambda
                        .params
                        .iter()
                        .map(|p| Value::Str(p.clone()))
                        .collect(),
                ),
            );
            info.insert("body".to_string(), Value::Str(format!("{:?}", lambda.body)));
        }
        Value::AsyncLambda(lambda) => {
            info.insert(
                "param_count".to_string(),
                Value::Int(lambda.params.len() as i64),
            );
            info.insert(
                "params".to_string(),
                Value::Array(
                    lambda
                        .params
                        .iter()
                        .map(|p| Value::Str(p.clone()))
                        .collect(),
                ),
            );
            info.insert("body".to_string(), Value::Str(format!("{:?}", lambda.body)));
            info.insert("is_async".to_string(), Value::Bool(true));
        }
        Value::Future(_) => {
            info.insert("pending".to_string(), Value::Bool(true));
            info.insert(
                "description".to_string(),
                Value::Str("Unevaluated future - use await to execute".to_string()),
            );
        }
        Value::Error(msg) => {
            info.insert("message".to_string(), Value::Str(msg.clone()));
            info.insert("is_error".to_string(), Value::Bool(true));
        }
        Value::Builtin(b) => {
            info.insert("name".to_string(), Value::Str(b.name.clone()));
            info.insert("is_builtin".to_string(), Value::Bool(true));
        }
    }

    Ok(Value::Record(info))
}

// --------------- Platform Detection Functions ---------------

/// platform() - Get the current platform name
/// Returns: String - One of "windows", "linux", "macos", "bsd", "ios", "android"
///
/// Example:
///   platform()  # Returns "windows" on Windows
fn bi_platform() -> Result<Value> {
    use crate::os_tools::OperatingSystem;
    let os = OperatingSystem::current();
    let platform_name = match os {
        OperatingSystem::Windows => "windows",
        OperatingSystem::Linux => "linux",
        OperatingSystem::MacOS => "macos",
        OperatingSystem::BSD => "bsd",
        OperatingSystem::iOS => "ios",
        OperatingSystem::Android => "android",
    };
    Ok(Value::Str(platform_name.to_string()))
}

/// is_windows() - Check if running on Windows
/// Returns: Bool
///
/// Example:
///   if is_windows() then "Windows!" else "Not Windows"
fn bi_is_windows() -> Result<Value> {
    Ok(Value::Bool(cfg!(target_os = "windows")))
}

/// is_linux() - Check if running on Linux (excluding Android)
/// Returns: Bool
///
/// Example:
///   if is_linux() then "Linux!" else "Not Linux"
fn bi_is_linux() -> Result<Value> {
    #[cfg(target_os = "linux")]
    {
        // Exclude Android
        let is_android = std::path::Path::new("/system/build.prop").exists();
        Ok(Value::Bool(!is_android))
    }
    #[cfg(not(target_os = "linux"))]
    {
        Ok(Value::Bool(false))
    }
}

/// is_macos() - Check if running on macOS
/// Returns: Bool
///
/// Example:
///   if is_macos() then "macOS!" else "Not macOS"
fn bi_is_macos() -> Result<Value> {
    Ok(Value::Bool(cfg!(target_os = "macos")))
}

/// is_unix() - Check if running on a Unix-like system (Linux, macOS, BSD, etc.)
/// Returns: Bool - true for Linux, macOS, BSD, Android, iOS (Unix-like systems)
///
/// Example:
///   if is_unix() then "/" else "\\"  # Path separator
fn bi_is_unix() -> Result<Value> {
    Ok(Value::Bool(cfg!(unix)))
}

/// is_bsd() - Check if running on BSD (FreeBSD, OpenBSD, NetBSD)
/// Returns: Bool
///
/// Example:
///   if is_bsd() then "BSD!" else "Not BSD"
fn bi_is_bsd() -> Result<Value> {
    let is_bsd = cfg!(target_os = "freebsd")
        || cfg!(target_os = "openbsd")
        || cfg!(target_os = "netbsd")
        || cfg!(target_os = "dragonfly");
    Ok(Value::Bool(is_bsd))
}

/// platform_module(base_path) - Get platform-specific module path
/// Args:
///   - base_path: String - Base module path without extension
/// Returns: String - Platform-specific module path
///
/// Given base_path "mymodule", returns:
///   - "mymodule_windows.ish" on Windows
///   - "mymodule_linux.ish" on Linux
///   - "mymodule_macos.ish" on macOS
///   - etc.
///
/// Example:
///   import platform_module("utils")  # Imports utils_windows.ish on Windows
fn bi_platform_module(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let base_path = if let Some(input_val) = input {
        match input_val {
            Value::Str(s) => s,
            other => {
                return Err(crate::safety::bad_arg(
                    "platform_module",
                    "base_path: String",
                    other.type_name(),
                ))
            }
        }
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(s) => s.clone(),
            other => {
                return Err(crate::safety::bad_arg(
                    "platform_module",
                    "base_path: String",
                    other.type_name(),
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err(
            "platform_module: requires base_path argument",
        ));
    };

    use crate::os_tools::OperatingSystem;
    let os = OperatingSystem::current();
    let platform_suffix = match os {
        OperatingSystem::Windows => "windows",
        OperatingSystem::Linux => "linux",
        OperatingSystem::MacOS => "macos",
        OperatingSystem::BSD => "bsd",
        OperatingSystem::iOS => "ios",
        OperatingSystem::Android => "android",
    };

    // Strip .ish extension if present
    let base = if base_path.ends_with(".ish") {
        &base_path[..base_path.len() - 3]
    } else {
        &base_path
    };

    let module_path = format!("{}_{}.ish", base, platform_suffix);
    Ok(Value::Str(module_path))
}

// --------------- Feature Flag Functions ---------------

/// features() - List all enabled runtime features
/// Returns: Array of String - Names of all enabled features
///
/// Example:
///   features()  # Returns ["ai", "experimental"] if those are enabled
fn bi_features() -> Result<Value> {
    let features = FEATURE_FLAGS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("features", "the feature table"))?;
    let feature_list: Vec<Value> = features.iter().map(|f| Value::Str(f.clone())).collect();
    Ok(Value::Array(feature_list))
}

/// feature_enabled(name) - Check if a runtime feature is enabled
/// Args:
///   - name: String - Feature name to check
/// Returns: Bool - true if the feature is enabled
///
/// Example:
///   feature_enabled("ai")        # Returns true if "ai" feature is enabled
///   has_feature("experimental")  # Alias
fn bi_feature_enabled(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = if let Some(input_val) = input {
        match input_val {
            Value::Str(s) => s,
            other => {
                return Err(crate::safety::bad_arg(
                    "feature_enabled",
                    "feature name: String",
                    other.type_name(),
                ))
            }
        }
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(s) => s.clone(),
            other => {
                return Err(crate::safety::bad_arg(
                    "feature_enabled",
                    "feature name: String",
                    other.type_name(),
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err(
            "feature_enabled: requires feature name argument",
        ));
    };

    let features = FEATURE_FLAGS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("feature_enabled", "the feature table"))?;
    Ok(Value::Bool(features.contains(&name)))
}

/// feature_enable(name) - Enable a runtime feature
/// Args:
///   - name: String - Feature name to enable
/// Returns: Bool - true (always succeeds)
///
/// Example:
///   feature_enable("experimental")
fn bi_feature_enable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = if let Some(input_val) = input {
        match input_val {
            Value::Str(s) => s,
            other => {
                return Err(crate::safety::bad_arg(
                    "feature_enable",
                    "feature name: String",
                    other.type_name(),
                ))
            }
        }
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(s) => s.clone(),
            other => {
                return Err(crate::safety::bad_arg(
                    "feature_enable",
                    "feature name: String",
                    other.type_name(),
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err(
            "feature_enable: requires feature name argument",
        ));
    };

    let mut features = FEATURE_FLAGS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("feature_enable", "the feature table"))?;
    features.insert(name);
    Ok(Value::Bool(true))
}

/// feature_disable(name) - Disable a runtime feature
/// Args:
///   - name: String - Feature name to disable
/// Returns: Bool - true if the feature was disabled, false if it wasn't enabled
///
/// Example:
///   feature_disable("experimental")
fn bi_feature_disable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = if let Some(input_val) = input {
        match input_val {
            Value::Str(s) => s,
            other => {
                return Err(crate::safety::bad_arg(
                    "feature_disable",
                    "feature name: String",
                    other.type_name(),
                ))
            }
        }
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(s) => s.clone(),
            other => {
                return Err(crate::safety::bad_arg(
                    "feature_disable",
                    "feature name: String",
                    other.type_name(),
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err(
            "feature_disable: requires feature name argument",
        ));
    };

    let mut features = FEATURE_FLAGS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("feature_disable", "the feature table"))?;
    let removed = features.remove(&name);
    Ok(Value::Bool(removed))
}

/// feature_set(name, enabled) - Set a runtime feature to enabled or disabled
/// Args:
///   - name: String - Feature name
///   - enabled: Bool - true to enable, false to disable
/// Returns: Bool - true (always succeeds)
///
/// Example:
///   feature_set("ai", true)       # Enable "ai" feature
///   feature_set("debug", false)   # Disable "debug" feature
fn bi_feature_set(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "feature_set";
    // Piped: the name is the subject and the one argument is `enabled`.
    // Direct: name and enabled are both arguments. Surplus arguments are
    // refused in either form, not dropped.
    let (name_value, enabled_value) = match input {
        Some(subject) => match args.as_slice() {
            [enabled] => (subject, enabled.clone()),
            _ => {
                return Err(crate::safety::arg_err(format!(
                    "{B}: piped, it takes exactly one argument (enabled), got {}",
                    args.len()
                )))
            }
        },
        None => match args.as_slice() {
            [name, enabled] => (name.clone(), enabled.clone()),
            _ => {
                return Err(crate::safety::arg_err(format!(
                    "{B} requires name and enabled arguments, got {}",
                    args.len()
                )))
            }
        },
    };
    let name = match name_value {
        Value::Str(s) => s,
        other => {
            return Err(crate::safety::bad_arg(
                B,
                "feature name: String",
                other.type_name(),
            ))
        }
    };
    let enabled = match enabled_value {
        Value::Bool(b) => b,
        other => {
            return Err(crate::safety::bad_arg(
                B,
                "enabled: Bool",
                other.type_name(),
            ))
        }
    };
    // A flag name is a short identifier. Anything else is refused rather than
    // stored, where it could never be matched by the feature it was meant for.
    if name.is_empty()
        || name.len() > 128
        || !name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | ':'))
    {
        return Err(crate::safety::bad_arg(
            B,
            "feature name: 1 to 128 letters, digits, '_', '-', '.' or ':'",
            &format!("{name:?}"),
        ));
    }
    let mut features = FEATURE_FLAGS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("feature_set", "the feature table"))?;
    if enabled {
        features.insert(name);
    } else {
        features.remove(&name);
    }
    Ok(Value::Bool(true))
}

// ===================== Distributed Computing Builtins =====================

/// cluster_create(name) - Create a new compute cluster
/// Args:
///   - name: String - Cluster name (optional, defaults to "default")
/// Returns: Record with cluster info
fn bi_cluster_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.len() > 1 {
        return Err(crate::safety::bad_arg(
            "cluster_create",
            "at most one name argument",
            &format!("{} arguments", args.len()),
        ));
    }
    // A name that is not a string used to become "default" with no word.
    let name = match input.or_else(|| args.first().cloned()) {
        None => "default".to_string(),
        Some(Value::Str(s)) if !s.is_empty() && s.len() <= 128 => s,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "cluster_create",
                "a cluster name: a non-empty string of at most 128 bytes",
                other.type_name(),
            ))
        }
    };

    // The cluster is stored in this process's registry, where cluster_status
    // counts it. Nothing is started and no node is contacted. Nodes added with
    // cluster_add_node join a separate process-wide node registry that does not
    // record which cluster they belong to.
    let created_at = chrono::Utc::now().to_rfc3339();
    {
        let mut clusters = CLUSTERS
            .write()
            .map_err(|_| crate::safety::lock_poisoned("cluster_create", "the cluster registry"))?;
        if clusters.contains_key(&name) {
            return Err(crate::safety::bad_arg(
                "cluster_create",
                "a cluster name not already in use in this process",
                &format!("{name:?}, which is already a cluster"),
            ));
        }
        if clusters.len() >= CLUSTER_MAX {
            return Err(crate::safety::budget_exceeded(
                "cluster_create",
                format!("{CLUSTER_MAX} clusters are already stored in this process"),
                "this process has no cluster removal; start a new process to reset the registry",
            ));
        }
        clusters.insert(name.clone(), created_at.clone());
    }

    let mut record = BTreeMap::new();
    record.insert("name".to_string(), Value::Str(name));
    record.insert("status".to_string(), Value::Str("created".to_string()));
    record.insert("created_at".to_string(), Value::Str(created_at));
    Ok(Value::Record(record))
}

/// Most clusters one process stores. The registry has no removal builtin.
const CLUSTER_MAX: usize = 64;

/// cluster_add_node(id, address, capabilities?) - Add a node to the cluster
/// Args:
///   - id: String - Node identifier
///   - address: String - Node address (e.g., "192.168.1.10:8080")
///   - capabilities: Array - Optional list of capabilities
/// Returns: Record with node info
fn bi_cluster_add_node(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (id, address) = if let Some(Value::Record(rec)) = input.clone() {
        // Record input: {id: "...", address: "..."}
        let id = rec
            .get("id")
            .map(|v| v.to_display_string())
            .ok_or_else(|| crate::safety::arg_err("cluster_add_node: missing 'id' in record"))?;
        let address = rec
            .get("address")
            .map(|v| v.to_display_string())
            .ok_or_else(|| {
                crate::safety::arg_err("cluster_add_node: missing 'address' in record")
            })?;
        (id, address)
    } else if args.len() >= 2 {
        let id = args[0].to_display_string();
        let address = args[1].to_display_string();
        (id, address)
    } else {
        return Err(crate::safety::arg_err(
            "cluster_add_node: requires id and address arguments",
        ));
    };

    if args.len() > 3 {
        return Err(crate::safety::bad_arg(
            "cluster_add_node",
            "at most 3 arguments: id, address, capabilities",
            &format!("{} arguments", args.len()),
        ));
    }
    if id.is_empty() || address.is_empty() || address.chars().any(char::is_whitespace) {
        return Err(crate::safety::bad_arg(
            "cluster_add_node",
            "a non-empty id and an address with no whitespace",
            &format!("id '{id}', address '{address}'"),
        ));
    }

    let capabilities = match args.get(2) {
        None => vec!["compute".to_string(), "storage".to_string()],
        // An array of strings or nothing. Anything else used to become an
        // empty capability list with no error.
        Some(Value::Array(arr)) => {
            let mut caps = Vec::with_capacity(arr.len());
            for c in arr {
                match c {
                    Value::Str(s) => caps.push(s.clone()),
                    other => {
                        return Err(crate::safety::bad_arg(
                            "cluster_add_node",
                            "capabilities: Array<String>",
                            other.type_name(),
                        ))
                    }
                }
            }
            caps
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "cluster_add_node",
                "capabilities: Array<String>",
                other.type_name(),
            ))
        }
    };

    let node = ClusterNode {
        id: id.clone(),
        address: address.clone(),
        capabilities: capabilities.clone(),
        status: NodeStatus::Registered,
        load: 0.0,
        last_heartbeat: std::time::Instant::now(),
    };

    let mut nodes = CLUSTER_NODES
        .write()
        .map_err(|_| crate::safety::lock_poisoned("cluster_add_node", "the cluster node table"))?;
    nodes.insert(id.clone(), node);

    let mut record = BTreeMap::new();
    record.insert("id".to_string(), Value::Str(id));
    record.insert("address".to_string(), Value::Str(address));
    record.insert(
        "capabilities".to_string(),
        Value::Array(capabilities.into_iter().map(Value::Str).collect()),
    );
    // Nothing contacted the node, so it is not "online": it is registered in
    // this process. Liveness is not checked by anything in this builtin.
    record.insert("status".to_string(), Value::Str("registered".to_string()));

    Ok(Value::Record(record))
}

/// cluster_remove_node(id) - Remove a node from the cluster
fn bi_cluster_remove_node(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let id = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("cluster_remove_node", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("cluster_remove_node: requires node id"))?;

    let mut nodes = CLUSTER_NODES.write().map_err(|_| {
        crate::safety::lock_poisoned("cluster_remove_node", "the cluster node table")
    })?;

    let removed = nodes.remove(&id).is_some();
    Ok(Value::Bool(removed))
}

/// cluster_status() - Get cluster status
fn bi_cluster_status(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let nodes = CLUSTER_NODES
        .read()
        .map_err(|_| crate::safety::lock_poisoned("cluster_status", "the cluster node table"))?;

    let jobs = DISTRIBUTED_JOBS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("cluster_status", "the distributed job table"))?;
    let clusters = CLUSTERS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("cluster_status", "the cluster registry"))?;

    let online_count = nodes
        .values()
        .filter(|n| n.status == NodeStatus::Online)
        .count();
    let busy_count = nodes
        .values()
        .filter(|n| n.status == NodeStatus::Busy)
        .count();
    // Nodes added by cluster_add_node are registered, not checked, so they are
    // counted here and not as online.
    let registered_count = nodes
        .values()
        .filter(|n| n.status == NodeStatus::Registered)
        .count();
    let pending_jobs = jobs
        .values()
        .filter(|j| j.status == JobStatus::Pending)
        .count();
    let running_jobs = jobs
        .values()
        .filter(|j| j.status == JobStatus::Running)
        .count();
    let avg_load: f32 = if nodes.is_empty() {
        0.0
    } else {
        nodes.values().map(|n| n.load).sum::<f32>() / nodes.len() as f32
    };

    let mut record = BTreeMap::new();
    record.insert("clusters".to_string(), Value::Int(clusters.len() as i64));
    record.insert(
        "cluster_names".to_string(),
        Value::Array(clusters.keys().map(|k| Value::Str(k.clone())).collect()),
    );
    record.insert("total_nodes".to_string(), Value::Int(nodes.len() as i64));
    record.insert("online_nodes".to_string(), Value::Int(online_count as i64));
    record.insert(
        "registered_nodes".to_string(),
        Value::Int(registered_count as i64),
    );
    record.insert("busy_nodes".to_string(), Value::Int(busy_count as i64));
    record.insert("total_jobs".to_string(), Value::Int(jobs.len() as i64));
    record.insert("pending_jobs".to_string(), Value::Int(pending_jobs as i64));
    record.insert("running_jobs".to_string(), Value::Int(running_jobs as i64));
    record.insert("average_load".to_string(), Value::Float(avg_load as f64));

    Ok(Value::Record(record))
}

/// cluster_nodes() - List all nodes in the cluster
fn bi_cluster_nodes(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let nodes = CLUSTER_NODES
        .read()
        .map_err(|_| crate::safety::lock_poisoned("cluster_nodes", "the cluster node table"))?;

    let node_list: Vec<Value> = nodes
        .values()
        .map(|node| {
            let mut record = BTreeMap::new();
            record.insert("id".to_string(), Value::Str(node.id.clone()));
            record.insert("address".to_string(), Value::Str(node.address.clone()));
            record.insert(
                "status".to_string(),
                Value::Str(node.status.as_str().to_string()),
            );
            record.insert("load".to_string(), Value::Float(node.load as f64));
            record.insert(
                "capabilities".to_string(),
                Value::Array(
                    node.capabilities
                        .iter()
                        .map(|c| Value::Str(c.clone()))
                        .collect(),
                ),
            );
            Value::Record(record)
        })
        .collect();

    Ok(Value::Array(node_list))
}

/// job_submit(name, task, priority?) - Refused. The distributed job table has no
/// executor behind it: a job submitted here would stay pending for ever, and the
/// status it reported would be a promise nothing keeps. No job id is issued, and
/// nothing is run through a shell.
fn bi_job_submit(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("job_submit", &input)?;
    collab_text_arg("job_submit", "name", args.first(), 128)?;
    collab_text_arg("job_submit", "task", args.get(1), 4096)?;
    match args.get(2) {
        None | Some(Value::Int(_)) => {}
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "job_submit",
                "priority: Int",
                other.type_name(),
            ))
        }
    }
    Err(crate::safety::unimplemented(
        "job_submit",
        "there is no job executor, so a submitted job would never run and no job id is issued",
        "run the task directly in this session",
    ))
}

/// job_status(job_id) - The status of a job in the distributed job table.
fn bi_job_status(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let job_id = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("job_status", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("job_status: requires job_id"))?;

    let jobs = DISTRIBUTED_JOBS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("job_status", "the distributed job table"))?;

    let job = jobs
        .get(&job_id)
        .ok_or_else(|| crate::safety::not_found("job_status", "job", &job_id.to_string()))?;

    let mut record = BTreeMap::new();
    record.insert("job_id".to_string(), Value::Str(job.id.clone()));
    record.insert("name".to_string(), Value::Str(job.name.clone()));
    record.insert(
        "status".to_string(),
        Value::Str(job.status.as_str().to_string()),
    );
    record.insert("priority".to_string(), Value::Int(job.priority as i64));
    if let Some(node_id) = &job.node_id {
        record.insert("node_id".to_string(), Value::Str(node_id.clone()));
    }

    Ok(Value::Record(record))
}

/// job_cancel(job_id) - Cancel a pending or running job. A job that has already
/// finished or been cancelled is refused, not reported as a silent false.
fn bi_job_cancel(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let job_id = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("job_cancel", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("job_cancel: requires job_id"))?;

    let mut jobs = DISTRIBUTED_JOBS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("job_cancel", "the distributed job table"))?;

    let job = jobs
        .get_mut(&job_id)
        .ok_or_else(|| crate::safety::not_found("job_cancel", "job", &job_id.to_string()))?;
    match job.status {
        JobStatus::Pending | JobStatus::Running => {
            job.status = JobStatus::Cancelled;
            Ok(Value::Bool(true))
        }
        _ => Err(crate::safety::bad_state(
            "job_cancel",
            &format!(
                "job {job_id} is {}; only a pending or running job cancels",
                job.status.as_str()
            ),
            "job_status",
        )),
    }
}

/// job_results(job_id) - Get the results of a completed job
fn bi_job_results(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let job_id = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("job_results", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("job_results: requires job_id"))?;

    let results = JOB_RESULTS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("job_results", "the job result store"))?;

    if let Some(result_values) = results.get(&job_id) {
        Ok(Value::Array(result_values.clone()))
    } else {
        Ok(Value::Array(vec![]))
    }
}

/// job_list() - List all jobs
fn bi_job_list(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let jobs = DISTRIBUTED_JOBS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("job_list", "the distributed job table"))?;

    let job_list: Vec<Value> = jobs
        .values()
        .map(|job| {
            let mut record = BTreeMap::new();
            record.insert("job_id".to_string(), Value::Str(job.id.clone()));
            record.insert("name".to_string(), Value::Str(job.name.clone()));
            record.insert(
                "status".to_string(),
                Value::Str(job.status.as_str().to_string()),
            );
            record.insert("priority".to_string(), Value::Int(job.priority as i64));
            Value::Record(record)
        })
        .collect();

    Ok(Value::Array(job_list))
}

/// remote_exec(node_id, command), or the same two fields as a Record piped in:
/// not implemented. No SSH or cluster transport is wired, so the command is not
/// sent to the node. Once it is, the remote node runs `command` through its
/// login shell, because ssh hands the string to the remote shell; a caller must
/// treat `command` as shell input. Arguments are checked first: a plain node
/// name, a non-empty command of at most 8 KiB, and a node that is registered.
fn bi_remote_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "remote_exec";
    let (node, command) = match input {
        Some(Value::Record(rec)) => {
            if !args.is_empty() {
                return Err(crate::safety::arg_err(
                    "remote_exec: give the node and command as arguments or as a piped Record, not both",
                ));
            }
            for key in rec.keys() {
                if key != "node_id" && key != "command" {
                    return Err(crate::safety::arg_err(format!(
                        "remote_exec: unknown field {key:?}; the fields are node_id and command"
                    )));
                }
            }
            let text = |field: &str| -> Result<String> {
                match rec.get(field) {
                    Some(Value::Str(s)) => Ok(s.clone()),
                    Some(other) => Err(crate::safety::arg_err(format!(
                        "remote_exec: {field} must be a String, got {}",
                        other.type_name()
                    ))),
                    None => Err(crate::safety::arg_err(format!(
                        "remote_exec: missing '{field}'"
                    ))),
                }
            };
            (text("node_id")?, text("command")?)
        }
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "remote_exec: a piped input must be a Record with node_id and command, got {}",
                other.type_name()
            )))
        }
        None => {
            k8s_max_args(B, &args, 2)?;
            let node = k8s_need(B, "a node id", &args, 0, pkg_plain)?;
            let command = match args.get(1) {
                Some(Value::Str(s)) => s.clone(),
                Some(other) => {
                    return Err(crate::safety::arg_err(format!(
                        "remote_exec: command must be a String, got {}",
                        other.type_name()
                    )))
                }
                None => {
                    return Err(crate::safety::arg_err(
                        "remote_exec requires node_id and command",
                    ))
                }
            };
            (node, command)
        }
    };
    let node_id = pkg_plain(B, "node id", &node)?;
    if command.trim().is_empty() || command.contains('\0') || command.len() > OPS_MAX_COMMAND {
        return Err(crate::safety::arg_err(format!(
            "remote_exec: command must be non-empty, without NUL, and at most {OPS_MAX_COMMAND} bytes"
        )));
    }
    let known = CLUSTER_NODES
        .read()
        .map_err(|_| crate::safety::lock_poisoned("remote_exec", "the cluster node table"))?
        .contains_key(&node_id);
    if !known {
        return Err(crate::safety::not_found(B, "node", &node_id));
    }
    Err(crate::safety::unimplemented(
        B,
        &format!(
            "the command was not sent to node {node_id:?}: no SSH or cluster transport is wired"
        ),
        "use ssh_exec for a remote command",
    ))
}

/// aggregate_results(results, strategy?) - Aggregate results from distributed computation
fn bi_aggregate_results(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Piped: the results are the input and the strategy is the only argument.
    // Unpiped: results, then strategy. The strategy used to be read from
    // position 1 either way, so `[..] | aggregate_results("sum")` silently
    // aggregated with "concat".
    let (results, strategy_arg) = match input {
        Some(v) => {
            if args.len() > 1 {
                return Err(crate::safety::bad_arg(
                    "aggregate_results",
                    "with piped input, at most one argument: the strategy",
                    &format!("{} arguments", args.len()),
                ));
            }
            (v, args.first())
        }
        None => {
            if args.len() > 2 {
                return Err(crate::safety::bad_arg(
                    "aggregate_results",
                    "results, then an optional strategy",
                    &format!("{} arguments", args.len()),
                ));
            }
            let r = args.first().cloned().ok_or_else(|| {
                crate::safety::arg_err("aggregate_results: requires results array")
            })?;
            (r, args.get(1))
        }
    };

    let results = match results {
        Value::Array(arr) => arr,
        other => {
            return Err(crate::safety::bad_arg(
                "aggregate_results",
                "results: Array",
                other.type_name(),
            ))
        }
    };

    let strategy = match strategy_arg {
        None => "concat".to_string(),
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "aggregate_results",
                "strategy: a string (concat, sum, count, first, last)",
                other.type_name(),
            ))
        }
    };

    match strategy.as_str() {
        "concat" => Ok(Value::Array(results)),
        "sum" => {
            // A non-number used to be skipped, so the sum of a list with a
            // failed element looked like a sum of the rest. Refuse it.
            let mut sum = 0.0f64;
            for (i, v) in results.iter().enumerate() {
                match v {
                    Value::Int(n) => sum += *n as f64,
                    Value::Float(f) if f.is_finite() => sum += *f,
                    other => {
                        return Err(crate::safety::bad_arg(
                            "aggregate_results",
                            &format!("results[{i}]: a finite number for strategy \"sum\""),
                            other.type_name(),
                        ))
                    }
                }
            }
            Ok(Value::Float(sum))
        }
        "count" => Ok(Value::Int(results.len() as i64)),
        "first" | "last" => {
            let pick = if strategy == "first" {
                results.first()
            } else {
                results.last()
            };
            // An empty list has no first or last element: that is a failure,
            // not a Null answer.
            pick.cloned().ok_or_else(|| {
                crate::safety::bad_arg(
                    "aggregate_results",
                    &format!("a non-empty results array for strategy \"{strategy}\""),
                    "an empty array",
                )
            })
        }
        other => Err(crate::safety::bad_arg(
            "aggregate_results",
            "strategy: one of concat, sum, count, first, last",
            other,
        )),
    }
}

// ===================== Advanced AI Builtins =====================

/// rag_index(content, source?, metadata?) - Index a document for RAG
fn bi_rag_index(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // The index lives for the whole process and every document is kept, so
    // both the size of one document and the number held are bounded.
    const MAX_DOC_BYTES: usize = 1 << 20;
    const MAX_DOCS: usize = 10_000;

    // Piped, the content is the input and `args` are source and metadata.
    // Unpiped, `args` are content, source and metadata. Reading source from
    // `args[1]` either way dropped a piped source without a word.
    let (content_in, rest): (Option<Value>, &[Value]) = match input {
        Some(v) => (Some(v), &args[..]),
        None => (args.first().cloned(), args.get(1..).unwrap_or(&[])),
    };
    if rest.len() > 2 {
        return Err(crate::safety::bad_arg(
            "rag_index",
            "at most 3 arguments: content, source, metadata",
            &format!("{} arguments", args.len()),
        ));
    }
    let content = match content_in {
        Some(Value::Str(s)) if s.len() <= MAX_DOC_BYTES => s,
        Some(Value::Str(s)) => {
            return Err(crate::safety::budget_exceeded(
                "rag_index",
                format!("content is {} bytes; the limit is {MAX_DOC_BYTES}", s.len()),
                "index a smaller document or split it",
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "rag_index",
                "content: a string",
                other.type_name(),
            ))
        }
        None => return Err(crate::safety::arg_err("rag_index: requires content")),
    };

    let source = match rest.first() {
        None | Some(Value::Null) => "unknown".to_string(),
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "rag_index",
                "source: a string",
                other.type_name(),
            ))
        }
    };

    let metadata: HashMap<String, String> = match rest.get(1) {
        None | Some(Value::Null) => HashMap::new(),
        Some(Value::Record(rec)) => rec
            .iter()
            .map(|(k, v)| (k.clone(), v.to_display_string()))
            .collect(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "rag_index",
                "metadata: a Record",
                other.type_name(),
            ))
        }
    };

    let mut index = RAG_INDEX
        .write()
        .map_err(|_| crate::safety::lock_poisoned("rag_index", "the RAG index"))?;
    if index.chunks.len() >= MAX_DOCS {
        return Err(crate::safety::budget_exceeded(
            "rag_index",
            format!("the index already holds {MAX_DOCS} documents"),
            "the index is process-local and has no removal; start a new process",
        ));
    }

    let doc_id = index.add_document(&content, &source, metadata);

    let mut record = BTreeMap::new();
    record.insert("doc_id".to_string(), Value::Str(doc_id));
    record.insert("source".to_string(), Value::Str(source));
    record.insert("chunk_count".to_string(), Value::Int(1));
    record.insert(
        "total_docs".to_string(),
        Value::Int(index.chunks.len() as i64),
    );

    Ok(Value::Record(record))
}

/// Most chunks rag_search returns, and most rag_query gathers into its context.
const RAG_SEARCH_MAX_TOP_K: usize = 100;
const RAG_QUERY_MAX_TOP_K: usize = 20;

/// The query and `top_k` of a rag call. Piped, the query is the input and
/// `args` holds only `top_k`; called directly, `args` is `query, top_k`. The
/// old code read `top_k` from `args[1]` either way, so a piped count was
/// ignored. `top_k` must be an integer from 1 up to `ceiling`: a negative
/// count used to wrap through `as usize`, and anything else fell back to the
/// default without a word.
fn rag_query_top_k(
    builtin: &str,
    args: &[Value],
    input: Option<Value>,
    default: usize,
    ceiling: usize,
) -> Result<(String, usize)> {
    let (query_v, rest): (Value, &[Value]) = match input {
        Some(v) => (v, args),
        None => match args.split_first() {
            Some((first, rest)) => (first.clone(), rest),
            None => return Err(crate::safety::arg_err(format!("{builtin}: requires query"))),
        },
    };
    if rest.len() > 1 {
        return Err(crate::safety::bad_arg(
            builtin,
            "at most 2 arguments when called directly (query, top_k); 1 when piped (top_k)",
            &format!("{} arguments", args.len()),
        ));
    }
    let query = key_arg(builtin, query_v)?;
    let top_k = match rest.first() {
        None | Some(Value::Null) => default,
        Some(Value::Int(n)) if *n < 1 => {
            return Err(crate::safety::bad_arg(
                builtin,
                "top_k: an integer from 1 up",
                &n.to_string(),
            ))
        }
        Some(Value::Int(n)) if *n as u128 > ceiling as u128 => {
            return Err(crate::safety::budget_exceeded(
                builtin,
                format!("top_k {n} is above the limit {ceiling}"),
                "ask for fewer chunks",
            ))
        }
        Some(Value::Int(n)) => *n as usize,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "top_k: an integer",
                other.type_name(),
            ))
        }
    };
    Ok((query, top_k))
}

/// rag_search(query, top_k?) - Search indexed documents
fn bi_rag_search(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (query, top_k) = rag_query_top_k("rag_search", &args, input, 5, RAG_SEARCH_MAX_TOP_K)?;

    let index = RAG_INDEX
        .read()
        .map_err(|_| crate::safety::lock_poisoned("rag_search", "the RAG index"))?;

    let results = index.search(&query, top_k);

    let result_values: Vec<Value> = results
        .iter()
        .map(|(chunk, score)| {
            let mut record = BTreeMap::new();
            record.insert("doc_id".to_string(), Value::Str(chunk.id.clone()));
            record.insert("content".to_string(), Value::Str(chunk.content.clone()));
            record.insert("source".to_string(), Value::Str(chunk.source.clone()));
            record.insert("score".to_string(), Value::Float(*score as f64));
            Value::Record(record)
        })
        .collect();

    Ok(Value::Array(result_values))
}

/// rag_query(query, top_k?) - Search and generate a response using RAG
fn bi_rag_query(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (query, top_k) = rag_query_top_k("rag_query", &args, input, 3, RAG_QUERY_MAX_TOP_K)?;

    let index = RAG_INDEX
        .read()
        .map_err(|_| crate::safety::lock_poisoned("rag_query", "the RAG index"))?;

    let results = index.search(&query, top_k);

    // Build context from retrieved documents
    let context: String = results
        .iter()
        .map(|(chunk, _)| chunk.content.as_str())
        .collect::<Vec<_>>()
        .join("\n\n");

    let mut record = BTreeMap::new();
    record.insert("query".to_string(), Value::Str(query));
    record.insert("context".to_string(), Value::Str(context));
    record.insert(
        "sources".to_string(),
        Value::Array(
            results
                .iter()
                .map(|(chunk, _)| Value::Str(chunk.source.clone()))
                .collect(),
        ),
    );
    record.insert("doc_count".to_string(), Value::Int(results.len() as i64));

    Ok(Value::Record(record))
}

/// rag_clear() - Clear the RAG index
fn bi_rag_clear(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let mut index = RAG_INDEX
        .write()
        .map_err(|_| crate::safety::lock_poisoned("rag_clear", "the RAG index"))?;

    let count = index.chunks.len();
    index.clear();

    Ok(Value::Int(count as i64))
}

/// The optional properties record of a `kg_*` call: absent or null is empty,
/// a Record is taken, and anything else is refused rather than dropped.
fn kg_properties(builtin: &str, v: Option<&Value>) -> Result<HashMap<String, String>> {
    match v {
        None | Some(Value::Null) => Ok(HashMap::new()),
        Some(Value::Record(rec)) => Ok(rec
            .iter()
            .map(|(k, v)| (k.clone(), v.to_display_string()))
            .collect()),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            "properties: a Record",
            other.type_name(),
        )),
    }
}

/// kg_add(type, name, properties?) - Add an entity to the knowledge graph
fn bi_kg_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const MAX_ENTITIES: usize = 100_000;
    if args.len() > 3 {
        return Err(crate::safety::bad_arg(
            "kg_add",
            "at most 3 arguments: type, name, properties",
            &format!("{} arguments", args.len()),
        ));
    }
    // Only a Record is documented as piped input; anything else was dropped.
    if matches!(&input, Some(v) if !matches!(v, Value::Record(_))) {
        return Err(crate::safety::bad_arg(
            "kg_add",
            "piped input: a Record {type, name, properties?}",
            input.as_ref().map_or("nothing", |v| v.type_name()),
        ));
    }
    let (entity_type, name) = if let Some(Value::Record(rec)) = input {
        let entity_type = rec
            .get("type")
            .map(|v| v.to_display_string())
            .ok_or_else(|| crate::safety::arg_err("kg_add: missing 'type'"))?;
        let name = rec
            .get("name")
            .map(|v| v.to_display_string())
            .ok_or_else(|| crate::safety::arg_err("kg_add: missing 'name'"))?;
        (entity_type, name)
    } else if args.len() >= 2 {
        (args[0].to_display_string(), args[1].to_display_string())
    } else {
        return Err(crate::safety::arg_err("kg_add: requires type and name"));
    };

    let properties = kg_properties("kg_add", args.get(2))?;

    let mut kg = KNOWLEDGE_GRAPH
        .write()
        .map_err(|_| crate::safety::lock_poisoned("kg_add", "the knowledge graph"))?;
    if kg.entities.len() >= MAX_ENTITIES {
        return Err(crate::safety::budget_exceeded(
            "kg_add",
            format!("the knowledge graph already holds {MAX_ENTITIES} entities"),
            "the graph is process-local and has no removal; start a new process",
        ));
    }

    let entity_id = kg.add_entity(&entity_type, &name, properties);

    let mut record = BTreeMap::new();
    record.insert("entity_id".to_string(), Value::Str(entity_id));
    record.insert("type".to_string(), Value::Str(entity_type));
    record.insert("name".to_string(), Value::Str(name));

    Ok(Value::Record(record))
}

/// kg_relate(source_id, target_id, relation_type, properties?) - Add a relation
fn bi_kg_relate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.len() > 4 {
        return Err(crate::safety::bad_arg(
            "kg_relate",
            "at most 4 arguments: source, target, relation, properties",
            &format!("{} arguments", args.len()),
        ));
    }
    if matches!(&input, Some(v) if !matches!(v, Value::Record(_))) {
        return Err(crate::safety::bad_arg(
            "kg_relate",
            "piped input: a Record {source, target, relation, properties?}",
            input.as_ref().map_or("nothing", |v| v.type_name()),
        ));
    }
    let (source_id, target_id, relation_type) = if let Some(Value::Record(rec)) = input {
        let source = rec
            .get("source")
            .map(|v| v.to_display_string())
            .ok_or_else(|| crate::safety::arg_err("kg_relate: missing 'source'"))?;
        let target = rec
            .get("target")
            .map(|v| v.to_display_string())
            .ok_or_else(|| crate::safety::arg_err("kg_relate: missing 'target'"))?;
        let rel_type = rec
            .get("relation")
            .map(|v| v.to_display_string())
            .ok_or_else(|| crate::safety::arg_err("kg_relate: missing 'relation'"))?;
        (source, target, rel_type)
    } else if args.len() >= 3 {
        (
            args[0].to_display_string(),
            args[1].to_display_string(),
            args[2].to_display_string(),
        )
    } else {
        return Err(crate::safety::arg_err(
            "kg_relate: requires source_id, target_id, and relation_type",
        ));
    };

    let properties = kg_properties("kg_relate", args.get(3))?;

    let mut kg = KNOWLEDGE_GRAPH
        .write()
        .map_err(|_| crate::safety::lock_poisoned("kg_relate", "the knowledge graph"))?;

    let relation_id = kg.add_relation(&source_id, &target_id, &relation_type, properties)?;

    let mut record = BTreeMap::new();
    record.insert("relation_id".to_string(), Value::Str(relation_id));
    record.insert("source".to_string(), Value::Str(source_id));
    record.insert("target".to_string(), Value::Str(target_id));
    record.insert("relation_type".to_string(), Value::Str(relation_type));

    Ok(Value::Record(record))
}

/// kg_query(pattern) - Query the knowledge graph
fn bi_kg_query(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let pattern = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("kg_query", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("kg_query: requires pattern"))?;

    let kg = KNOWLEDGE_GRAPH
        .read()
        .map_err(|_| crate::safety::lock_poisoned("kg_query", "the knowledge graph"))?;

    let results = kg.query(&pattern);
    Ok(Value::Array(results))
}

/// kg_entities() - List all entities in the knowledge graph
fn bi_kg_entities(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let kg = KNOWLEDGE_GRAPH
        .read()
        .map_err(|_| crate::safety::lock_poisoned("kg_entities", "the knowledge graph"))?;

    let entities: Vec<Value> = kg
        .entities
        .values()
        .map(|entity| {
            let mut record = BTreeMap::new();
            record.insert("id".to_string(), Value::Str(entity.id.clone()));
            record.insert("type".to_string(), Value::Str(entity.entity_type.clone()));
            record.insert("name".to_string(), Value::Str(entity.name.clone()));
            Value::Record(record)
        })
        .collect();

    Ok(Value::Array(entities))
}

/// kg_relations() - List all relations in the knowledge graph
fn bi_kg_relations(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let kg = KNOWLEDGE_GRAPH
        .read()
        .map_err(|_| crate::safety::lock_poisoned("kg_relations", "the knowledge graph"))?;

    let relations: Vec<Value> = kg
        .relations
        .iter()
        .map(|rel| {
            let mut record = BTreeMap::new();
            record.insert("id".to_string(), Value::Str(rel.id.clone()));
            record.insert("source".to_string(), Value::Str(rel.source_id.clone()));
            record.insert("target".to_string(), Value::Str(rel.target_id.clone()));
            record.insert("type".to_string(), Value::Str(rel.relation_type.clone()));
            Value::Record(record)
        })
        .collect();

    Ok(Value::Array(relations))
}

/// semantic_cache(query, response) - Store a response in the semantic cache
fn bi_semantic_cache(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const MAX_QUERY_BYTES: usize = 4096;
    const MAX_RESPONSE_BYTES: usize = 256 * 1024;
    if args.len() > 2 {
        return Err(crate::safety::bad_arg(
            "semantic_cache",
            "at most 2 arguments: query, response",
            &format!("{} arguments", args.len()),
        ));
    }
    if matches!(&input, Some(v) if !matches!(v, Value::Record(_))) {
        return Err(crate::safety::bad_arg(
            "semantic_cache",
            "piped input: a Record {query, response}",
            input.as_ref().map_or("nothing", |v| v.type_name()),
        ));
    }
    let (query, response) = if let Some(Value::Record(rec)) = input {
        let query = rec
            .get("query")
            .map(|v| v.to_display_string())
            .ok_or_else(|| crate::safety::arg_err("semantic_cache: missing 'query'"))?;
        let response = rec
            .get("response")
            .map(|v| v.to_display_string())
            .ok_or_else(|| crate::safety::arg_err("semantic_cache: missing 'response'"))?;
        (query, response)
    } else if args.len() >= 2 {
        (args[0].to_display_string(), args[1].to_display_string())
    } else {
        return Err(crate::safety::arg_err(
            "semantic_cache: requires query and response",
        ));
    };
    if query.is_empty() || query.len() > MAX_QUERY_BYTES {
        return Err(crate::safety::bad_arg(
            "semantic_cache",
            &format!("a query of 1 to {MAX_QUERY_BYTES} bytes"),
            &format!("{} bytes", query.len()),
        ));
    }
    if response.len() > MAX_RESPONSE_BYTES {
        return Err(crate::safety::budget_exceeded(
            "semantic_cache",
            format!(
                "response is {} bytes; the limit is {MAX_RESPONSE_BYTES}",
                response.len()
            ),
            "cache a shorter response",
        ));
    }

    let mut cache = SEMANTIC_CACHE
        .write()
        .map_err(|_| crate::safety::lock_poisoned("semantic_cache", "the semantic cache"))?;

    cache.put(&query, &response);

    let (entries, hits) = cache.stats();
    let mut record = BTreeMap::new();
    record.insert("cached".to_string(), Value::Bool(true));
    record.insert("total_entries".to_string(), Value::Int(entries as i64));
    record.insert("total_hits".to_string(), Value::Int(hits as i64));

    Ok(Value::Record(record))
}

/// semantic_cache_get(query) - Try to get a cached response
fn bi_semantic_cache_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let query = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("semantic_cache_get", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("semantic_cache_get: requires query"))?;

    let mut cache = SEMANTIC_CACHE
        .write()
        .map_err(|_| crate::safety::lock_poisoned("semantic_cache_get", "the semantic cache"))?;

    if let Some(response) = cache.get(&query) {
        let mut record = BTreeMap::new();
        record.insert("hit".to_string(), Value::Bool(true));
        record.insert("response".to_string(), Value::Str(response));
        Ok(Value::Record(record))
    } else {
        let mut record = BTreeMap::new();
        record.insert("hit".to_string(), Value::Bool(false));
        Ok(Value::Record(record))
    }
}

/// semantic_cache_clear() - Clear the semantic cache
fn bi_semantic_cache_clear(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let mut cache = SEMANTIC_CACHE
        .write()
        .map_err(|_| crate::safety::lock_poisoned("semantic_cache_clear", "the semantic cache"))?;

    let (count, _) = cache.stats();
    cache.clear();

    Ok(Value::Int(count as i64))
}

// --------------- AI / Agents wrappers (optional) ---------------

/// The most steps one agent or swarm run may take. Each step can be a model
/// call, so an unbounded `max_steps` is an unbounded bill.
const MAX_AGENT_STEPS: i64 = 1000;

/// The keys an agent or swarm config record may carry. Any other key is
/// refused: the body used to ignore it, so a caller who set `model_uri` got a
/// run on whatever model the environment picked, with no error.
const AGENT_CONFIG_KEYS: &[&str] = &["goal", "tools", "max_steps", "dry_run"];

/// One agent or swarm call, with every argument checked before anything runs.
struct AgentCall {
    goal: String,
    tools: Vec<String>,
    max_steps: usize,
    dry_run: bool,
}

/// Read the arguments of `agent(...)` or `swarm(...)` in each of their forms:
///
/// - a config record, as the argument or as the piped input;
/// - `goal, [tools...], [max_steps], [dry_run]`, with the tools as Strings or
///   as one Array of them;
/// - `goal, json`, where `json` is a JSON object whose keys are the config.
///
/// Every argument is either used or refused. A surplus argument, or one of the
/// wrong type, used to be dropped and the run went ahead without it. Nothing
/// here calls a model, so a refusal costs no rate-limit budget and no tokens.
fn parse_agent_call(
    builtin: &str,
    args: &[Value],
    input: Option<&Value>,
    default_steps: usize,
) -> Result<AgentCall> {
    if let Some(piped) = input {
        return match piped {
            Value::Record(cfg) if args.is_empty() => {
                agent_config(builtin, cfg.clone(), default_steps)
            }
            Value::Record(_) => Err(crate::safety::arg_err(format!(
                "{builtin}: a piped config takes no other arguments"
            ))),
            other => Err(crate::safety::arg_err(format!(
                "{builtin}: piped input must be a config record, got {}",
                other.type_name()
            ))),
        };
    }
    let goal_raw = match args.first() {
        Some(Value::Record(cfg)) => {
            if args.len() > 1 {
                return Err(surplus_arg(builtin, &args[1]));
            }
            return agent_config(builtin, cfg.clone(), default_steps);
        }
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "a goal String, or a config Record",
                other.type_name(),
            ))
        }
        None => return Err(crate::safety::bad_arg(builtin, "a goal String", "nothing")),
    };

    // A JSON object as the second argument is a whole config; the goal is the
    // first argument.
    if let Some(Value::Str(s)) = args.get(1) {
        let text = s.trim();
        if text.starts_with('{') {
            let json: serde_json::Value = serde_json::from_str(text).map_err(|e| {
                crate::safety::arg_err(format!("{builtin}: config JSON does not parse: {e}"))
            })?;
            let mut cfg = match Value::from_json(&json) {
                Value::Record(cfg) => cfg,
                _ => {
                    return Err(crate::safety::arg_err(format!(
                        "{builtin}: config JSON must be an object"
                    )))
                }
            };
            cfg.insert("goal".into(), Value::Str(goal_raw));
            // Positional max_steps and dry_run may follow, as the form
            // `goal, json, [max_steps], [dry_run]` documents; they override the config.
            let mut j = 2usize;
            if let Some(Value::Int(n)) = args.get(j) {
                cfg.insert("max_steps".into(), Value::Int(*n));
                j += 1;
            }
            if let Some(Value::Bool(b)) = args.get(j) {
                cfg.insert("dry_run".into(), Value::Bool(*b));
                j += 1;
            }
            if let Some(extra) = args.get(j) {
                return Err(surplus_arg(builtin, extra));
            }
            return agent_config(builtin, cfg, default_steps);
        }
    }

    let goal =
        validate_ai_prompt(&goal_raw).context(format!("{builtin}: goal validation failed"))?;
    let mut i = 1usize;
    let mut tools: Vec<String> = Vec::new();
    while let Some(Value::Str(name)) = args.get(i) {
        tools.push(name.clone());
        i += 1;
    }
    if tools.is_empty() {
        if let Some(Value::Array(items)) = args.get(i) {
            tools = agent_strings(builtin, items, "tools array must contain strings")?;
            i += 1;
        }
    }
    let mut max_steps = default_steps;
    if let Some(Value::Int(n)) = args.get(i) {
        max_steps = steps_arg(builtin, *n)?;
        i += 1;
    }
    let mut dry_run = false;
    if let Some(Value::Bool(b)) = args.get(i) {
        dry_run = *b;
        i += 1;
    }
    if let Some(extra) = args.get(i) {
        return Err(surplus_arg(builtin, extra));
    }
    check_tools(builtin, &tools)?;
    Ok(AgentCall {
        goal,
        tools,
        max_steps,
        dry_run,
    })
}

/// Read a config record: `goal` is required; `tools`, `max_steps` and `dry_run`
/// are optional and each is type-checked rather than defaulted when wrong.
fn agent_config(
    builtin: &str,
    cfg: BTreeMap<String, Value>,
    default_steps: usize,
) -> Result<AgentCall> {
    if let Some(key) = cfg
        .keys()
        .find(|k| !AGENT_CONFIG_KEYS.contains(&k.as_str()))
    {
        return Err(crate::safety::arg_err(format!(
            "{builtin} config has no key '{key}'; its keys are goal, tools, max_steps, dry_run"
        )));
    }
    let goal_raw = match cfg.get("goal") {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(format!(
                "{builtin} config requires {{goal: String}}"
            )))
        }
    };
    let goal =
        validate_ai_prompt(&goal_raw).context(format!("{builtin}: goal validation failed"))?;
    let tools = match cfg.get("tools") {
        None => Vec::new(),
        Some(Value::Array(items)) => {
            agent_strings(builtin, items, "config tools must be an array of strings")?
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "tools: Array of String",
                other.type_name(),
            ))
        }
    };
    let max_steps = match cfg.get("max_steps") {
        None => default_steps,
        Some(Value::Int(n)) => steps_arg(builtin, *n)?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "max_steps: Int",
                other.type_name(),
            ))
        }
    };
    let dry_run = match cfg.get("dry_run") {
        None => false,
        Some(Value::Bool(b)) => *b,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "dry_run: Bool",
                other.type_name(),
            ))
        }
    };
    check_tools(builtin, &tools)?;
    Ok(AgentCall {
        goal,
        tools,
        max_steps,
        dry_run,
    })
}

fn agent_strings(builtin: &str, items: &[Value], message: &str) -> Result<Vec<String>> {
    items
        .iter()
        .map(|v| match v {
            Value::Str(s) => Ok(s.clone()),
            _ => Err(crate::safety::arg_err(format!("{builtin}: {message}"))),
        })
        .collect()
}

fn steps_arg(builtin: &str, n: i64) -> Result<usize> {
    if (1..=MAX_AGENT_STEPS).contains(&n) {
        Ok(n as usize)
    } else {
        Err(crate::safety::bad_arg(
            builtin,
            &format!("max_steps: Int in 1..={MAX_AGENT_STEPS}"),
            &n.to_string(),
        ))
    }
}

/// Refuse a tool name no builtin answers to. The agent would otherwise learn
/// this only when the model asked for that tool, after the model had run.
fn check_tools(builtin: &str, tools: &[String]) -> Result<()> {
    for tool in tools {
        if !crate::builtins::is_dispatched(tool) {
            return Err(crate::safety::not_found(builtin, "tool", tool));
        }
    }
    Ok(())
}

fn surplus_arg(builtin: &str, extra: &Value) -> anyhow::Error {
    crate::safety::arg_err(format!(
        "{builtin}: unexpected {} argument; the form is goal, [tools...], [max_steps], [dry_run]",
        extra.type_name()
    ))
}

/// Refuse a piped value for a builtin that takes none, so it is never dropped
/// without a word.
fn refuse_pipeline_input(builtin: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::arg_err(format!(
            "{builtin} takes no pipeline input"
        )));
    }
    Ok(())
}

fn bi_agent(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    let call = parse_agent_call("agent", &args, input.as_ref(), 8)?;
    // SECURITY: Rate limit agent calls (CVSS 7.8). This runs after the
    // arguments are read, so a refused call does not spend the budget.
    check_rate_limit("bi_agent", 10, Duration::from_secs(60))
        .context("Agent rate limit exceeded")?;
    let tools: Vec<&str> = call.tools.iter().map(String::as_str).collect();
    let out = crate::ai::agents::run_sync(&call.goal, &tools, call.max_steps, call.dry_run, env)?;
    Ok(Value::Str(out))
}

fn bi_swarm(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    let call = parse_agent_call("swarm", &args, input.as_ref(), 12)?;
    let tools: Vec<&str> = call.tools.iter().map(String::as_str).collect();
    let out =
        crate::ai::agents::swarm::run_sync(&call.goal, &tools, call.max_steps, call.dry_run, env)?;
    Ok(Value::Str(out))
}

// --------------- File system commands ---------------

fn bi_ls(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path_str = if args.is_empty() {
        ".".to_string()
    } else {
        match &args[0] {
            Value::Str(s) => s.clone(),
            other => {
                return Err(crate::safety::bad_arg(
                    "ls",
                    "path: String",
                    other.type_name(),
                ))
            }
        }
    };

    // The probes below stat the string, which opens SMB for a UNC one.
    crate::security::check_share_egress("ls", &path_str)?;

    // `ls("src/*.rs")` lists the matches themselves, as `ls src/*.rs` does.
    let paths: Vec<std::path::PathBuf> =
        if crate::posix::has_glob_meta(&path_str) && !std::path::Path::new(&path_str).exists() {
            expand_glob_for("ls", &path_str)?
                .into_iter()
                .map(std::path::PathBuf::from)
                .collect()
        } else {
            crate::security::check_read_jail("ls", &path_str)?;
            if !std::path::Path::new(&path_str).exists() {
                return Err(crate::safety::not_found("ls", "directory", &path_str));
            }
            // SECURITY: Validate path to prevent traversal attacks (CVSS 8.2)
            let validated_path = validate_read_path(&path_str)?;
            // A file lists as itself, one entry, as `ls file` does. Reading it
            // as a directory failed with an OS error.
            if !validated_path.is_dir() {
                vec![validated_path]
            } else {
                fs::read_dir(&validated_path)
                    .map_err(|e| crate::safety::fs_error("ls", &validated_path, &e))?
                    .map(|e| e.map(|e| e.path()))
                    .collect::<std::io::Result<Vec<_>>>()
                    .map_err(|e| crate::safety::fs_error("ls", &validated_path, &e))?
            }
        };
    let mut files = Vec::new();

    for path in paths {
        // A dangling symlink is listed as itself, as ls(1) lists it; it used to
        // fail the whole directory with E_NOT_FOUND.
        let metadata = fs::metadata(&path)
            .or_else(|e| match fs::symlink_metadata(&path) {
                Ok(link) if link.file_type().is_symlink() => Ok(link),
                _ => Err(e),
            })
            .map_err(|e| crate::safety::fs_error("ls", &path, &e))?;
        let name = path
            .file_name()
            .ok_or_else(|| crate::safety::arg_err("ls: invalid filename"))?
            .to_string_lossy()
            .to_string();

        // Extract file extension
        let ext = path
            .extension()
            .map(|e| format!(".{}", e.to_string_lossy()))
            .unwrap_or_default();

        let mut record = BTreeMap::new();
        record.insert("name".to_string(), Value::Str(name));
        // The walk is over the canonical directory, so its entries carry the
        // verbatim prefix; report the ordinary drive path.
        record.insert(
            "path".to_string(),
            Value::Str(
                crate::safety::strip_verbatim_prefix(&path)
                    .to_string_lossy()
                    .to_string(),
            ),
        );
        record.insert("ext".to_string(), Value::Str(ext));
        record.insert("is_dir".to_string(), Value::Bool(metadata.is_dir()));
        record.insert("size".to_string(), Value::Int(metadata.len() as i64));

        if let Ok(modified) = metadata.modified() {
            if let Ok(duration) = modified.duration_since(std::time::UNIX_EPOCH) {
                record.insert(
                    "modified".to_string(),
                    Value::Int(duration.as_secs() as i64),
                );
            }
        }

        files.push(Value::Record(record));
    }

    Ok(Value::Array(files))
}

fn bi_pwd() -> Result<Value> {
    let current_dir = std::env::current_dir()?;
    Ok(Value::Str(current_dir.to_string_lossy().to_string()))
}

fn bi_cat(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if let Some(input) = input {
        return Ok(input);
    }

    if args.is_empty() {
        return Err(crate::safety::arg_err("cat: no file specified"));
    }

    // The probes below stat the string, which opens SMB for a UNC one.
    for arg in &args {
        if let Value::Str(path) = arg {
            crate::security::check_share_egress("cat", path)?;
        }
    }

    let path_str = match &args[0] {
        Value::Str(s) => s,
        other => {
            return Err(crate::safety::bad_arg(
                "cat",
                "path: String",
                other.type_name(),
            ))
        }
    };

    Ok(Value::Str(read_named_files("cat", path_str)?))
}

/// The text with a leading UTF-8 byte-order mark removed. Windows PowerShell
/// writes one by default; it is not part of the text, so it is not read as
/// the first character. Only text readers call this, never a byte reader or
/// a writer, which keep the bytes they were given.
fn without_bom(text: String) -> String {
    match text.strip_prefix('\u{FEFF}') {
        Some(rest) => rest.to_string(),
        None => text,
    }
}

/// The text of the path a builtin was given. A glob reads every match, in
/// order, as `cat src/*.rs` does -- unless a file with that literal name
/// exists. Every path read goes through `validate_read_path`, so the workspace
/// jail applies to each match, not only to the pattern. `cat` and `grep` both
/// read their paths this way.
fn read_named_files(builtin: &str, path_str: &str) -> Result<String> {
    let mut all = String::new();
    for (_, text) in read_named_file_list(builtin, path_str)? {
        // A file that ends without a newline would run into the next one, so
        // `lines` would count the two as one line. Separate them.
        if !all.is_empty() && !all.ends_with('\n') {
            all.push('\n');
        }
        all.push_str(&text);
    }
    Ok(all)
}

/// Each file a path names, with its text, in order: a glob names every file it
/// matches, and any other path names itself. `read_named_files` joins these.
fn read_named_file_list(builtin: &str, path_str: &str) -> Result<Vec<(String, String)>> {
    if crate::posix::has_glob_meta(path_str) && !std::path::Path::new(path_str).exists() {
        let paths = expand_glob_for(builtin, path_str)?;
        let files: Vec<&String> = paths
            .iter()
            .filter(|p| std::path::Path::new(p).is_file())
            .collect();
        if files.is_empty() {
            return Err(crate::safety::not_found(builtin, "file matching", path_str));
        }
        let mut out = Vec::with_capacity(files.len());
        for p in files {
            out.push((p.clone(), read_named_file(builtin, p)?));
        }
        return Ok(out);
    }
    Ok(vec![(
        path_str.to_string(),
        read_named_file(builtin, path_str)?,
    )])
}

fn read_named_file(builtin: &str, path_str: &str) -> Result<String> {
    // The jail comes before the existence check, so a missing path outside the
    // workspace is E_OUTSIDE_WORKSPACE and not E_NOT_FOUND (an existence oracle).
    crate::security::check_read_jail(builtin, path_str)?;
    // A missing parent directory made validate_read_path fail with an uncoded
    // "Failed to canonicalize parent directory".
    if !std::path::Path::new(path_str).exists() {
        return Err(crate::safety::not_found(builtin, "file", path_str));
    }
    // SECURITY: Validate path to prevent traversal attacks (CVSS 8.2)
    let validated_path = validate_read_path(path_str)?;

    // SECURITY FIX (MED-001): Check file size before reading
    let metadata = fs::metadata(&validated_path)
        .map_err(|e| crate::safety::fs_error(builtin, &validated_path, &e))?;
    check_file_size_limit(metadata.len()).context(format!("{builtin}: file too large"))?;

    let bytes = fs::read(&validated_path)
        .map_err(|e| crate::safety::fs_error(builtin, &validated_path, &e))?;
    decode_text(builtin, &validated_path, bytes).map(without_bom)
}

fn bi_read_text(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err("read_text: no file specified"));
    }

    let path_str = match &args[0] {
        Value::Str(s) => s,
        other => {
            return Err(crate::safety::bad_arg(
                "read_text",
                "path: String",
                other.type_name(),
            ))
        }
    };

    // SECURITY: Validate path to prevent traversal attacks
    let validated_path = validate_read_path(path_str)?;

    // SECURITY FIX (MED-001): Check file size before reading
    let metadata = fs::metadata(&validated_path)
        .map_err(|e| crate::safety::fs_error("read_text", &validated_path, &e))?;
    check_file_size_limit(metadata.len()).context("read_text: file too large")?;

    let bytes = fs::read(&validated_path)
        .map_err(|e| crate::safety::fs_error("read_text", &validated_path, &e))?;
    let content = decode_text("read_text", &validated_path, bytes).map(without_bom)?;

    Ok(Value::Str(content))
}

fn bi_head(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // An Array as the first argument, `head([1, 2, 3], 2)`: the same as piping
    // it in, which is `take(n)`.
    if input.is_none() && matches!(args.first(), Some(Value::Array(_))) {
        let count = match args.get(1) {
            None => 10,
            Some(value) => line_count("head", value)?,
        };
        return bi_take(vec![Value::Int(count as i64)], args.into_iter().next());
    }
    // An Array piped in: its first n elements, the same as `take(n)`.
    if matches!(input, Some(Value::Array(_))) {
        let count = match args.first() {
            None => 10,
            Some(value) => line_count("head", value)?,
        };
        return bi_take(vec![Value::Int(count as i64)], input);
    }
    let (count, content) = match input {
        Some(Value::Str(content)) => (args.first().map(|v| line_count("head", v)).transpose()?.unwrap_or(10), content),
        Some(_) => return Err(crate::safety::arg_err("head piped input must be String")),
        None => match args.as_slice() {
            [Value::Str(path)] => (10, line_read("head", path)?),
            [Value::Str(path), count] => (line_count("head", count)?, line_read("head", path)?),
            [count, Value::Str(path)] => (line_count("head", count)?, line_read("head", path)?),
            _ => return Err(crate::safety::arg_err("head requires a file path and optional count, or count then path, or a piped String")),
        },
    };
    Ok(Value::Str(
        content.lines().take(count).collect::<Vec<_>>().join("\n"),
    ))
}

fn line_count(builtin: &str, value: &Value) -> Result<usize> {
    let Value::Int(n) = value else {
        return Err(crate::safety::arg_err(format!(
            "{builtin} count must be a nonnegative Int"
        )));
    };
    usize::try_from(*n).map_err(|_| {
        crate::safety::arg_err(format!(
            "{builtin} count must be a nonnegative representable Int"
        ))
    })
}

/// Read a whole text file a caller named, up to the resource limit
/// (`max_file_size_mb`, 100 MiB by default). A larger file is
/// E_BUDGET_EXCEEDED, not an allocation the size of the file. The limit is
/// enforced on the bytes read, not only on the size the metadata reports, so a
/// file that grows, or a device or pipe that reports 0, is held to it too.
/// Path validation stays with the caller.
fn read_text_capped(builtin: &str, path: impl AsRef<std::path::Path>) -> Result<String> {
    read_text_capped_at(
        builtin,
        path.as_ref(),
        crate::security::max_file_size_bytes()?,
    )
}

fn read_text_capped_at(builtin: &str, path: &std::path::Path, max: u64) -> Result<String> {
    decode_text(builtin, path, read_bytes_capped_at(builtin, path, max)?)
}

/// The text of the bytes a text reader read from `path`. Bytes that are not
/// UTF-8 are a bad value in the file, not an I/O failure, so the error is
/// E_BAD_VALUE and gives the offset of the first byte that is not UTF-8.
fn decode_text(builtin: &str, path: &std::path::Path, bytes: Vec<u8>) -> Result<String> {
    String::from_utf8(bytes).map_err(|e| {
        let offset = e.utf8_error().valid_up_to();
        crate::safety::value_not_representable(
            builtin,
            format!(
                "{builtin}: `{}` is not UTF-8 text: the first byte that is not UTF-8 is at byte offset {offset}",
                crate::safety::strip_verbatim_prefix(path).display()
            ),
            "the file is not UTF-8 text; convert it to UTF-8 first",
        )
    })
}

/// Read a whole binary file a caller named, up to the resource limit, as
/// `read_text_capped` does for text. Path validation stays with the caller.
fn read_bytes_capped(builtin: &str, path: impl AsRef<std::path::Path>) -> Result<Vec<u8>> {
    read_bytes_capped_at(
        builtin,
        path.as_ref(),
        crate::security::max_file_size_bytes()?,
    )
}

fn read_bytes_capped_at(builtin: &str, path: &std::path::Path, max: u64) -> Result<Vec<u8>> {
    use std::io::Read;
    crate::security::check_read_jail(builtin, &path.to_string_lossy())?;
    let over = || {
        crate::safety::budget_exceeded(
            builtin,
            format!(
                "{builtin}: `{}` is larger than {} MiB",
                path.display(),
                max / (1024 * 1024)
            ),
            "read a part of the file (head, tail, line_read) or raise max_file_size_mb",
        )
    };
    let file = fs::File::open(path).map_err(|e| crate::safety::fs_error(builtin, path, &e))?;
    if file.metadata().is_ok_and(|m| m.len() > max) {
        return Err(over());
    }
    let mut bytes = Vec::new();
    file.take(max.saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(|e| crate::safety::fs_error(builtin, path, &e))?;
    if bytes.len() as u64 > max {
        return Err(over());
    }
    Ok(bytes)
}

/// Whether a capped read failed because the path does not exist. The capped
/// readers report I/O errors as `SafetyError`s, so the `io::ErrorKind` is gone.
fn capped_read_not_found(e: &anyhow::Error) -> bool {
    e.downcast_ref::<crate::safety::SafetyError>()
        .is_some_and(|s| s.code == crate::safety::ErrorCode::NotFound)
}

fn line_read(builtin: &str, path: &str) -> Result<String> {
    use std::io::Read;
    const MAX_BYTES: u64 = 64 * 1024 * 1024;
    // The jail names this builtin, as every builtin's refusal does; a name-less
    // refusal read ": `path` is outside the workspace".
    crate::security::check_read_jail(builtin, path)?;
    let path = crate::security::validate_safe_path(path)?;
    let metadata = fs::metadata(&path).map_err(|e| crate::safety::fs_error(builtin, &path, &e))?;
    if metadata.len() > MAX_BYTES {
        return Err(crate::safety::budget_exceeded(
            builtin,
            "file exceeds 64 MiB".into(),
            "use a smaller file",
        ));
    }
    if !metadata.is_file() {
        return Err(crate::safety::arg_err(format!(
            "{builtin} requires a regular UTF-8 file"
        )));
    }
    let file = fs::File::open(&path).map_err(|e| crate::safety::fs_error(builtin, &path, &e))?;
    let mut content = String::new();
    file.take(MAX_BYTES + 1)
        .read_to_string(&mut content)
        .map_err(|e| crate::safety::fs_error(builtin, &path, &e))?;
    if content.len() as u64 > MAX_BYTES {
        return Err(crate::safety::budget_exceeded(
            builtin,
            "file exceeds 64 MiB".into(),
            "use a smaller file",
        ));
    }
    Ok(content)
}

fn bi_tail(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // An Array as the first argument, `tail([1, 2, 3], 2)`: as piping it in.
    if input.is_none() && matches!(args.first(), Some(Value::Array(_))) {
        let count = match args.get(1) {
            None => 10,
            Some(value) => line_count("tail", value)?,
        };
        return bi_last(vec![Value::Int(count as i64)], args.into_iter().next());
    }
    // An Array piped in: its last n elements, the same as `last(n)`.
    if matches!(input, Some(Value::Array(_))) {
        let count = match args.first() {
            None => 10,
            Some(value) => line_count("tail", value)?,
        };
        return bi_last(vec![Value::Int(count as i64)], input);
    }
    let (count, content) = if let Some(value) = input {
        let Value::Str(content) = value else {
            return Err(crate::safety::arg_err("tail piped input must be String"));
        };
        let count = match args.first() {
            None => 10,
            Some(value) => line_count("tail", value)?,
        };
        (count, content)
    } else {
        match args.as_slice() {
            [Value::Str(path)] => (10,line_read("tail", path)?),
            [Value::Str(path),count] => (line_count("tail", count)?,line_read("tail", path)?),
            [count,Value::Str(path)] => (line_count("tail", count)?,line_read("tail", path)?),
            _=>return Err(crate::safety::arg_err("tail requires a file path and optional count, or count then path, or a piped String")),
        }
    };
    let mut lines: Vec<_> = content.lines().rev().take(count).collect();
    lines.reverse();
    Ok(Value::Str(lines.join("\n")))
}

/// The most entries one directory walk may return. A walk over `/` or `C:\`
/// could otherwise build an array of every file on the disk before anyone saw
/// it. Past this the walk is refused with E_BUDGET_EXCEEDED, not cut short: a
/// shorter listing presented as the whole is the silent wrong answer.
pub(crate) const WALK_MAX_ENTRIES: usize = 1_000_000;

/// The refusal for a walk that would return more than `max` entries.
fn walk_over(builtin: &str, max: usize) -> anyhow::Error {
    crate::safety::budget_exceeded(
        builtin,
        format!("more than {max} entries; the listing would be partial, so nothing was returned"),
        "narrow the root, or filter with a pattern or depth",
    )
}

/// Refuses when a walk that already holds `len` entries cannot take one more
/// without exceeding `max`.
fn check_walk_room(builtin: &str, len: usize, max: usize) -> Result<()> {
    if len >= max {
        return Err(walk_over(builtin, max));
    }
    Ok(())
}

/// Adds `v` to a walk's output, or refuses once the output is at the cap.
fn push_capped(builtin: &str, out: &mut Vec<Value>, v: Value, max: usize) -> Result<()> {
    check_walk_room(builtin, out.len(), max)?;
    out.push(v);
    Ok(())
}

fn bi_find(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let (path_str, pattern) = if args.len() >= 2 {
        match (&args[0], &args[1]) {
            (Value::Str(p), Value::Str(pat)) => (p.clone(), Some(pat.clone())),
            _ => {
                return Err(crate::safety::arg_err(
                    "find: path and pattern must be strings",
                ))
            }
        }
    } else if args.len() == 1 {
        match &args[0] {
            Value::Str(p) => (p.clone(), None),
            other => {
                return Err(crate::safety::bad_arg(
                    "find",
                    "path: String",
                    other.type_name(),
                ))
            }
        }
    } else {
        (".".to_string(), None)
    };

    // SECURITY: Validate path to prevent traversal attacks (CVSS 8.2)
    let validated_path = validate_read_path(&path_str)?;

    let mut results = Vec::new();

    // A walk error used to be dropped, so an unreadable directory vanished
    // from the listing and the rest was returned as the whole answer.
    for entry in WalkDir::new(&validated_path) {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) => {
                return Err(match e.io_error() {
                    Some(io) => crate::safety::fs_error(
                        "find",
                        e.path().unwrap_or(validated_path.as_path()),
                        io,
                    ),
                    None => crate::safety::bad_state_with_hint(
                        "find",
                        &e.to_string(),
                        "a tree without symbolic-link loops",
                    ),
                });
            }
        };
        // Reported without the verbatim prefix `canonicalize` put on the root.
        let path_str = crate::safety::strip_verbatim_prefix(entry.path())
            .to_string_lossy()
            .to_string();

        if let Some(ref pattern) = pattern {
            // Simple glob matching: support * for any characters
            let filename = entry.file_name().to_string_lossy();
            if shell_glob(
                &pattern.chars().collect::<Vec<_>>(),
                &filename.chars().collect::<Vec<_>>(),
            ) {
                push_capped("find", &mut results, Value::Str(path_str), WALK_MAX_ENTRIES)?;
            }
        } else {
            push_capped("find", &mut results, Value::Str(path_str), WALK_MAX_ENTRIES)?;
        }
    }

    Ok(Value::Array(results))
}

// `find`'s patterns go through `shell_glob`. This used a matcher that knew
// four forms -- `*`, `*.ext`, `prefix*` and an exact name -- and treated
// anything else as an exact name, so `find("a*b.rs")`, `find("?.rs")` and
// `find("[ab].rs")` silently found nothing. `shell_glob` is a strict superset
// of those four, so no pattern that worked before behaves differently.

fn bi_sort(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let reverse = args
        .iter()
        .any(|arg| matches!(arg, Value::Str(s) if s == "-r" || s == "--reverse"));

    // A direct call's subject is its first argument, so `sort([2, 1])` sorts
    // exactly what `[2, 1] | sort` sorts.
    let subject = input.or_else(|| args.first().cloned());
    let array = if let Some(input) = subject {
        match input {
            Value::Array(arr) => arr,
            Value::Str(s) => {
                let lines: Vec<Value> =
                    s.lines().map(|line| Value::Str(line.to_string())).collect();
                lines
            }
            _ => {
                return Err(crate::safety::arg_err(
                    "sort: input must be an array or string",
                ))
            }
        }
    } else {
        return Err(crate::safety::bad_arg(
            "sort",
            "a piped Array or String",
            "a direct call with no subject",
        ));
    };

    // A Record, Bool, Array or Null has no order here, so a list of them has no
    // sorted form: the comparator used to call every such pair equal, and the
    // list came back in input order with exit 0. A list of records is sorted by
    // one of its fields.
    if let Some(unordered) = array.iter().find(|v| {
        matches!(
            v,
            Value::Record(_) | Value::Bool(_) | Value::Array(_) | Value::Null
        )
    }) {
        return Err(crate::safety::bad_arg_with_hint(
            "sort",
            "numbers or strings",
            unordered.type_name(),
            "sort a list of records by a field with sort_by(fn(r) => r.field); a list of \
             Bools, Arrays or nulls has no order to sort by",
        ));
    }

    // Numbers order against numbers and strings against strings. Nothing orders
    // a number against a string, so a mixed array has no sorted form. The
    // comparator used to call such a pair equal, and the array came back in
    // input order with exit 0.
    let mut kinds: Vec<&str> = Vec::new();
    for v in &array {
        let kind = match v {
            Value::Int(_) | Value::Float(_) => "number",
            Value::Str(_) => "String",
            other => other.type_name(),
        };
        if !kinds.contains(&kind) {
            kinds.push(kind);
        }
    }
    if kinds.len() > 1 {
        return Err(crate::safety::bad_arg(
            "sort",
            "elements of one type (all numbers or all strings)",
            &format!("a mix of {}", kinds.join(" and ")),
        ));
    }

    let mut sorted = array;
    sorted.sort_by(|a, b| {
        let cmp = match (a, b) {
            (Value::Str(s1), Value::Str(s2)) => s1.cmp(s2),
            (Value::Int(i1), Value::Int(i2)) => i1.cmp(i2),
            (Value::Float(f1), Value::Float(f2)) => {
                f1.partial_cmp(f2).unwrap_or(std::cmp::Ordering::Equal)
            }
            // An Int and a Float are both numbers, so they order by value.
            (Value::Int(i), Value::Float(f)) => (*i as f64)
                .partial_cmp(f)
                .unwrap_or(std::cmp::Ordering::Equal),
            (Value::Float(f), Value::Int(i)) => f
                .partial_cmp(&(*i as f64))
                .unwrap_or(std::cmp::Ordering::Equal),
            _ => std::cmp::Ordering::Equal,
        };
        if reverse {
            cmp.reverse()
        } else {
            cmp
        }
    });

    Ok(Value::Array(sorted))
}

/// chunk(array, size) - Split an Array into consecutive pieces of `size`
/// elements. The last piece is shorter when the length is not a multiple of
/// `size`; an empty Array gives no pieces. `size` must be an Int of at least 1.
///
/// Example:
///   [1, 2, 3] | chunk(2)        # [[1, 2], [3]]
///   chunk([1, 2, 3, 4], 2)      # [[1, 2], [3, 4]]
fn bi_chunk(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Piped, the subject is the input and the size is the first argument;
    // called directly, the array is the first argument and the size the second.
    let (subject, size_arg) = match input {
        Some(v) => (v, args.first()),
        None => match args.first() {
            Some(v) => (v.clone(), args.get(1)),
            None => {
                return Err(crate::safety::bad_arg(
                    "chunk",
                    "an Array as the subject",
                    "nothing",
                ))
            }
        },
    };
    let items = match subject {
        Value::Array(a) => a,
        other => {
            return Err(crate::safety::bad_arg(
                "chunk",
                "an Array as the subject",
                other.type_name(),
            ))
        }
    };
    let size = match size_arg {
        Some(Value::Int(n)) if *n >= 1 => *n as usize,
        Some(Value::Int(n)) => {
            return Err(crate::safety::bad_arg(
                "chunk",
                "a size of at least 1",
                &n.to_string(),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "chunk",
                "a size: an Int of at least 1",
                other.type_name(),
            ))
        }
        None => {
            return Err(crate::safety::bad_arg(
                "chunk",
                "a size: an Int of at least 1",
                "nothing",
            ))
        }
    };
    Ok(Value::Array(
        items
            .chunks(size)
            .map(|c| Value::Array(c.to_vec()))
            .collect(),
    ))
}

fn bi_uniq(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let _count = args
        .iter()
        .any(|arg| matches!(arg, Value::Str(s) if s == "-c" || s == "--count"));

    // The subject is the piped value, or the first argument of a direct call.
    // A String is split into lines (`s.lines()`), as the piped form always did.
    let subject = match (input, args.first()) {
        (Some(input), _) => input,
        (None, Some(first)) => first.clone(),
        (None, None) => {
            return Err(crate::safety::bad_arg(
                "uniq",
                "an Array or a String",
                "a direct call with no subject",
            ))
        }
    };
    let array = match subject {
        Value::Array(arr) => arr,
        Value::Str(s) => s.lines().map(|line| Value::Str(line.to_string())).collect(),
        other => {
            return Err(crate::safety::bad_arg(
                "uniq",
                "an Array or a String",
                other.type_name(),
            ))
        }
    };

    let mut unique = Vec::new();
    let mut last: Option<&Value> = None;

    for item in &array {
        if last != Some(item) {
            unique.push(item.clone());
            last = Some(item);
        }
    }

    Ok(Value::Array(unique))
}

fn bi_wc(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let lines_only = args
        .iter()
        .any(|arg| matches!(arg, Value::Str(s) if s == "-l" || s == "--lines"));
    let words_only = args
        .iter()
        .any(|arg| matches!(arg, Value::Str(s) if s == "-w" || s == "--words"));
    let chars_only = args
        .iter()
        .any(|arg| matches!(arg, Value::Str(s) if s == "-c" || s == "--chars"));

    let content_came_from_pipe = input.is_some();
    let content = if let Some(input) = input {
        match input {
            Value::Str(s) => s,
            other => {
                return Err(crate::safety::bad_arg(
                    "wc",
                    "input: String",
                    other.type_name(),
                ))
            }
        }
    } else if !args.is_empty() {
        let path = match &args[0] {
            Value::Str(s) if !s.starts_with('-') => s,
            other => {
                return Err(crate::safety::bad_arg(
                    "wc",
                    "a piped String, or a file path as the first argument",
                    other.type_name(),
                ))
            }
        };
        read_text_capped("wc", path)?
    } else {
        return Err(crate::safety::bad_arg(
            "wc",
            "a piped String",
            "a direct call with no subject",
        ));
    };
    // An unknown flag ("-x", "--bogus") was ignored and every count returned.
    let flags = if content_came_from_pipe {
        &args[..]
    } else {
        &args[1..]
    };
    for f in flags {
        if !matches!(f, Value::Str(s) if matches!(s.as_str(), "-l" | "--lines" | "-w" | "--words" | "-c" | "--chars"))
        {
            return Err(crate::safety::bad_arg(
                "wc",
                "a flag -l, -w or -c",
                &f.to_display_string(),
            ));
        }
    }

    let line_count = content.lines().count();
    let word_count = content.split_whitespace().count();
    let char_count = content.chars().count();

    let mut result = BTreeMap::new();

    if lines_only {
        result.insert("lines".to_string(), Value::Int(line_count as i64));
    } else if words_only {
        result.insert("words".to_string(), Value::Int(word_count as i64));
    } else if chars_only {
        result.insert("chars".to_string(), Value::Int(char_count as i64));
    } else {
        result.insert("lines".to_string(), Value::Int(line_count as i64));
        result.insert("words".to_string(), Value::Int(word_count as i64));
        result.insert("chars".to_string(), Value::Int(char_count as i64));
    }

    Ok(Value::Record(result))
}

fn bi_grep(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err("grep: pattern required"));
    }

    let pattern = match &args[0] {
        Value::Str(s) => s,
        other => {
            return Err(crate::safety::bad_arg(
                "grep",
                "pattern: String",
                other.type_name(),
            ))
        }
    };

    let case_insensitive = args
        .iter()
        .any(|arg| matches!(arg, Value::Str(s) if s == "-i" || s == "--ignore-case"));
    let invert = args
        .iter()
        .any(|arg| matches!(arg, Value::Str(s) if s == "-v" || s == "--invert-match"));

    // The options Record, when there is one, is read before the source is.
    let line_numbers = grep_line_numbers(&args)?;

    // Each source is its file's name (None for piped text) and its text. A
    // glob searches each file on its own, so a match can name the file.
    let sources: Vec<(Option<String>, String)> = if let Some(input) = input {
        let content = match input {
            Value::Str(s) => s,
            Value::Array(arr) => {
                let lines: Vec<String> = arr
                    .iter()
                    .filter_map(|v| {
                        if let Value::Str(s) = v {
                            Some(s.clone())
                        } else {
                            None
                        }
                    })
                    .collect();
                lines.join("\n")
            }
            _ => {
                return Err(crate::safety::arg_err(
                    "grep: input must be a string or array",
                ))
            }
        };
        vec![(None, content)]
    } else if args.len() > 1 {
        let path = match &args[1] {
            Value::Str(s) if !s.starts_with('-') => s,
            _ => {
                return Err(crate::safety::bad_arg(
                    "grep",
                    "a piped String, or a file path as the second argument",
                    "nothing",
                ))
            }
        };
        grep_source_files(path)?
            .into_iter()
            .map(|(file, text)| (Some(file), text))
            .collect()
    } else {
        return Err(crate::safety::bad_arg(
            "grep",
            "a piped String, or a file path as the second argument",
            "a direct call with no subject",
        ));
    };

    // The declaration always said "text or regex"; the body only ever did a
    // substring search, so `grep("^version", "Cargo.toml")` answered [] --
    // an empty result for a pattern every grep user writes. The pattern is
    // now what grep takes: a POSIX basic regular expression.
    // A back-reference (\1 to \9) is the one BRE form the translation refuses.
    // Any other failure is the regex compiler's, and its reason is what to fix.
    let translated = crate::posix::bre_to_regex(pattern).ok_or_else(|| {
        crate::safety::bad_arg_in(
            "grep",
            format!("grep: {pattern:?} has a back-reference, which grep does not support"),
            "remove the \\1 to \\9 back-reference; to match an extended regex, use regex_match",
        )
    })?;
    let re = regex::RegexBuilder::new(&translated)
        .case_insensitive(case_insensitive)
        .build()
        .map_err(|e| {
            // The compiler's last "error:" line is the reason; the lines above it
            // only quote the pattern with a caret.
            let text = e.to_string();
            let reason = text
                .lines()
                .rev()
                .find_map(|line| line.strip_prefix("error: "))
                .unwrap_or(text.as_str())
                .to_string();
            crate::safety::bad_arg_in(
                "grep",
                format!("grep: {pattern:?} is not a valid regular expression: {reason}"),
                "grep takes a basic regular expression: + ? | ( ) { } are literal unless backslashed, so write \\( and \\| for groups and alternatives; for an extended regex, use regex_match",
            )
        })?;
    let mut matching: Vec<Value> = Vec::new();
    for (file, text) in &sources {
        for (index, line) in text.lines().enumerate() {
            if re.is_match(line) == invert {
                continue;
            }
            matching.push(if line_numbers {
                Value::Record(BTreeMap::from([
                    (
                        "file".to_string(),
                        file.clone().map_or(Value::Null, Value::Str),
                    ),
                    ("line".to_string(), Value::Int(index as i64 + 1)),
                    ("text".to_string(), Value::Str(line.to_string())),
                ]))
            } else {
                Value::Str(line.to_string())
            });
        }
    }

    Ok(Value::Array(matching))
}

/// The options Record of `grep`, when one is given after the pattern. Its only
/// key is `line_numbers`, a Bool; any other key or value is a bad argument.
fn grep_line_numbers(args: &[Value]) -> Result<bool> {
    let mut line_numbers = false;
    for arg in args.iter().skip(1) {
        if let Value::Record(options) = arg {
            for (key, value) in options {
                match (key.as_str(), value) {
                    ("line_numbers", Value::Bool(on)) => line_numbers = *on,
                    ("line_numbers", other) => {
                        return Err(crate::safety::bad_arg_in(
                            "grep",
                            format!(
                                "grep: line_numbers must be a Bool, got {}",
                                other.type_name()
                            ),
                            "pass {line_numbers: true} or {line_numbers: false}",
                        ))
                    }
                    _ => {
                        return Err(crate::safety::bad_arg_in(
                            "grep",
                            format!("grep: unknown option {key}; grep takes line_numbers"),
                            "the options Record takes one key: {line_numbers: true}",
                        ))
                    }
                }
            }
        }
    }
    Ok(line_numbers)
}

/// The files `grep(pattern, path)` searches, each with its text. The path is
/// read as `cat` reads it, so a glob searches every matching file in order and
/// `grep("fn ", "src/*.rs")` answers what `cat("src/*.rs") | grep("fn ")`
/// does. A directory is not text. Reading it gave E_OS_DENIED with a
/// permissions hint, which was the wrong cause, so it is refused as a bad
/// argument instead.
fn grep_source_files(path: &str) -> Result<Vec<(String, String)>> {
    crate::security::check_share_egress("grep", path)?;
    let named = std::path::Path::new(path);
    if named.exists() {
        // The jail is checked before the kind, so a directory outside the
        // workspace is refused as outside it, not described.
        validate_read_path(path)?;
        if named.is_dir() {
            return Err(crate::safety::bad_value(
                format!("grep: `{path}` is a directory, not a file"),
                "pass a file, or a glob that names the files to search, such as 'src/**/*.rs'",
            ));
        }
    }
    read_named_file_list("grep", path)
}

/// enumerate(items): each element with its position, as {index, value} records
/// counted from 0. The Array is piped in or passed as the argument.
fn bi_enumerate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let items = match input.or_else(|| args.into_iter().next()) {
        Some(Value::Array(items)) => items,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "enumerate",
                "an Array",
                other.type_name(),
            ))
        }
        None => return Err(subject_refusal("enumerate", "an Array")),
    };
    Ok(Value::Array(
        items
            .into_iter()
            .enumerate()
            .map(|(index, value)| {
                Value::Record(BTreeMap::from([
                    ("index".to_string(), Value::Int(index as i64)),
                    ("value".to_string(), value),
                ]))
            })
            .collect(),
    ))
}

// --------------- Formatting helpers ---------------

fn format_value_one_line(v: &Value) -> String {
    // keep this consistent with your pretty module; simplified for echo
    match v {
        Value::Null => "null".into(),
        Value::Bool(b) => b.to_string(),
        Value::Int(n) => n.to_string(),
        Value::Float(x) => crate::value::float_text(*x),
        Value::Str(s) => s.clone(),
        Value::Uri(s) => s.clone(),
        Value::Array(_) => crate::value::plain_text(v, false),
        Value::Record(_) => "{…}".into(),
        Value::Table(t) => format!("<Table rows={}>", t.rows.len()),
        Value::Lambda(_) => "<lambda>".into(),
        Value::AsyncLambda(_) => "<async lambda>".into(),
        Value::Future(_) => "<future>".into(),
        Value::Builtin(b) => format!("<builtin:{}>", b.name),
        Value::Error(msg) => format!("Error: {}", msg),
    }
}

// Helper function to convert Value to string representation
fn value_to_string(value: &Value) -> String {
    match value {
        Value::Str(s) => s.clone(),
        Value::Int(i) => i.to_string(),
        Value::Float(f) => crate::value::float_text(*f),
        Value::Bool(b) => b.to_string(),
        Value::Uri(s) => s.clone(),
        Value::Array(_) => crate::value::plain_text(value, false),
        Value::Record(_) => "{…}".into(),
        Value::Table(t) => format!("<Table rows={}>", t.rows.len()),
        Value::Lambda(_) => "<lambda>".into(),
        Value::AsyncLambda(_) => "<async lambda>".into(),
        Value::Future(_) => "<future>".into(),
        Value::Null => "<null>".into(),
        Value::Error(msg) => format!("Error: {}", msg),
        Value::Builtin(b) => format!("<builtin:{}>", b.name),
    }
}

// =============== PowerShell-style Parameter Binding ===============

/// PowerShell-style parameter binding result
// =============== PowerShell-style Cmdlets ===============

/// Get-Files: PowerShell-style file listing.
///
/// Grammar: at most one path, given positionally or as -Path / -p; -Recurse /
/// -r; and -Filter / -f with a substring of the name. The path comes from the
/// pipe or from the arguments, never both. Anything outside that grammar is
/// refused before the filesystem is read.
fn bi_get_files(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "Get-Files";
    let mut path_arg: Option<String> = None;
    let mut recurse = false;
    let mut filter: Option<String> = None;
    let mut i = 0;
    while i < args.len() {
        let Value::Str(token) = &args[i] else {
            return Err(crate::safety::arg_err(format!(
                "{NAME}: arguments must be strings, got {}",
                args[i].type_name()
            )));
        };
        match token.as_str() {
            "-Recurse" | "-r" => {
                recurse = true;
                i += 1;
            }
            "-Path" | "-p" | "-Filter" | "-f" => {
                let Some(Value::Str(value)) = args.get(i + 1) else {
                    return Err(crate::safety::arg_err(format!(
                        "{NAME}: {token} needs a string value"
                    )));
                };
                let slot = if matches!(token.as_str(), "-Path" | "-p") {
                    &mut path_arg
                } else {
                    &mut filter
                };
                if slot.is_some() {
                    return Err(crate::safety::arg_err(format!(
                        "{NAME}: {token} is given more than once"
                    )));
                }
                *slot = Some(value.clone());
                i += 2;
            }
            other if other.starts_with('-') => {
                return Err(crate::safety::arg_err(format!(
                    "{NAME}: unknown parameter {other}"
                )));
            }
            _ => {
                if path_arg.is_some() {
                    return Err(crate::safety::arg_err(format!(
                        "{NAME}: the path is given more than once"
                    )));
                }
                path_arg = Some(token.clone());
                i += 1;
            }
        }
    }

    let path = match (input, path_arg) {
        (None, None) => ".".to_string(),
        (None, Some(path)) => path,
        (Some(Value::Str(piped)), None) => piped,
        (Some(other), None) => {
            return Err(crate::safety::arg_err(format!(
                "{NAME}: pipeline input must be a path string, got {}",
                other.type_name()
            )))
        }
        (Some(_), Some(_)) => {
            return Err(crate::safety::arg_err(format!(
                "{NAME}: the path is both piped and given as an argument; give it once"
            )))
        }
    };

    let mut files = Vec::new();
    if recurse {
        for entry in WalkDir::new(&path).min_depth(1) {
            let entry = entry.map_err(|e| walk_failure(&path, e))?;
            let metadata = entry.metadata().map_err(|e| walk_failure(&path, e))?;
            let name = entry.file_name().to_string_lossy().to_string();
            if filter.as_ref().is_some_and(|p| !name.contains(p.as_str())) {
                continue;
            }
            let full = entry.path().to_string_lossy().to_string();
            push_capped(
                NAME,
                &mut files,
                file_record(name, full, &metadata),
                WALK_MAX_ENTRIES,
            )?;
        }
    } else {
        let listing =
            fs::read_dir(&path).map_err(|e| crate::safety::fs_error("get_files", &path, &e))?;
        for entry in listing {
            let entry = entry.map_err(|e| crate::safety::fs_error("get_files", &path, &e))?;
            let metadata = entry
                .metadata()
                .map_err(|e| crate::safety::fs_error("get_files", entry.path(), &e))?;
            let name = entry.file_name().to_string_lossy().to_string();
            if filter.as_ref().is_some_and(|p| !name.contains(p.as_str())) {
                continue;
            }
            let full = entry.path().to_string_lossy().to_string();
            push_capped(
                NAME,
                &mut files,
                file_record(name, full, &metadata),
                WALK_MAX_ENTRIES,
            )?;
        }
    }

    Ok(Value::Array(files))
}

fn file_record(name: String, full_name: String, metadata: &fs::Metadata) -> Value {
    let mut file_obj = BTreeMap::new();
    file_obj.insert("Name".to_string(), Value::Str(name));
    file_obj.insert("FullName".to_string(), Value::Str(full_name));
    file_obj.insert("IsDirectory".to_string(), Value::Bool(metadata.is_dir()));
    file_obj.insert("Length".to_string(), Value::Int(metadata.len() as i64));
    if let Ok(modified) = metadata.modified() {
        if let Ok(duration) = modified.duration_since(std::time::UNIX_EPOCH) {
            file_obj.insert(
                "LastWriteTime".to_string(),
                Value::Int(duration.as_secs() as i64),
            );
        }
    }
    Value::Record(file_obj)
}

/// A walk that cannot read an entry is a failure, not a shorter listing.
fn walk_failure(path: &str, e: walkdir::Error) -> anyhow::Error {
    match e.io_error() {
        Some(io) => crate::safety::fs_error("get_files", path, io),
        None => crate::safety::bad_state_with_hint(
            "Get-Files",
            &format!("{path}: {e}"),
            "a tree without symbolic-link loops",
        ),
    }
}

/// Get-Content: PowerShell-style file content reading, one element per line.
///
/// The path comes from the pipe or from a single argument, never both.
fn bi_get_content(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "Get-Content";
    if args.len() > 1 {
        return Err(crate::safety::arg_err(format!(
            "{NAME}: takes one path, got {} arguments",
            args.len()
        )));
    }
    let path = match (input, args.into_iter().next()) {
        (None, None) => return Err(crate::safety::arg_err(format!("{NAME}: no path provided"))),
        (None, Some(Value::Str(path))) | (Some(Value::Str(path)), None) => path,
        (None, Some(other)) => {
            return Err(crate::safety::arg_err(format!(
                "{NAME}: path must be a string, got {}",
                other.type_name()
            )))
        }
        (Some(other), None) => {
            return Err(crate::safety::arg_err(format!(
                "{NAME}: pipeline input must be a path string, got {}",
                other.type_name()
            )))
        }
        (Some(_), Some(_)) => {
            return Err(crate::safety::arg_err(format!(
                "{NAME}: the path is both piped and given as an argument; give it once"
            )))
        }
    };

    let content = read_text_capped("get_content", &path)?;

    // Return as array of lines (PowerShell style)
    let lines: Vec<Value> = content
        .lines()
        .map(|line| Value::Str(line.to_string()))
        .collect();

    Ok(Value::Array(lines))
}

/// Select-Object: PowerShell-style property selection.
///
/// Each argument names a property to keep on every piped record. A piped item
/// that is not a record is refused, not passed through unchanged.
fn bi_select_object(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "Select-Object";
    let input =
        input.ok_or_else(|| crate::safety::arg_err("Select-Object: requires pipeline input"))?;

    if args.is_empty() {
        return Ok(input);
    }
    if let Some(bad) = args.iter().find(|a| !matches!(a, Value::Str(_))) {
        return Err(crate::safety::arg_err(format!(
            "{NAME}: property names must be strings, got {}",
            bad.type_name()
        )));
    }

    match input {
        Value::Array(arr) => {
            let mut results = Vec::with_capacity(arr.len());
            for item in &arr {
                results.push(select_properties(item, &args)?);
            }
            Ok(Value::Array(results))
        }
        other => select_properties(&other, &args),
    }
}

fn select_properties(value: &Value, properties: &[Value]) -> Result<Value> {
    let Value::Record(record) = value else {
        return Err(crate::safety::bad_arg(
            "Select-Object",
            "a record to select properties from",
            value.type_name(),
        ));
    };
    let mut selected = BTreeMap::new();
    for prop in properties {
        if let Value::Str(prop_name) = prop {
            if let Some(val) = record.get(prop_name) {
                selected.insert(prop_name.clone(), val.clone());
            }
        }
    }
    Ok(Value::Record(selected))
}

/// Where-Object: PowerShell-style filtering.
///
/// Two forms: `where-object(fn(element) => Bool)`, or
/// `where-object(property, operator, value)`. Both need a piped array.
/// The cmdlet name in `Where-Object` messages, kept out of the format strings
/// because tests/no_raw_shell_interpolation.rs reads a cmdlet name inside a
/// `format!` as a PowerShell command being built.
const WHERE_OBJECT: &str = "Where-Object";

fn bi_where_object(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    const NAME: &str = "Where-Object";
    let input =
        input.ok_or_else(|| crate::safety::arg_err("Where-Object: requires pipeline input"))?;

    match args.first() {
        None => Err(crate::safety::arg_err(
            "Where-Object: requires filter condition",
        )),
        // Lambda filtering: the existing where logic.
        Some(Value::Lambda(_)) => {
            if args.len() != 1 {
                return Err(crate::safety::arg_err(format!(
                    "{NAME}: a lambda filter takes one argument, got {}",
                    args.len()
                )));
            }
            bi_where(args.clone(), Some(input), env)
        }
        // PowerShell-style property filtering: where Status -eq "Running"
        Some(Value::Str(property)) => {
            if args.len() != 3 {
                return Err(crate::safety::arg_err(format!(
                    "{NAME}: property filtering takes a property, an operator and a value, got {} arguments",
                    args.len()
                )));
            }
            filter_by_property(&input, property, &args[1], &args[2])
        }
        Some(other) => Err(crate::safety::arg_err(format!(
            "{NAME}: the filter must be a lambda or a property name, got {}",
            other.type_name()
        ))),
    }
}

fn filter_by_property(
    input: &Value,
    property: &str,
    operator: &Value,
    target: &Value,
) -> Result<Value> {
    let op_str = match operator {
        Value::Str(s) => s.as_str(),
        other => {
            return Err(crate::safety::arg_err(format!(
                "{WHERE_OBJECT}: operator must be a string, got {}",
                other.type_name()
            )))
        }
    };

    // Checked before any element is read: a bad operator is refused even when
    // the array is empty or no element carries the property.
    match op_str {
        "-eq" | "==" | "-ne" | "!=" => {}
        "-like" => {
            if !matches!(target, Value::Str(_)) {
                return Err(crate::safety::arg_err(format!(
                    "{WHERE_OBJECT}: -like needs a string value, got {}",
                    target.type_name()
                )));
            }
        }
        "-gt" | ">" | "-lt" | "<" | "-ge" | ">=" | "-le" | "<=" => {
            if !matches!(target, Value::Int(_) | Value::Float(_) | Value::Str(_)) {
                return Err(crate::safety::arg_err(format!(
                    "{WHERE_OBJECT}: {op_str} needs a number or a string value, got {}",
                    target.type_name()
                )));
            }
        }
        other => {
            return Err(crate::safety::bad_arg(
                "Where-Object",
                "an operator: -eq -ne -gt -lt -ge -le -like",
                other,
            ))
        }
    }

    let Value::Array(items) = input else {
        return Err(crate::safety::bad_arg(
            "Where-Object",
            "an array as the piped subject",
            input.type_name(),
        ));
    };

    let mut results = Vec::new();
    for item in items {
        let Value::Record(record) = item else {
            continue;
        };
        let Some(value) = record.get(property) else {
            continue;
        };
        let matches = match op_str {
            "-eq" | "==" => value == target,
            "-ne" | "!=" => value != target,
            "-gt" | ">" => compare_values(value, target, std::cmp::Ordering::Greater),
            "-lt" | "<" => compare_values(value, target, std::cmp::Ordering::Less),
            "-ge" | ">=" => {
                compare_values(value, target, std::cmp::Ordering::Greater) || value == target
            }
            "-le" | "<=" => {
                compare_values(value, target, std::cmp::Ordering::Less) || value == target
            }
            // "-like" is the only operator left, and its target is a string.
            _ => {
                matches!((value, target), (Value::Str(v), Value::Str(t)) if v.contains(t.as_str()))
            }
        };
        if matches {
            results.push(item.clone());
        }
    }
    Ok(Value::Array(results))
}

fn compare_values(a: &Value, b: &Value, expected: std::cmp::Ordering) -> bool {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => x.cmp(y) == expected,
        (Value::Float(x), Value::Float(y)) => x.partial_cmp(y) == Some(expected),
        (Value::Int(x), Value::Float(y)) => crate::value::cmp_int_float(*x, *y) == Some(expected),
        (Value::Float(x), Value::Int(y)) => {
            crate::value::cmp_int_float(*y, *x).map(|o| o.reverse()) == Some(expected)
        }
        (Value::Str(x), Value::Str(y)) => x.cmp(y) == expected,
        _ => false,
    }
}

/// ForEach-Object: PowerShell-style iteration
fn bi_foreach_object(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    // This is essentially the same as map, but with PowerShell naming
    bi_map(args, input, env)
}

/// Sort-Object: PowerShell-style sorting, by value or by one property.
fn bi_sort_object(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "Sort-Object";
    let input =
        input.ok_or_else(|| crate::safety::arg_err("Sort-Object: requires pipeline input"))?;

    if args.len() > 1 {
        return Err(crate::safety::arg_err(format!(
            "{NAME}: sorts by one property, got {} arguments",
            args.len()
        )));
    }
    let property = match args.first() {
        None => None,
        Some(Value::Str(property)) => Some(property.as_str()),
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{NAME}: property name must be a string, got {}",
                other.type_name()
            )))
        }
    };

    let mut arr = match input {
        Value::Array(arr) => arr,
        other => {
            return Err(crate::safety::bad_arg(
                NAME,
                "an array as the piped subject",
                other.type_name(),
            ))
        }
    };

    match property {
        None => arr.sort_by(compare_values_for_sort),
        Some(property) => {
            if let Some(other) = arr.iter().find(|v| !matches!(v, Value::Record(_))) {
                return Err(crate::safety::bad_arg(
                    NAME,
                    "records when sorting by a property",
                    other.type_name(),
                ));
            }
            arr.sort_by(|a, b| {
                compare_values_for_sort(
                    &get_property_value(a, property),
                    &get_property_value(b, property),
                )
            });
        }
    }
    Ok(Value::Array(arr))
}

fn get_property_value(value: &Value, property: &str) -> Value {
    match value {
        Value::Record(record) => record
            .get(property)
            .cloned()
            .unwrap_or(Value::Str("".to_string())),
        _ => value.clone(),
    }
}

fn compare_values_for_sort(a: &Value, b: &Value) -> std::cmp::Ordering {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => x.cmp(y),
        (Value::Float(x), Value::Float(y)) => x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal),
        (Value::Int(x), Value::Float(y)) => (*x as f64)
            .partial_cmp(y)
            .unwrap_or(std::cmp::Ordering::Equal),
        (Value::Float(x), Value::Int(y)) => x
            .partial_cmp(&(*y as f64))
            .unwrap_or(std::cmp::Ordering::Equal),
        (Value::Str(x), Value::Str(y)) => x.cmp(y),
        (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
        _ => std::cmp::Ordering::Equal,
    }
}

/// The subject and the remaining arguments of a builtin that takes a subject
/// first: the piped value when there is one, otherwise the first argument.
fn subject_and_rest(
    builtin: &str,
    args: Vec<Value>,
    input: Option<Value>,
) -> Result<(Value, Vec<Value>)> {
    match input {
        Some(v) => Ok((v, args)),
        None => {
            let mut args = args;
            if args.is_empty() {
                return Err(crate::safety::bad_arg(
                    builtin,
                    "a subject (piped or the first argument)",
                    "nothing",
                ));
            }
            let subject = args.remove(0);
            Ok((subject, args))
        }
    }
}

/// One step of a `get` path: a record key, or an Array index (negative counts
/// from the end). `None` when the step is missing.
fn get_step(current: &Value, step: &Value) -> Result<Option<Value>> {
    match (current, step) {
        (Value::Record(map), Value::Str(key)) => Ok(map.get(key).cloned()),
        (Value::Array(items), Value::Int(i)) => {
            let len = items.len() as i64;
            let pos = if *i < 0 { len + *i } else { *i };
            Ok(usize::try_from(pos)
                .ok()
                .and_then(|p| items.get(p))
                .cloned())
        }
        (Value::Array(items), Value::Str(key)) => Ok(key
            .parse::<i64>()
            .ok()
            .and_then(|i| {
                let len = items.len() as i64;
                usize::try_from(if i < 0 { len + i } else { i }).ok()
            })
            .and_then(|p| items.get(p))
            .cloned()),
        (_, Value::Str(_)) | (_, Value::Int(_)) => Ok(None),
        (_, other) => Err(crate::safety::bad_arg(
            "get",
            "a path of field names (String) and indices (Int)",
            other.type_name(),
        )),
    }
}

/// `get(record, path, default?)`: the value at `path`, or `default` (Null when
/// omitted) when any step is missing or Null, or the value found is Null.
///
/// `path` is a field name, a dotted path (`"u.n"`), or an Array of keys and
/// indices. A field whose name itself holds a dot is found first by its whole
/// name. The strict `r.field` access stays an error for a missing field; this
/// is the form for an optional one.
///
/// Example:
///   {u: {n: 5}} | get("u.n", 0)     # 5
///   get({a: 1}, "b", 0)             # 0
fn bi_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (subject, rest) = subject_and_rest("get", args, input)?;
    if rest.is_empty() || rest.len() > 2 {
        return Err(crate::safety::bad_arg_with_hint(
            "get",
            "a path and an optional default: get(record, path, default?)",
            &format!("{} arguments after the subject", rest.len()),
            r#"pass the path, then a default: r | get("u.n", 0)"#,
        ));
    }
    let default = rest.get(1).cloned().unwrap_or(Value::Null);
    let steps: Vec<Value> = match &rest[0] {
        Value::Str(path) => {
            if let Value::Record(map) = &subject {
                if let Some(v) = map.get(path) {
                    return Ok(if matches!(v, Value::Null) {
                        default
                    } else {
                        v.clone()
                    });
                }
            }
            path.split('.').map(|s| Value::Str(s.to_string())).collect()
        }
        Value::Int(i) => vec![Value::Int(*i)],
        Value::Array(items) => items.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "get",
                "a path: a field name, a dotted path, or an Array of keys and indices",
                other.type_name(),
            ))
        }
    };
    let mut current = subject;
    for step in &steps {
        if matches!(current, Value::Null) {
            return Ok(default);
        }
        match get_step(&current, step)? {
            Some(next) => current = next,
            None => return Ok(default),
        }
    }
    Ok(if matches!(current, Value::Null) {
        default
    } else {
        current
    })
}

/// `has(record, key)`: whether a Record has the field `key` (an Array has the
/// Int index). A field holding Null is present.
///
/// Example:
///   {a: 1} | has("a")     # true
///   has({a: 1}, "b")      # false
fn bi_has(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (subject, rest) = subject_and_rest("has", args, input)?;
    if rest.len() != 1 {
        return Err(crate::safety::bad_arg_with_hint(
            "has",
            "one key: has(record, key)",
            &format!("{} arguments after the subject", rest.len()),
            r#"pass the key: r | has("a")"#,
        ));
    }
    match (&subject, &rest[0]) {
        (Value::Record(map), Value::Str(key)) => Ok(Value::Bool(map.contains_key(key))),
        (Value::Array(items), Value::Int(i)) => {
            Ok(Value::Bool(*i >= 0 && (*i as usize) < items.len()))
        }
        (Value::Record(_), other) => Err(crate::safety::bad_arg(
            "has",
            "a String key for a Record",
            other.type_name(),
        )),
        (Value::Array(_), other) => Err(crate::safety::bad_arg(
            "has",
            "an Int index for an Array",
            other.type_name(),
        )),
        (other, _) => Err(crate::safety::bad_arg(
            "has",
            "a Record (or an Array) as the subject",
            other.type_name(),
        )),
    }
}

/// `to_entries(record)`: `[{key, value}, ...]`, in the order a Record iterates.
///
/// Example:
///   {a: 1} | to_entries     # [{key: "a", value: 1}]
fn bi_to_entries(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (subject, rest) = subject_and_rest("to_entries", args, input)?;
    if !rest.is_empty() {
        return Err(crate::safety::bad_arg(
            "to_entries",
            "no arguments after the subject",
            &format!("{} arguments", rest.len()),
        ));
    }
    match subject {
        Value::Record(map) => Ok(Value::Array(
            map.into_iter()
                .map(|(k, v)| {
                    let mut entry = BTreeMap::new();
                    entry.insert("key".to_string(), Value::Str(k));
                    entry.insert("value".to_string(), v);
                    Value::Record(entry)
                })
                .collect(),
        )),
        other => Err(crate::safety::bad_arg(
            "to_entries",
            "a Record as the subject",
            other.type_name(),
        )),
    }
}

/// `from_entries(array)`: a Record from `[{key, value}, ...]` records or
/// `[[key, value], ...]` pairs. A later entry with the same key wins. A key
/// that is not a String is E_BAD_ARG naming the entry's index.
///
/// Example:
///   [["a", 1], ["b", 2]] | from_entries     # {a: 1, b: 2}
fn bi_from_entries(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (subject, rest) = subject_and_rest("from_entries", args, input)?;
    if !rest.is_empty() {
        return Err(crate::safety::bad_arg(
            "from_entries",
            "no arguments after the subject",
            &format!("{} arguments", rest.len()),
        ));
    }
    let items = match subject {
        Value::Array(items) => items,
        other => {
            return Err(crate::safety::bad_arg(
                "from_entries",
                "an Array of {key, value} records or [key, value] pairs",
                other.type_name(),
            ))
        }
    };
    let mut out = BTreeMap::new();
    for (i, item) in items.into_iter().enumerate() {
        let (key, value) = match item {
            Value::Record(mut m) => match m.remove("key") {
                Some(k) => (k, m.remove("value").unwrap_or(Value::Null)),
                None => {
                    return Err(crate::safety::bad_arg_with_hint(
                        "from_entries",
                        &format!("entry {i} to have a key field"),
                        "a Record without one",
                        "each entry is {key: String, value: Any} or [key, value]",
                    ))
                }
            },
            Value::Array(mut pair) if pair.len() == 2 => {
                let value = pair.remove(1);
                (pair.remove(0), value)
            }
            other => {
                return Err(crate::safety::bad_arg_with_hint(
                    "from_entries",
                    &format!("entry {i} to be a {{key, value}} Record or a [key, value] pair"),
                    other.type_name(),
                    "each entry is {key: String, value: Any} or [key, value]",
                ))
            }
        };
        match key {
            Value::Str(k) => {
                out.insert(k, value);
            }
            other => {
                return Err(crate::safety::bad_arg_with_hint(
                    "from_entries",
                    &format!("entry {i}'s key to be a String"),
                    other.type_name(),
                    "convert it first: str(k) or to_string(k)",
                ))
            }
        }
    }
    Ok(Value::Record(out))
}

/// group_by (Group-Object): group rows by a field name or a lambda key. The
/// subject is piped (`rows | group_by("a")`) or the first argument
/// (`group_by(rows, "a")`), as for `where` and `sort_by`.
fn bi_group_object(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    // A piped value is the subject; otherwise it is the first argument.
    let (input, args) = match input {
        Some(v) => (v, args),
        None => {
            let mut args = args;
            if args.is_empty() {
                return Err(crate::safety::bad_arg_with_hint(
                    "group_by",
                    "an Array of rows and a key",
                    "nothing",
                    r#"pass the rows and a key: group_by(rows, "field") or rows | group_by("field")"#,
                ));
            }
            let subject = args.remove(0);
            (subject, args)
        }
    };

    if args.is_empty() {
        return Err(crate::safety::bad_arg_with_hint(
            "group_by",
            "a field name String or a lambda as the key",
            "nothing",
            r#"pass the key: rows | group_by("field") or group_by(rows, fn(r) => r.field)"#,
        ));
    }

    // The key is a field name, or a lambda called once per row whose result is
    // the key. `group_by(.region)` and `group_by(fn(r) => r.region)` are both
    // lambdas by the time they arrive here.
    let property = match &args[0] {
        Value::Str(s) => Some(s),
        Value::Lambda(_) => None,
        _ => {
            return Err(crate::safety::arg_err(
                "group_by: the key must be a field name String or a lambda",
            ))
        }
    };

    match input {
        Value::Array(arr) => {
            // Each row with its key's text and type name. Rows share a group
            // only when both match, so Int 1 and String "1" stay apart, while
            // the group is still named by the text, as it always was.
            let mut keyed: Vec<((String, &'static str), Value)> = Vec::with_capacity(arr.len());
            match property {
                Some(property) => {
                    for item in arr {
                        let key = get_property_value(&item, property);
                        keyed.push(((value_to_string(&key), key.type_name()), item));
                    }
                }
                None => {
                    let lam = need_lambda(&args[0], "group_by")?;
                    with_param_slots(lam, env, |env| {
                        for item in arr {
                            let key = call_lambda_one(lam, item.clone(), env, false)?.0;
                            keyed.push(((value_to_string(&key), key.type_name()), item));
                        }
                        Ok(())
                    })?;
                }
            }

            // Ordered by the key's text, then its type, so the groups come out
            // in the same order as before.
            let mut groups: BTreeMap<(String, &'static str), Vec<Value>> = BTreeMap::new();
            for (key, item) in keyed {
                groups.entry(key).or_default().push(item);
            }

            let mut result = Vec::new();
            for ((key, _type), items) in groups {
                let mut group = BTreeMap::new();
                group.insert("Name".to_string(), Value::Str(key));
                group.insert("Count".to_string(), Value::Int(items.len() as i64));
                group.insert("Group".to_string(), Value::Array(items));
                result.push(Value::Record(group));
            }

            Ok(Value::Array(result))
        }
        _ => Err(crate::safety::arg_err(
            "group_by: the rows must be an Array",
        )),
    }
}

/// Measure-Object: PowerShell-style count and, for one property, its statistics.
///
/// A piped array is measured element by element; any other piped value counts
/// as a single element. Statistics come from the numeric values of the property.
fn bi_measure_object(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "Measure-Object";
    let input =
        input.ok_or_else(|| crate::safety::arg_err("Measure-Object: requires pipeline input"))?;

    if args.len() > 1 {
        return Err(crate::safety::arg_err(format!(
            "{NAME}: takes one property name, got {} arguments",
            args.len()
        )));
    }
    let property = match args.first() {
        None => None,
        Some(Value::Str(property)) => Some(property.as_str()),
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{NAME}: property name must be a string, got {}",
                other.type_name()
            )))
        }
    };

    let items = match input {
        Value::Array(arr) => arr,
        other => vec![other],
    };

    let mut result = BTreeMap::new();
    result.insert("Count".to_string(), Value::Int(items.len() as i64));

    if let Some(property) = property {
        let values: Vec<f64> = items
            .iter()
            .filter_map(|item| match item {
                Value::Record(record) => match record.get(property) {
                    Some(Value::Int(i)) => Some(*i as f64),
                    Some(Value::Float(f)) => Some(*f),
                    _ => None,
                },
                _ => None,
            })
            .collect();

        if !values.is_empty() {
            let sum: f64 = values.iter().sum();
            let avg = sum / values.len() as f64;
            let min = values.iter().fold(f64::INFINITY, |a, &b| a.min(b));
            let max = values.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));

            result.insert("Sum".to_string(), Value::Float(sum));
            result.insert("Average".to_string(), Value::Float(avg));
            result.insert("Minimum".to_string(), Value::Float(min));
            result.insert("Maximum".to_string(), Value::Float(max));
        }
    }

    Ok(Value::Record(result))
}

// =============== Nushell-style Data Commands ===============

/// from-json: Parse JSON into structured data
fn bi_from_json(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let json_str = if let Some(input) = input {
        match input {
            Value::Str(s) => s,
            _ => {
                return Err(crate::safety::arg_err(
                    "from-json: input must be a JSON string",
                ))
            }
        }
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(s) => s.clone(),
            _ => {
                return Err(crate::safety::arg_err(
                    "from-json: argument must be a JSON string",
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err("from-json: no JSON input provided"));
    };
    let json_str = without_bom(json_str);

    // A bare `?` here surfaced serde's message as E_UNKNOWN with exit 1, the
    // one uncoded failure left in benches/agentic/errors.mjs (malformed-json).
    let parsed: serde_json::Value = serde_json::from_str(&json_str).map_err(|e| {
        // `from_json("issues.json")` -- the parser handed a path -- was every
        // IronShell attempt a small model made in the local E7 run. It stays
        // an error (the text is not JSON), but the repair is mechanical, so
        // the hint names it.
        let path = json_str.trim();
        // is_file() is a stat, and on Windows a stat of `\\host\share` opens an
        // SMB session, so a remote-share string is never probed (as in lsof).
        if !path.is_empty()
            && path.len() < 4096
            && !crate::safety::names_a_remote_share(path)
            && std::path::Path::new(path).is_file()
        {
            return anyhow::Error::new(crate::safety::SafetyError {
                code: crate::safety::ErrorCode::BadValue,
                message: format!("from_json: {path:?} is a file name, not JSON text"),
                builtin: "from_json".to_string(),
                hint: format!(
                    "read and parse the file with open({path:?}), or cat({path:?}) | from_json"
                ),
                approval: None,
                did_you_mean: vec![format!("open({path:?})")],
                expected: "JSON text".to_string(),
                got: "a file path".to_string(),
                extra: serde_json::Map::new(),
            });
        }
        // The text is wrong, not the call: a corrected call with the same text
        // fails again, so this is E_BAD_ARG and not retryable.
        let (detail, hint) = json_failure(&e, &json_str);
        crate::safety::bad_value_in(
            "from_json",
            format!("from_json: the text is not JSON: {detail}"),
            &hint,
        )
    })?;
    if let Some(refusal) = wide_integer_refusal("from_json", &json_str) {
        return Err(refusal);
    }
    Ok(json_to_value(with_integer_negative_zeros(
        parsed, &json_str,
    )))
}

/// `parsed` again, with every JSON `-0` that has no fraction or exponent read
/// as the integer 0. serde_json reads such a `-0` as the Float -0.0, but JSON's
/// grammar writes an integer there, and the Int has no sign of zero.
pub(crate) fn with_integer_negative_zeros(
    parsed: serde_json::Value,
    text: &str,
) -> serde_json::Value {
    if !text.contains("-0") {
        return parsed;
    }
    let bytes = text.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut changed = false;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'"' => {
                let start = i;
                i += 1;
                while i < bytes.len() && bytes[i] != b'"' {
                    i += if bytes[i] == b'\\' { 2 } else { 1 };
                }
                let end = (i + 1).min(bytes.len());
                out.extend_from_slice(&bytes[start..end]);
                i = end;
            }
            b'-' | b'0'..=b'9' => {
                let start = i;
                while i < bytes.len()
                    && matches!(bytes[i], b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E')
                {
                    i += 1;
                }
                if &bytes[start..i] == b"-0" {
                    out.push(b'0');
                    changed = true;
                } else {
                    out.extend_from_slice(&bytes[start..i]);
                }
            }
            other => {
                out.push(other);
                i += 1;
            }
        }
    }
    if !changed {
        return parsed;
    }
    match String::from_utf8(out) {
        Ok(fixed) => serde_json::from_str(&fixed).unwrap_or(parsed),
        Err(_) => parsed,
    }
}

/// to-json: Convert structured data to JSON
fn bi_to_json(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Piped, the value is the input and the argument is the pretty flag; called
    // directly, the value is the first argument.
    let (value, flags) = match input {
        Some(value) => (value, args.as_slice()),
        None => match args.split_first() {
            Some((value, flags)) => (value.clone(), flags),
            None => return Err(subject_refusal("to_json", "a value")),
        },
    };

    let json_val = value_to_json_strict("to_json", &value, "value")?;
    // An Int is the indent in spaces, 0 to 8; 0 is compact.
    if let Some(Value::Int(indent)) = flags.first() {
        return Ok(Value::Str(json_indented("to_json", &json_val, *indent)?));
    }

    let pretty = flags
        .first()
        .and_then(|arg| match arg {
            Value::Bool(b) => Some(*b),
            Value::Str(s) => Some(s == "pretty" || s == "true"),
            _ => None,
        })
        .unwrap_or(false);

    let json_str = if pretty {
        serde_json::to_string_pretty(&json_val)?
    } else {
        serde_json::to_string(&json_val)?
    };

    Ok(Value::Str(json_str))
}

/// Format bytes into a human-readable string (e.g. "1.5G", "100M", "4.0K")
fn format_bytes(bytes: i64) -> String {
    let abs = bytes.unsigned_abs();
    if abs >= 1_073_741_824 {
        format!("{:.1}G", bytes as f64 / 1_073_741_824.0)
    } else if abs >= 1_048_576 {
        format!("{:.1}M", bytes as f64 / 1_048_576.0)
    } else if abs >= 1024 {
        format!("{:.1}K", bytes as f64 / 1024.0)
    } else {
        format!("{}B", bytes)
    }
}

fn json_to_value(json: serde_json::Value) -> Value {
    match json {
        // Was `Value::Str("null")`: every JSON null reached the value space as
        // a four-letter string. It printed identically, so nothing looked
        // wrong, but `typeof(from_json("null"))` said String, `x == null` never
        // matched a null field, and AECON tagged the column as ambiguous.
        serde_json::Value::Null => Value::Null,
        serde_json::Value::Bool(b) => Value::Bool(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::Int(i)
            } else if let Some(f) = n.as_f64() {
                Value::Float(f)
            } else {
                Value::Str(n.to_string())
            }
        }
        serde_json::Value::String(s) => Value::Str(s),
        serde_json::Value::Array(arr) => Value::Array(arr.into_iter().map(json_to_value).collect()),
        serde_json::Value::Object(obj) => {
            let mut map = BTreeMap::new();
            for (k, v) in obj {
                map.insert(k, json_to_value(v));
            }
            Value::Record(map)
        }
    }
}

fn value_to_json(value: Value) -> serde_json::Value {
    match value {
        // A null is a JSON null, not the text "<null>" that value_to_string gives.
        Value::Null => serde_json::Value::Null,
        Value::Str(s) => serde_json::Value::String(s),
        Value::Int(i) => serde_json::Value::Number(serde_json::Number::from(i)),
        Value::Float(f) => serde_json::Value::Number(
            serde_json::Number::from_f64(f).unwrap_or_else(|| serde_json::Number::from(0)),
        ),
        Value::Bool(b) => serde_json::Value::Bool(b),
        Value::Array(arr) => serde_json::Value::Array(arr.into_iter().map(value_to_json).collect()),
        Value::Record(map) => {
            let mut obj = serde_json::Map::new();
            for (k, v) in map {
                obj.insert(k, value_to_json(v));
            }
            serde_json::Value::Object(obj)
        }
        _ => serde_json::Value::String(value_to_string(&value)),
    }
}

/// `value_to_json` for a user-facing JSON write (to_json, json_stringify,
/// save_json). A float JSON cannot hold, NaN or an infinity, is refused with
/// the path to it, where `value_to_json` writes 0. `path` starts at "value".
/// `value_to_json` itself stays for internal encodings.
fn value_to_json_strict(builtin: &str, value: &Value, path: &str) -> Result<serde_json::Value> {
    Ok(match value {
        Value::Float(f) if !f.is_finite() => {
            let what = if f.is_nan() {
                "NaN"
            } else if *f > 0.0 {
                "infinity"
            } else {
                "negative infinity"
            };
            return Err(crate::safety::value_not_representable(
                builtin,
                format!("{builtin}: {path} is {what}, which JSON cannot hold"),
                "JSON has no NaN or infinity: replace it with a number or null, or keep it as text",
            ));
        }
        Value::Array(items) => serde_json::Value::Array(
            items
                .iter()
                .enumerate()
                .map(|(i, item)| value_to_json_strict(builtin, item, &format!("{path}[{i}]")))
                .collect::<Result<Vec<_>>>()?,
        ),
        Value::Record(map) => {
            let mut obj = serde_json::Map::new();
            for (k, v) in map {
                obj.insert(
                    k.clone(),
                    value_to_json_strict(builtin, v, &path_key(path, k))?,
                );
            }
            serde_json::Value::Object(obj)
        }
        other => value_to_json(other.clone()),
    })
}

/// Whether `token` is an integer literal (an optional sign, then digits only)
/// that does not fit in a 64-bit Int. Such a number has no Int, and as a Float
/// it would lose its digits.
pub(crate) fn is_wide_integer(token: &str) -> bool {
    let digits = token.strip_prefix(['-', '+']).unwrap_or(token);
    !digits.is_empty()
        && digits.bytes().all(|b| b.is_ascii_digit())
        && token.parse::<i64>().is_err()
}

/// One open container while `wide_json_integer` reads JSON text.
struct JsonFrame {
    object: bool,
    /// The index of the element being read, for an Array.
    index: usize,
    /// The key of the member being read, for an object.
    key: String,
    /// Whether the next string in an object is a key.
    expect_key: bool,
}

/// The path a JSON scan is at, as a refusal names it: `value[0].id`.
fn json_path(stack: &[JsonFrame]) -> String {
    stack.iter().fold(String::from("value"), |path, frame| {
        if frame.object {
            path_key(&path, &frame.key)
        } else {
            format!("{path}[{}]", frame.index)
        }
    })
}

/// The first integer in JSON text that does not fit in a 64-bit Int, with its
/// path and its literal. serde_json reads such a number as a Float, which keeps
/// about 17 digits, so the text is scanned for it. Only text serde_json has
/// already accepted is scanned.
fn wide_json_integer(text: &str) -> Option<(String, String)> {
    let bytes = text.as_bytes();
    let mut stack: Vec<JsonFrame> = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'"' => {
                let start = i;
                i += 1;
                while i < bytes.len() && bytes[i] != b'"' {
                    i += if bytes[i] == b'\\' { 2 } else { 1 };
                }
                // The quotes and backslashes are ASCII, so these are char boundaries.
                let end = (i + 1).min(bytes.len());
                if let Some(frame) = stack.last_mut() {
                    if frame.object && frame.expect_key {
                        frame.key =
                            serde_json::from_str::<String>(&text[start..end]).unwrap_or_default();
                        frame.expect_key = false;
                    }
                }
                i = end;
            }
            b'{' | b'[' => {
                let object = bytes[i] == b'{';
                stack.push(JsonFrame {
                    object,
                    index: 0,
                    key: String::new(),
                    expect_key: object,
                });
                i += 1;
            }
            b'}' | b']' => {
                stack.pop();
                i += 1;
            }
            b',' => {
                if let Some(frame) = stack.last_mut() {
                    if frame.object {
                        frame.expect_key = true;
                    } else {
                        frame.index += 1;
                    }
                }
                i += 1;
            }
            b':' => {
                if let Some(frame) = stack.last_mut() {
                    frame.expect_key = false;
                }
                i += 1;
            }
            b'-' | b'0'..=b'9' => {
                let start = i;
                while i < bytes.len()
                    && matches!(bytes[i], b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E')
                {
                    i += 1;
                }
                let token = &text[start..i];
                if is_wide_integer(token) {
                    return Some((json_path(&stack), token.to_string()));
                }
            }
            _ => i += 1,
        }
    }
    None
}

/// The refusal for an integer in JSON text that does not fit in a 64-bit Int,
/// or None when every integer fits. Call it only on text that parsed as JSON.
/// `builtin` names the reader, which is what the error says it came from.
pub(crate) fn wide_integer_refusal(builtin: &str, text: &str) -> Option<anyhow::Error> {
    let (path, literal) = wide_json_integer(text)?;
    Some(crate::safety::value_not_representable(
        builtin,
        format!("{builtin}: integer overflow at {path}: {literal} does not fit in a 64-bit Int"),
        &format!("quote it as a string to keep the digits, such as \"{literal}\""),
    ))
}

/// from-csv: Parse CSV into structured data
/// The refusal for a conversion called with no value: it takes its subject
/// piped in or as the first argument, and the hint shows both forms.
fn subject_refusal(builtin: &str, what: &str) -> anyhow::Error {
    crate::safety::bad_arg_in(
        builtin,
        format!("{builtin}: requires {what}"),
        &format!("pipe the value in: v | {builtin}, or pass it as the argument: {builtin}(v)"),
    )
}

fn bi_from_csv(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Piped, the text is the input; called directly, it is the first argument.
    let csv_str = match input.or_else(|| args.into_iter().next()) {
        Some(Value::Str(s)) => s,
        Some(_) => {
            return Err(crate::safety::arg_err(
                "from-csv: input must be a CSV string",
            ))
        }
        None => return Err(subject_refusal("from_csv", "CSV text")),
    };

    parse_delimited(
        "from-csv",
        &csv_str,
        csv::ReaderBuilder::new().delimiter(b','),
    )
}

/// Parse delimited text with a header row into an Array of Records, with the
/// column type inference `from_csv` has. `open("x.tsv")` reads tab-separated
/// text through this with a tab delimiter and no quoting (TSV has none).
fn parse_delimited(builtin: &str, text: &str, builder: &mut csv::ReaderBuilder) -> Result<Value> {
    let mut reader = builder.from_reader(text.as_bytes());
    let headers: Vec<String> = reader
        .headers()
        .map_err(|e| crate::safety::bad_arg(builtin, "CSV text", &e.to_string()))?
        .iter()
        .map(|h| h.to_string())
        .collect();

    check_csv_headers(builtin, &headers)?;
    let mut records = Vec::new();
    for record in reader.records() {
        // A malformed row (unequal field counts, bad quoting) is the caller's
        // text, so E_BAD_ARG; it was an uncoded csv::Error, E_UNKNOWN.
        records.push(record.map_err(|e| csv_row_error(builtin, text, &e))?);
    }

    let rows = csv_rows(&headers, &records);
    Ok(Value::Array(rows.into_iter().map(Value::Record).collect()))
}

/// The refusal for a header row that names a column twice. Each row is a record
/// keyed by its header, so the second column would overwrite the first and one
/// column would vanish without a word. Names match exactly, as the keys do.
pub(crate) fn check_csv_headers(builtin: &str, headers: &[String]) -> Result<()> {
    for (i, name) in headers.iter().enumerate() {
        if let Some(first) = headers[..i].iter().position(|h| h == name) {
            return Err(crate::safety::bad_arg_in(
                builtin,
                format!(
                    "{builtin}: duplicate CSV column '{name}' at columns {} and {}",
                    first + 1,
                    i + 1
                ),
                "rename one column, or read the file with csv_columns(...) to see the header",
            ));
        }
    }
    Ok(())
}

/// The refusal for a CSV row the reader cannot take. csv counts a row's line
/// itself, and under CRLF that count is one short, so the line is worked out
/// from the byte the error names: the newlines up to and including that byte,
/// plus one. A row with the wrong number of fields is named by its line and by
/// the two counts.
fn csv_row_error(builtin: &str, text: &str, e: &csv::Error) -> anyhow::Error {
    if let csv::ErrorKind::UnequalLengths {
        pos: Some(pos),
        expected_len,
        len,
    } = e.kind()
    {
        let end = usize::try_from(pos.byte())
            .unwrap_or(usize::MAX)
            .saturating_add(1)
            .min(text.len());
        let line = text.as_bytes()[..end]
            .iter()
            .filter(|&&b| b == b'\n')
            .count()
            + 1;
        return crate::safety::bad_arg_in(
            builtin,
            format!(
                "{builtin}: CSV line {line}: found {len} fields where the header has {expected_len}"
            ),
            "fix the row so it has as many fields as the header, or quote a field that holds a comma",
        );
    }
    crate::safety::bad_arg(builtin, "CSV text", &e.to_string())
}

/// Whether a cell is a number a numeric column can hold: it parses as an Int or
/// a Float, has no leading "+", and has no leading zero before another digit.
/// So "0", "0.5" and "-0.5" are numbers, while "007", "00" and "-01" are not:
/// their zeros are part of an identifier or a code, not a magnitude.
fn is_number(field: &str) -> bool {
    if field.starts_with('+') {
        return false;
    }
    let unsigned = field.strip_prefix('-').unwrap_or(field).as_bytes();
    if unsigned.len() > 1 && unsigned[0] == b'0' && unsigned[1].is_ascii_digit() {
        return false;
    }
    // A word for a non-finite float ("NaN", "inf", "-Infinity") is a label in
    // CSV, not a number: JSON cannot hold it, so the column is text.
    // An integer past the 64-bit range would become a Float and lose its digits.
    if is_wide_integer(field) {
        return false;
    }
    field.parse::<i64>().is_ok() || matches!(field.parse::<f64>(), Ok(f) if f.is_finite())
}

/// One numeric cell as its column's type: an Int when every non-empty cell of
/// the column is an integer (`all_int`), else a Float.
fn numeric_cell(field: &str, all_int: bool) -> Value {
    if all_int {
        if let Ok(i) = field.parse::<i64>() {
            return Value::Int(i);
        }
    }
    match field.parse::<f64>() {
        Ok(f) => Value::Float(f),
        Err(_) => Value::Str(field.to_string()),
    }
}

/// The Bool a CSV cell spells: true or false in any case, else None.
fn csv_bool(field: &str) -> Option<bool> {
    if field.eq_ignore_ascii_case("true") {
        Some(true)
    } else if field.eq_ignore_ascii_case("false") {
        Some(false)
    } else {
        None
    }
}

/// The rows of a parsed CSV table, each column typed as a whole.
///
/// A column is numeric only when every non-empty cell is a number (see
/// `is_number`): a cell that is an integer past the 64-bit range makes its
/// column text. Its cells are then Int when all of them are integers, else
/// Float, and an empty cell is Null, so a sum or a count over it does not meet a
/// blank String. Every other column is all Strings, a blank being `""`: one
/// cell such as "007" or "NA" makes the whole column text. A column with no
/// non-empty cell is text too, since nothing in it says what type it is.
pub(crate) fn csv_rows(
    headers: &[String],
    records: &[csv::StringRecord],
) -> Vec<BTreeMap<String, Value>> {
    // Per column: None for text, Some(Some(all_int)) for a numeric column,
    // Some(None) for a column of true and false in any case.
    let kinds: Vec<Option<Option<bool>>> = (0..headers.len())
        .map(|column| {
            let mut numbers = 0usize;
            let mut flags = 0usize;
            let mut all_int = true;
            for record in records {
                match record.get(column) {
                    Some("") | None => {}
                    Some(field) if csv_bool(field).is_some() => flags += 1,
                    Some(field) if is_number(field) => {
                        numbers += 1;
                        all_int &= field.parse::<i64>().is_ok();
                    }
                    Some(_) => return None,
                }
            }
            match (numbers, flags) {
                (0, 0) => None,
                (_, 0) => Some(Some(all_int)),
                (0, _) => Some(None),
                _ => None,
            }
        })
        .collect();

    records
        .iter()
        .map(|record| {
            let mut row = BTreeMap::new();
            for (i, field) in record.iter().enumerate() {
                if let Some(header) = headers.get(i) {
                    let value = match kinds[i] {
                        Some(_) if field.is_empty() => Value::Null,
                        Some(Some(all_int)) => numeric_cell(field, all_int),
                        Some(None) => Value::Bool(csv_bool(field).unwrap_or(false)),
                        None => Value::Str(field.to_string()),
                    };
                    row.insert(header.clone(), value);
                }
            }
            row
        })
        .collect()
}

/// `csv_rows` for the SQL paths (`sql`, `sql_value` and `db_csv_to_sqlite`): an
/// empty cell in a text column is NULL, as one in a numeric column already is,
/// so `where amt is null` finds it and `sum` does not count it as 0. The csv
/// reader cannot tell an empty cell from a quoted `""`, so both are NULL.
/// `open` and `from_csv` keep their `""`.
pub(crate) fn csv_rows_sql(
    headers: &[String],
    records: &[csv::StringRecord],
) -> Vec<BTreeMap<String, Value>> {
    // csv_rows already reads a blank cell of a numeric column as null; a
    // blank in a text column stays '' (round 20), so `where note = ''` finds
    // it.
    csv_rows(headers, records)
}

/// The SQLite column type for a column of shell values, inferred as `sql` reads
/// them: INTEGER when every non-null value is an Int or Bool (a Bool is stored
/// 1 or 0), REAL when they are numbers and one is a Float, TEXT otherwise and
/// for a column of nothing but nulls.
pub(crate) fn sqlite_column_type<'a>(values: impl Iterator<Item = &'a Value>) -> &'static str {
    let (mut ints, mut reals) = (false, false);
    for v in values {
        match v {
            Value::Null => {}
            Value::Int(_) | Value::Bool(_) => ints = true,
            Value::Float(_) => reals = true,
            _ => return "TEXT",
        }
    }
    if reals {
        "REAL"
    } else if ints {
        "INTEGER"
    } else {
        "TEXT"
    }
}

/// Line endings of CSV text from the sqlite3 CLI as one RFC 4180 CRLF per row.
/// The CLI writes CRLF itself and its stdout in text mode (Windows) turns the
/// LF into CRLF again, giving CR CR LF. A newline inside a quoted cell is left
/// as it came.
fn normalize_csv_line_ends(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut in_quotes = false;
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '"' => {
                in_quotes = !in_quotes;
                out.push(c);
            }
            '\r' | '\n' if !in_quotes => {
                if c == '\r' {
                    while chars.peek() == Some(&'\r') {
                        chars.next();
                    }
                    if chars.peek() == Some(&'\n') {
                        chars.next();
                    }
                }
                out.push_str("\r\n");
            }
            _ => out.push(c),
        }
    }
    out
}

/// to_csv: Convert structured data to CSV
///
/// The columns are the first record's keys, or the `columns` Array when one is
/// given, in that order; a record without one of them writes an empty field.
fn bi_to_csv(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Piped, the rows are the input and an optional columns Array the first
    // argument; called directly, the rows come first and the columns second.
    let mut args = args.into_iter();
    let (input, columns) = match input {
        Some(rows) => (rows, args.next()),
        None => {
            let rows = args
                .next()
                .ok_or_else(|| subject_refusal("to_csv", "an array of records"))?;
            (rows, args.next())
        }
    };
    let columns: Option<Vec<String>> = match columns {
        None => None,
        Some(Value::Array(names)) => {
            let mut out = Vec::with_capacity(names.len());
            for name in names {
                match name {
                    Value::Str(s) => out.push(s),
                    other => {
                        return Err(crate::safety::bad_arg(
                            "to_csv",
                            "columns: Array of String",
                            other.type_name(),
                        ))
                    }
                }
            }
            if out.is_empty() {
                return Err(crate::safety::bad_arg(
                    "to_csv",
                    "columns: at least one column name",
                    "an empty Array",
                ));
            }
            Some(out)
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "to_csv",
                "columns: Array of String",
                other.type_name(),
            ))
        }
    };

    match input {
        Value::Array(arr) => {
            let headers: Vec<String> = match (columns, arr.first()) {
                (Some(names), _) => {
                    // A repeated column name would write the column twice, and each
                    // record has one value per name: refused, as the reader refuses it.
                    check_csv_headers("to_csv", &names)?;
                    names
                }
                (None, None) => return Ok(Value::Str(String::new())),
                (None, Some(Value::Record(_))) => {
                    // The keys of every record, sorted, so a key that only a later
                    // row has is a column too and is not dropped.
                    let mut keys = std::collections::BTreeSet::new();
                    for item in &arr {
                        if let Value::Record(record) = item {
                            keys.extend(record.keys().cloned());
                        }
                    }
                    keys.into_iter().collect()
                }
                (None, Some(_)) => {
                    return Err(crate::safety::arg_err(
                        "to_csv: input must be an array of records",
                    ))
                }
            };

            let mut csv_output = String::new();

            // Write headers, quoted as a value is, so a column name with a comma
            // reads back as one column.
            csv_output.push_str(&csv_line(headers.iter().map(|h| csv_escape(h)).collect()));
            csv_output.push('\n');

            // Write data rows
            for (index, item) in arr.iter().enumerate() {
                if let Value::Record(record) = item {
                    let row: Vec<String> = headers
                        .iter()
                        .map(|header| -> Result<String> {
                            Ok(record
                                .get(header)
                                .map(|v| -> Result<String> {
                                    Ok(match v {
                                        // An empty CSV field, not "<null>".
                                        Value::Null => String::new(),
                                        // A nested record or array is written as its
                                        // compact JSON, not a "{…}" or "[len=1]" placeholder
                                        // that loses the data. A NaN inside it is
                                        // refused, as to_json refuses it, not written as 0.
                                        Value::Record(_) | Value::Array(_) => csv_escape(
                                            &value_to_json_strict(
                                                "to_csv",
                                                v,
                                                &format!("rows[{index}].{header}"),
                                            )?
                                            .to_string(),
                                        ),
                                        // A NaN or infinity cell is refused, as to_json refuses
                                        // it: written it would read back as the text "NaN".
                                        Value::Float(f) if !f.is_finite() => {
                                            let what = if f.is_nan() {
                                                "NaN"
                                            } else if *f > 0.0 {
                                                "infinity"
                                            } else {
                                                "negative infinity"
                                            };
                                            return Err(crate::safety::value_not_representable(
                                                "to_csv",
                                                format!(
                                                    "to_csv: rows[{index}].{header} is {what}, which CSV cannot hold as a number"
                                                ),
                                                "CSV has no NaN or infinity number: replace it with a number or null, or keep it as text",
                                            ));
                                        }
                                        // A whole Float keeps its point, so it reads back as a
                                        // Float and not as an Int column.
                                        Value::Float(f) if f.fract() == 0.0 => {
                                            csv_escape(&format!("{f:.1}"))
                                        }
                                        v => csv_escape(&value_to_string(v)),
                                    })
                                })
                                .transpose()?
                                .unwrap_or_default())
                        })
                        .collect::<Result<Vec<_>>>()?;
                    csv_output.push_str(&csv_line(row));
                    csv_output.push('\n');
                }
            }

            Ok(Value::Str(csv_output))
        }
        _ => Err(crate::safety::arg_err(
            "to_csv: input must be an array of records",
        )),
    }
}

/// One CSV line from its escaped fields. A line of one empty field would be
/// an empty line, which the reader skips and so drops the row; it is written
/// as `""`, which reads back as one empty field.
fn csv_line(fields: Vec<String>) -> String {
    let line = fields.join(",");
    if line.is_empty() {
        "\"\"".to_string()
    } else {
        line
    }
}

fn csv_escape(s: &str) -> String {
    if s.contains(',') || s.contains('"') || s.contains('\n') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

/// csv_columns(path_or_text): the header row, in file order.
///
/// A String that names an existing file is read as that file; any other String
/// is CSV text. A single line that ends in .csv, .tsv or .txt and names no file
/// is E_NOT_FOUND, not a header. Quoting is parsed as `from_csv` parses it, so a
/// quoted header with a comma is one column.
fn bi_csv_columns(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Piped, the path or text is the input; called directly, it is the first argument.
    let subject = match input.or_else(|| args.into_iter().next()) {
        Some(Value::Str(s)) => s,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "csv_columns",
                "a path or CSV text: String",
                other.type_name(),
            ))
        }
        None => return Err(subject_refusal("csv_columns", "a CSV path or CSV text")),
    };

    // A remote-share string is never probed: exists() on it opens a connection.
    let probed = !crate::safety::names_a_remote_share(&subject);
    // A directory is not a CSV file, and its name is not CSV text either.
    if probed && std::path::Path::new(&subject).is_dir() {
        validate_read_path(&subject)?;
        return Err(crate::safety::bad_arg_in(
            "csv_columns",
            format!("csv_columns: '{subject}' names a directory, not a CSV file"),
            "pass the path of a CSV file, or CSV text with a newline",
        ));
    }
    let is_file = probed && std::path::Path::new(&subject).is_file();
    if is_file {
        let validated = validate_read_path(&subject)?;
        let file = std::fs::File::open(&validated)
            .map_err(|e| crate::safety::fs_error("csv_columns", &validated, &e))?;
        return csv_header_row(std::io::BufReader::new(file));
    }
    // One line that ends like a file name and names no file is a mistyped path,
    // not a header: refuse it rather than return the name as the only column.
    let lower = subject.to_ascii_lowercase();
    let names_a_file = [".csv", ".tsv", ".txt"]
        .iter()
        .any(|ext| lower.ends_with(ext));
    if names_a_file && !subject.contains(['\n', '\r']) {
        return Err(crate::safety::not_found_with(
            "csv_columns",
            format!("csv_columns: no file named '{subject}'"),
            "pass CSV text with a newline, or an existing file",
        ));
    }
    csv_header_row(subject.as_bytes())
}

/// The first record of a CSV source as its column names. Only the header is
/// read, so a large file costs one row. A leading byte-order mark is not part
/// of the first name.
fn csv_header_row(source: impl std::io::Read) -> Result<Value> {
    let mut reader = csv::Reader::from_reader(source);
    let mut names: Vec<String> = reader
        .headers()
        .map_err(|e| crate::safety::bad_arg("csv_columns", "CSV text", &e.to_string()))?
        .iter()
        .map(str::to_string)
        .collect();
    if let Some(first) = names.first_mut() {
        let unmarked = first.trim_start_matches('\u{feff}').to_string();
        *first = unmarked;
    }
    Ok(Value::Array(names.into_iter().map(Value::Str).collect()))
}

/// from-yaml: Parse YAML into structured data.
///
/// Delegates to [`crate::yaml`], which implements a documented subset (nested
/// mappings, sequences, quoting, comments, JSON-style flow collections) and
/// returns an error naming any construct outside it. It never silently
/// mis-parses — see that module for why that matters here.
fn bi_from_yaml(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Accepts either a pipeline value or a positional argument, matching
    // `from-json`'s contract.
    let yaml_str = match input {
        Some(Value::Str(s)) => s,
        Some(_) => {
            return Err(crate::safety::arg_err(
                "from-yaml: input must be a YAML string",
            ))
        }
        None => match args.first() {
            Some(Value::Str(s)) => s.clone(),
            Some(_) => {
                return Err(crate::safety::arg_err(
                    "from-yaml: argument must be a YAML string",
                ))
            }
            None => return Err(crate::safety::arg_err("from-yaml: requires YAML input")),
        },
    };
    crate::yaml::parse(&yaml_str).map_err(|e| {
        // A refusal the parser coded (an integer past 64 bits) keeps its code.
        if e.downcast_ref::<crate::safety::SafetyError>().is_some() {
            e
        } else {
            let message = format!("from-yaml: {e}");
            match yaml_unsupported_construct(&message) {
                Some(construct) => crate::safety::bad_arg_in(
                    "from_yaml",
                    message,
                    &format!(
                        "the document uses {construct}, which is outside IronShell's YAML subset; convert it to JSON and use from_json, or rewrite it without that construct"
                    ),
                ),
                None => crate::safety::arg_err(message),
            }
        }
    })
}

/// The unsupported YAML construct a parse error names, in words for a hint, or
/// None for an error that is not about the subset (a bad indent, a duplicate key).
fn yaml_unsupported_construct(message: &str) -> Option<&'static str> {
    const CONSTRUCTS: [(&str, &str); 7] = [
        ("anchors (&name)", "anchors (&name)"),
        ("aliases (*name)", "aliases (*name)"),
        ("explicit tags (!!type)", "explicit tags (!!type)"),
        ("folded block scalars (>)", "folded block scalars (>)"),
        ("block scalars (|)", "block scalars (|)"),
        ("merge keys (<<)", "merge keys (<<)"),
        ("multiple YAML documents", "several documents (---)"),
    ];
    for (needle, name) in CONSTRUCTS {
        if message.contains(needle) {
            return Some(name);
        }
    }
    if message.contains("flow collection") {
        return Some(
            "a flow collection that is not valid JSON (YAML flow maps need quoted keys and values)",
        );
    }
    None
}

/// to-yaml: Convert structured data to YAML.
///
/// Output is quoted wherever quoting is required, so the result parses back to
/// the same value.
fn bi_to_yaml(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let value = match input {
        Some(v) => v,
        None => args
            .into_iter()
            .next()
            .ok_or_else(|| crate::safety::arg_err("to-yaml: requires pipeline input"))?,
    };
    Ok(Value::Str(crate::yaml::emit(&value)))
}

/// columns: Get column names from structured data
fn bi_columns(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let input = input.ok_or_else(|| crate::safety::arg_err("columns: requires pipeline input"))?;

    match input {
        Value::Array(arr) => {
            if let Some(Value::Record(first)) = arr.first() {
                let columns: Vec<Value> = first.keys().map(|k| Value::Str(k.clone())).collect();
                Ok(Value::Array(columns))
            } else {
                Ok(Value::Array(Vec::new()))
            }
        }
        Value::Record(record) => {
            let columns: Vec<Value> = record.keys().map(|k| Value::Str(k.clone())).collect();
            Ok(Value::Array(columns))
        }
        _ => Ok(Value::Array(Vec::new())),
    }
}

/// describe: Get type and structure information about data
fn bi_describe(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let input = input.ok_or_else(|| crate::safety::arg_err("describe: requires pipeline input"))?;

    let mut description = BTreeMap::new();

    match &input {
        Value::Str(s) => {
            description.insert("type".to_string(), Value::Str("string".to_string()));
            description.insert("length".to_string(), Value::Int(s.len() as i64));
        }
        Value::Int(_) => {
            description.insert("type".to_string(), Value::Str("integer".to_string()));
        }
        Value::Float(_) => {
            description.insert("type".to_string(), Value::Str("float".to_string()));
        }
        Value::Bool(_) => {
            description.insert("type".to_string(), Value::Str("boolean".to_string()));
        }
        Value::Array(arr) => {
            description.insert("type".to_string(), Value::Str("array".to_string()));
            description.insert("length".to_string(), Value::Int(arr.len() as i64));

            if !arr.is_empty() {
                let first_type = match &arr[0] {
                    Value::Str(_) => "string",
                    Value::Int(_) => "integer",
                    Value::Float(_) => "float",
                    Value::Bool(_) => "boolean",
                    Value::Array(_) => "array",
                    Value::Record(_) => "record",
                    _ => "unknown",
                };
                description.insert(
                    "element_type".to_string(),
                    Value::Str(first_type.to_string()),
                );
            }
        }
        Value::Record(record) => {
            description.insert("type".to_string(), Value::Str("record".to_string()));
            description.insert("fields".to_string(), Value::Int(record.len() as i64));

            let field_names: Vec<Value> = record.keys().map(|k| Value::Str(k.clone())).collect();
            description.insert("field_names".to_string(), Value::Array(field_names));
        }
        _ => {
            description.insert("type".to_string(), Value::Str("unknown".to_string()));
        }
    }

    Ok(Value::Record(description))
}

// =============== AI-Enhanced Commands ===============

/// ai: Direct AI query with optional multi-modal support
/// Usage:
///   ai("prompt")                              - Simple text query
///   ai("prompt", {images: ["path1", "path2"]}) - With images
///   ai("prompt", {audio: ["path"]})           - With audio
///   ai("prompt", {video: ["path"]})           - With video
///   (no model argument: the provider comes from IRONSHELL_AI;
///    a model field is accepted and not used)
fn bi_ai(args: Vec<Value>, input: Option<Value>, _env: &mut Env) -> Result<Value> {
    // SECURITY: Rate limit AI calls
    check_rate_limit("bi_ai", 30, Duration::from_secs(60)).context("AI rate limit exceeded")?;

    // Get prompt from input or first argument
    let prompt = if let Some(input) = input {
        match input {
            Value::Str(s) => s,
            _ => return Err(crate::safety::arg_err("ai: input must be a prompt string")),
        }
    } else if !args.is_empty() {
        match &args[0] {
            Value::Str(s) => s.clone(),
            other => {
                return Err(crate::safety::bad_arg(
                    "ai",
                    "prompt: String",
                    other.type_name(),
                ))
            }
        }
    } else {
        return Err(crate::safety::arg_err("ai: requires a prompt string"));
    };

    // SECURITY: Validate AI prompt for injection
    let validated_prompt = validate_ai_prompt(&prompt).context("ai: prompt validation failed")?;

    // Check for optional config record (second argument)
    let config = args.get(1).and_then(|v| {
        if let Value::Record(r) = v {
            Some(r.clone())
        } else {
            None
        }
    });

    // Extract multi-modal content if present
    let images = config
        .as_ref()
        .and_then(|c| extract_string_array(c, "images"));
    let audio = config
        .as_ref()
        .and_then(|c| extract_string_array(c, "audio"));
    let video = config
        .as_ref()
        .and_then(|c| extract_string_array(c, "video"));
    let _model = config.as_ref().and_then(|c| {
        c.get("model").and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.clone())
            } else {
                None
            }
        })
    });

    // Determine if this is a multi-modal request
    let has_media = images.is_some() || audio.is_some() || video.is_some();

    if has_media {
        // Multi-modal request
        let mut content_parts = vec![crate::ai::MultiModalContent {
            text: Some(validated_prompt),
            image_url: None,
            audio_url: None,
            video_url: None,
            image_data: None,
            audio_data: None,
            video_data: None,
        }];

        // Load and encode images
        if let Some(img_paths) = images {
            for path in img_paths {
                // SECURITY: Validate path
                let validated_path = validate_read_path(&path)
                    .context(format!("ai: invalid image path: {}", path))?;

                // Read and base64 encode the image
                let data = read_bytes_capped("ai", &validated_path).context(format!(
                    "ai: failed to read image: {}",
                    validated_path.display()
                ))?;

                use base64::{engine::general_purpose::STANDARD, Engine as _};
                let encoded = STANDARD.encode(&data);

                content_parts.push(crate::ai::MultiModalContent {
                    text: None,
                    image_url: None,
                    audio_url: None,
                    video_url: None,
                    image_data: Some(encoded),
                    audio_data: None,
                    video_data: None,
                });
            }
        }

        // Load and encode audio
        if let Some(audio_paths) = audio {
            for path in audio_paths {
                let validated_path = validate_read_path(&path)
                    .context(format!("ai: invalid audio path: {}", path))?;

                let data = read_bytes_capped("ai", &validated_path).context(format!(
                    "ai: failed to read audio: {}",
                    validated_path.display()
                ))?;

                use base64::{engine::general_purpose::STANDARD, Engine as _};
                let encoded = STANDARD.encode(&data);

                content_parts.push(crate::ai::MultiModalContent {
                    text: None,
                    image_url: None,
                    audio_url: None,
                    video_url: None,
                    image_data: None,
                    audio_data: Some(encoded),
                    video_data: None,
                });
            }
        }

        // Load and encode video
        if let Some(video_paths) = video {
            for path in video_paths {
                let validated_path = validate_read_path(&path)
                    .context(format!("ai: invalid video path: {}", path))?;

                let data = read_bytes_capped("ai", &validated_path).context(format!(
                    "ai: failed to read video: {}",
                    validated_path.display()
                ))?;

                use base64::{engine::general_purpose::STANDARD, Engine as _};
                let encoded = STANDARD.encode(&data);

                content_parts.push(crate::ai::MultiModalContent {
                    text: None,
                    image_url: None,
                    audio_url: None,
                    video_url: None,
                    image_data: None,
                    audio_data: None,
                    video_data: Some(encoded),
                });
            }
        }

        let message = crate::ai::MultiModalMessage {
            role: "user".to_string(),
            content: content_parts,
        };

        let response = crate::ai::complete_multimodal_sync(&[message])?;

        Ok(Value::Str(response))
    } else {
        // Simple text-only request
        let response = crate::ai::complete_sync_router(&validated_prompt)?;

        Ok(Value::Str(response))
    }
}

/// Helper to extract a string array from a record field
fn extract_string_array(record: &BTreeMap<String, Value>, key: &str) -> Option<Vec<String>> {
    record.get(key).and_then(|v| {
        if let Value::Array(arr) = v {
            let strings: Vec<String> = arr
                .iter()
                .filter_map(|item| {
                    if let Value::Str(s) = item {
                        Some(s.clone())
                    } else {
                        None
                    }
                })
                .collect();
            if strings.is_empty() {
                None
            } else {
                Some(strings)
            }
        } else {
            None
        }
    })
}

// suggest / explain / complete / fix
//
// These were documented as "AI-powered". No model was consulted: each matched
// keywords against canned paragraphs, and the paragraphs told the caller to run
// `Get-Files`, `Get-Content`, `Where-Object`, `Sort-Object`, `from-json`,
// `describe` and `ai-suggest "..."` -- none of which this shell can call (the
// last parses as a subtraction). An agent following the advice failed again.
//
// They now answer from the shell's own catalogue: the dispatcher's names and
// the declared signatures, which the test suite executes. Nothing here claims
// intelligence it does not have.

/// The single string subject of these builtins: piped input or the first
/// argument.
fn hint_subject(builtin: &str, args: &[Value], input: Option<Value>) -> Result<String> {
    match input.or_else(|| args.first().cloned()) {
        Some(Value::Str(s)) if !s.trim().is_empty() => Ok(s),
        other => Err(crate::safety::bad_arg(
            builtin,
            "a non-empty String (argument or piped input)",
            other.as_ref().map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

fn hint_signature_record(sig: &crate::signature::Signature) -> Value {
    let mut r = BTreeMap::new();
    r.insert("name".to_string(), Value::Str(sig.name.to_string()));
    r.insert("signature".to_string(), Value::Str(sig.render()));
    r.insert("doc".to_string(), Value::Str(sig.doc.to_string()));
    Value::Record(r)
}

/// suggest(query): declared builtins whose name or description contains every
/// word of the query, best (most words in the name) first; at most 10.
fn bi_ai_suggest(args: Vec<Value>, input: Option<Value>, _env: &mut Env) -> Result<Value> {
    let query = hint_subject("suggest", &args, input)?.to_lowercase();
    let words: Vec<&str> = query.split_whitespace().collect();
    let mut hits: Vec<(usize, &crate::signature::Signature)> = crate::signature::SIGNATURES
        .iter()
        .filter_map(|sig| {
            let name = sig.name.to_lowercase();
            let text = format!("{} {}", name, sig.doc.to_lowercase());
            words
                .iter()
                .all(|w| text.contains(w))
                .then(|| (words.iter().filter(|w| name.contains(*w)).count(), sig))
        })
        .collect();
    hits.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.name.cmp(b.1.name)));
    Ok(Value::Array(
        hits.into_iter()
            .take(10)
            .map(|(_, sig)| hint_signature_record(sig))
            .collect(),
    ))
}

/// explain(subject): a builtin's declared signature and description, or what
/// an error code in the subject means.
fn bi_ai_explain(args: Vec<Value>, input: Option<Value>, _env: &mut Env) -> Result<Value> {
    let subject = hint_subject("explain", &args, input)?;
    if let Some(sig) = crate::signature::signature_of(subject.trim()) {
        return Ok(hint_signature_record(sig));
    }
    if is_dispatched(subject.trim()) {
        let mut r = BTreeMap::new();
        r.insert("name".to_string(), Value::Str(subject.trim().to_string()));
        r.insert(
            "doc".to_string(),
            Value::Str(
                "a builtin with no declared signature yet; its arguments are not described"
                    .to_string(),
            ),
        );
        return Ok(Value::Record(r));
    }
    if subject.contains("E_") {
        return bi_diagnose(vec![hint_error_value(&subject)], None);
    }
    Err(crate::safety::not_found(
        "explain",
        "builtin or error code",
        subject.trim(),
    ))
}

/// complete(partial): builtin names that start with `partial`, sorted,
/// at most 20.
fn bi_ai_complete(args: Vec<Value>, input: Option<Value>, _env: &mut Env) -> Result<Value> {
    let partial = hint_subject("complete", &args, input)?;
    let mut names: Vec<&str> = BUILTIN_LOOKUP
        .keys()
        .copied()
        .chain(FALLBACK_BUILTINS.iter().map(|(n, _)| *n))
        .filter(|n| n.starts_with(partial.trim()))
        .collect();
    names.sort_unstable();
    names.dedup();
    Ok(Value::Array(
        names
            .into_iter()
            .take(20)
            .map(|n| Value::Str(n.to_string()))
            .collect(),
    ))
}

/// An error given as text: the JSON a coded error prints, or plain words.
fn hint_error_value(text: &str) -> Value {
    let t = text.trim();
    let json = t
        .find('{')
        .and_then(|i| serde_json::from_str::<serde_json::Value>(&t[i..]).ok());
    match json.map(json_to_value) {
        Some(Value::Record(r)) => match r.get("error") {
            Some(inner @ Value::Record(_)) => inner.clone(),
            _ => Value::Record(r),
        },
        _ => match t.find("E_") {
            // "error[E_BAD_ARG]: ..." as the CLI prints it
            Some(i) => {
                let code: String = t[i..]
                    .chars()
                    .take_while(|c| c.is_ascii_uppercase() || *c == '_')
                    .collect();
                let mut r = BTreeMap::new();
                r.insert("code".to_string(), Value::Str(code));
                r.insert("message".to_string(), Value::Str(t.to_string()));
                Value::Record(r)
            }
            None => Value::Str(t.to_string()),
        },
    }
}

/// fix(error): the minimal repair context for an error, as diagnose gives
/// for a caught error record, from the error's text.
fn bi_ai_fix(args: Vec<Value>, input: Option<Value>, _env: &mut Env) -> Result<Value> {
    let error = match input.or_else(|| args.first().cloned()) {
        Some(v @ Value::Record(_)) => v,
        Some(Value::Str(s)) if !s.trim().is_empty() => hint_error_value(&s),
        other => {
            return Err(crate::safety::bad_arg(
                "fix",
                "an error: the record a catch bound, or its text",
                other.as_ref().map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    bi_diagnose(vec![error], None)
}

// ============ Option Type Constructors ============

/// Some(value) - Creates an Option variant containing a value
/// Returns: Record with _tag="Some" and _value=<arg>
fn bi_some(args: Vec<Value>) -> Result<Value> {
    if args.len() != 1 {
        return Err(crate::safety::arg_err(format!(
            "Some expects exactly 1 argument, got {}",
            args.len()
        )));
    }

    let mut record = BTreeMap::new();
    record.insert("_tag".to_string(), Value::Str("Some".to_string()));
    record.insert("_value".to_string(), args[0].clone());

    Ok(Value::Record(record))
}

/// None - Creates an Option variant representing no value
/// Returns: Record with _tag="None"
fn bi_none() -> Result<Value> {
    let mut record = BTreeMap::new();
    record.insert("_tag".to_string(), Value::Str("None".to_string()));

    Ok(Value::Record(record))
}

/// The one string argument a builtin takes; anything else is refused by name.
fn sole_str(builtin: &str, args: &[Value], expected: &str) -> Result<String> {
    match args {
        [Value::Str(s)] => Ok(s.clone()),
        [other] => Err(crate::safety::bad_arg(builtin, expected, other.type_name())),
        _ => Err(crate::safety::bad_arg(
            builtin,
            expected,
            &format!("{} argument(s)", args.len()),
        )),
    }
}

/// The single config record a builtin takes. A table, a string or any other
/// value is refused, because a config that is silently ignored is not a config.
fn cfg_record<'a>(
    builtin: &str,
    args: &'a [Value],
    expected: &str,
) -> Result<&'a std::collections::BTreeMap<String, Value>> {
    match args {
        [Value::Record(r)] => Ok(r),
        [other] => Err(crate::safety::bad_arg(builtin, expected, other.type_name())),
        _ => Err(crate::safety::bad_arg(
            builtin,
            expected,
            &format!("{} argument(s)", args.len()),
        )),
    }
}

/// Refuse a config key the builtin does not read. A misspelt option is an
/// error; read as its default it would be a silently different call.
fn cfg_known_keys(
    builtin: &str,
    rec: &std::collections::BTreeMap<String, Value>,
    known: &[&str],
) -> Result<()> {
    if let Some(key) = rec.keys().find(|k| !known.contains(&k.as_str())) {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("only the keys {}", known.join(", ")),
            &format!("unknown key '{key}'"),
        ));
    }
    Ok(())
}

fn cfg_str(
    builtin: &str,
    rec: &std::collections::BTreeMap<String, Value>,
    field: &str,
) -> Result<Option<String>> {
    match rec.get(field) {
        None => Ok(None),
        Some(Value::Str(s)) => Ok(Some(s.clone())),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{field}: a string"),
            other.type_name(),
        )),
    }
}

fn cfg_required_str(
    builtin: &str,
    rec: &std::collections::BTreeMap<String, Value>,
    field: &str,
) -> Result<String> {
    cfg_str(builtin, rec, field)?
        .ok_or_else(|| crate::safety::bad_arg(builtin, &format!("{field}: a string"), "missing"))
}

fn cfg_bool(
    builtin: &str,
    rec: &std::collections::BTreeMap<String, Value>,
    field: &str,
) -> Result<Option<bool>> {
    match rec.get(field) {
        None => Ok(None),
        Some(Value::Bool(b)) => Ok(Some(*b)),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{field}: a boolean"),
            other.type_name(),
        )),
    }
}

/// An integer field in `lo..=hi`. A value outside the range is refused, not
/// wrapped by an `as` cast.
fn cfg_int(
    builtin: &str,
    rec: &std::collections::BTreeMap<String, Value>,
    field: &str,
    lo: i64,
    hi: i64,
) -> Result<Option<i64>> {
    match rec.get(field) {
        None => Ok(None),
        Some(Value::Int(n)) if (lo..=hi).contains(n) => Ok(Some(*n)),
        Some(Value::Int(n)) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{field}: an integer in {lo}..={hi}"),
            &n.to_string(),
        )),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{field}: an integer"),
            other.type_name(),
        )),
    }
}

/// A numeric field (Int or Float) in `lo..=hi`, finite. Int is widened, never
/// dropped: the earlier code read only Float and silently ignored Int.
fn cfg_float(
    builtin: &str,
    rec: &std::collections::BTreeMap<String, Value>,
    field: &str,
    lo: f64,
    hi: f64,
) -> Result<Option<f64>> {
    let v = match rec.get(field) {
        None => return Ok(None),
        Some(Value::Float(f)) => *f,
        Some(Value::Int(n)) => *n as f64,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                &format!("{field}: a number"),
                other.type_name(),
            ))
        }
    };
    if v.is_finite() && v >= lo && v <= hi {
        Ok(Some(v))
    } else {
        Err(crate::safety::bad_arg(
            builtin,
            &format!("{field}: a number in {lo}..={hi}"),
            &v.to_string(),
        ))
    }
}

// ============ AI Backend Detection ============

/// ai_backends() - Detect and list all available AI backends
/// Returns: Array of records with backend information
///
/// Example:
///   ai_backends() | select(["name", "available", "models"])
fn bi_ai_backends(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("ai_backends", &args, &input)?;
    // A probe the budget or policy refuses is the answer, not an empty list.
    let backends = crate::ai::try_detect_available_backends()?;

    let records: Vec<Value> = backends
        .into_iter()
        .map(|backend| {
            let mut record = BTreeMap::new();
            record.insert("name".to_string(), Value::Str(backend.name));
            record.insert(
                "provider".to_string(),
                Value::Str(format!("{:?}", backend.provider)),
            );
            record.insert("endpoint".to_string(), Value::Str(backend.endpoint));
            record.insert("available".to_string(), Value::Bool(backend.available));

            let models: Vec<Value> = backend.models.into_iter().map(Value::Str).collect();
            record.insert("models".to_string(), Value::Array(models));

            Value::Record(record)
        })
        .collect();

    Ok(Value::Array(records))
}

/// ai_detect() - Automatically detect and return the best available backend
/// Returns: String with the model URI (e.g., "ollama:llama3" or "vllm:model")
/// Returns empty string if no backend is available.
///
/// Example:
///   let backend = ai_detect()
///   if backend != "" { ai(backend, "Hello!") }
fn bi_ai_detect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("ai_detect", &args, &input)?;
    // A probe the budget or policy refuses is an error. "No backend" is the
    // empty string, and only that.
    match crate::ai::try_auto_select_backend()? {
        Some(uri) => Ok(Value::Str(uri)),
        None => Ok(Value::Str(String::new())),
    }
}

/// ai_usage() - Get detailed AI usage statistics for the current session
/// Returns: Record with call_count, total_tokens, total_cost_usd, and per-call records
///
/// Example:
///   ai_usage()
///   ai_usage() | get("total_cost_usd")
fn bi_ai_usage() -> Result<Value> {
    let tracker = crate::ai::COST_TRACKER
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("ai_usage", "the cost tracker"))?;
    let summary = tracker.summary();
    Ok(Value::from_json(&summary))
}

/// ai_cost() - Get total estimated cost for the current session in USD
/// Returns: Float (cost in USD)
///
/// Example:
///   ai_cost()  # => 0.0042
fn bi_ai_cost() -> Result<Value> {
    let tracker = crate::ai::COST_TRACKER
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("ai_cost", "the cost tracker"))?;
    Ok(Value::Float(tracker.total_cost_usd))
}

/// ai_reset_usage() - Reset all usage tracking counters
/// Returns: String confirmation
///
/// Example:
///   ai_reset_usage()
fn bi_ai_reset_usage(input: Option<Value>) -> Result<Value> {
    refuse_piped("ai_reset_usage", &input)?;
    let mut tracker = crate::ai::COST_TRACKER
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("ai_reset_usage", "the cost tracker"))?;
    tracker.reset();
    Ok(Value::Str("Usage tracking reset".to_string()))
}

/// ai_gpu_memory() - Query GPU memory status
/// Returns: Record with GPU memory info for all available GPUs
///
/// Example:
///   ai_gpu_memory()
///   ai_gpu_memory() | get("gpus") | map(fn(g) => g.free_mb)
fn bi_ai_gpu_memory(input: Option<Value>) -> Result<Value> {
    refuse_piped("ai_gpu_memory", &input)?;
    let summary = crate::ai::try_gpu_memory_summary(None, None, None)?;
    Ok(Value::from_json(&summary))
}

/// ai_model_fits(config) - Check if a model fits in GPU memory
/// Args: config record with params_b (float), file_size_mb (int), quantization (string)
/// Returns: Record with model_fits (bool), estimated VRAM, GPU info
///
/// Example:
///   ai_model_fits({params_b: 7.0, quantization: "q4_k_m"})
///   ai_model_fits({file_size_mb: 4096})
fn bi_ai_model_fits(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ai_model_fits";
    refuse_piped(B, &input)?;
    let config = cfg_record(
        B,
        &args,
        "a config record: {params_b | file_size_mb, quantization?}",
    )?;
    cfg_known_keys(B, config, &["params_b", "file_size_mb", "quantization"])?;

    // The upper bound keeps the VRAM estimate far inside u64, so the estimate
    // cannot overflow; the lower bound refuses a size that rounds to zero MB
    // and so "fits" anything.
    let params_b = cfg_float(B, config, "params_b", f64::MIN_POSITIVE, 1_000_000.0)?;
    let file_size_mb = cfg_int(B, config, "file_size_mb", 1, i64::MAX)?;
    let quantization = cfg_str(B, config, "quantization")?;
    match (params_b.is_some(), file_size_mb.is_some()) {
        (true, false) | (false, true) => {}
        (false, false) => {
            return Err(crate::safety::bad_arg(
                B,
                "params_b (billions, above 0) or file_size_mb (1 or more)",
                "neither",
            ))
        }
        (true, true) => {
            return Err(crate::safety::bad_arg(
                B,
                "one of params_b or file_size_mb",
                "both",
            ))
        }
    }

    let summary = crate::ai::try_gpu_memory_summary(
        params_b,
        file_size_mb.map(|n| n as u64),
        quantization.as_deref(),
    )?;
    Ok(Value::from_json(&summary))
}

// =========================== AI Provider Registry Builtins ===========================

/// ai_providers() - List all registered providers and their status
/// Returns: Array of records with provider info
///
/// Example:
///   ai_providers()
///   ai_providers() | where(fn(p) => p.status == "ready")
fn bi_ai_providers() -> Result<Value> {
    use crate::providers::registry::PROVIDER_REGISTRY;

    let mut providers = PROVIDER_REGISTRY.list();
    providers.sort_by_key(|provider| provider.scheme());
    let available = PROVIDER_REGISTRY.available();

    let mut records = Vec::new();
    for p in &providers {
        let status = PROVIDER_REGISTRY
            .status(p)
            .map(|s| match s {
                crate::providers::registry::ProviderStatus::Ready => "ready".to_string(),
                crate::providers::registry::ProviderStatus::Unchecked => "unchecked".to_string(),
                crate::providers::registry::ProviderStatus::Unavailable { reason } => {
                    format!("unavailable: {}", reason)
                }
                crate::providers::registry::ProviderStatus::AuthFailed { reason } => {
                    format!("auth_failed: {}", reason)
                }
                crate::providers::registry::ProviderStatus::Disabled => "disabled".to_string(),
            })
            .unwrap_or_else(|| "unknown".to_string());

        let is_available = available.contains(p);
        let is_default = PROVIDER_REGISTRY.default_provider() == Some(*p);

        let mut rec = std::collections::BTreeMap::new();
        rec.insert("name".to_string(), Value::Str(p.scheme().to_string()));
        rec.insert("status".to_string(), Value::Str(status));
        rec.insert("available".to_string(), Value::Bool(is_available));
        rec.insert("default".to_string(), Value::Bool(is_default));
        if let Some(env_key) = p.api_key_env_var() {
            rec.insert(
                "has_key".to_string(),
                Value::Bool(std::env::var(env_key).is_ok()),
            );
        } else if matches!(p, crate::providers::ProviderType::Bedrock) {
            // Bedrock is refused (no SigV4 signing), so it has no usable key.
            rec.insert("has_key".to_string(), Value::Bool(false));
            rec.insert("available".to_string(), Value::Bool(false));
        } else {
            rec.insert("has_key".to_string(), Value::Bool(true));
        }
        records.push(Value::Record(rec));
    }

    Ok(Value::Array(records))
}

/// ai_routes() - List all configured routing rules
/// Returns: Array of records with rule info
///
/// Example:
///   ai_routes()
fn bi_ai_routes() -> Result<Value> {
    // The rules the registry checks, in the order it checks them, and the
    // registry's totals. Nothing here contacts a provider.
    use crate::providers::registry::PROVIDER_REGISTRY;

    let stats = PROVIDER_REGISTRY.stats();
    let providers = PROVIDER_REGISTRY.list();
    let rules = PROVIDER_REGISTRY.routing_rules();

    let rule_values: Vec<Value> = rules
        .iter()
        .map(|rule| {
            let mut r = std::collections::BTreeMap::new();
            r.insert("name".to_string(), Value::Str(rule.name.clone()));
            r.insert("priority".to_string(), Value::Int(i64::from(rule.priority)));
            r.insert(
                "condition".to_string(),
                Value::Str(rule.condition.describe()),
            );
            // A rule with no target matches but returns nothing, so route
            // skips it: Null says so instead of guessing a provider.
            r.insert(
                "target".to_string(),
                rule.target_provider
                    .map(|p| Value::Str(p.scheme().to_string()))
                    .unwrap_or(Value::Null),
            );
            r.insert(
                "allow_fallback".to_string(),
                Value::Bool(rule.allow_fallback),
            );
            Value::Record(r)
        })
        .collect();

    let mut rec = std::collections::BTreeMap::new();
    rec.insert("rule_count".to_string(), Value::Int(rules.len() as i64));
    if rules.is_empty() {
        rec.insert(
            "note".to_string(),
            Value::Str(
                "no routing rules are registered; a request goes to the provider its model names when that provider is registered, and to the default provider otherwise"
                    .to_string(),
            ),
        );
    }
    rec.insert("rules".to_string(), Value::Array(rule_values));
    rec.insert(
        "total_requests".to_string(),
        Value::Int(stats.total_requests as i64),
    );
    rec.insert(
        "total_tokens".to_string(),
        Value::Int(stats.total_tokens as i64),
    );
    rec.insert(
        "registered_providers".to_string(),
        Value::Int(providers.len() as i64),
    );
    rec.insert(
        "default_provider".to_string(),
        PROVIDER_REGISTRY
            .default_provider()
            .map(|p| Value::Str(p.scheme().to_string()))
            .unwrap_or(Value::Str("none".to_string())),
    );
    rec.insert(
        "router_enabled".to_string(),
        Value::Bool(std::env::var("IRONSHELL_AI_ROUTER").ok().as_deref() == Some("registry")),
    );

    Ok(Value::Record(rec))
}

/// ai_add_route(config) - Add a routing rule
/// Args: config record with name, priority (int), condition (string), target (string), allow_fallback (bool)
/// Condition types: "always", "has_tools", "has_vision", "model:pattern", "tokens_over:N"
/// Returns: String confirmation
///
/// Example:
///   ai_add_route({name: "tools_to_openai", priority: 100, condition: "has_tools", target: "openai"})
///   ai_add_route({name: "large_to_groq", priority: 50, condition: "tokens_over:4000", target: "groq"})
fn bi_ai_add_route(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::providers::registry::{RoutingCondition, RoutingRule, PROVIDER_REGISTRY};
    use crate::providers::ProviderType;
    const B: &str = "ai_add_route";

    refuse_piped(B, &input)?;
    let config = cfg_record(
        B,
        &args,
        "a config record: {name, condition, priority?, target?, allow_fallback?}",
    )?;
    cfg_known_keys(
        B,
        config,
        &["name", "priority", "condition", "target", "allow_fallback"],
    )?;

    let name = cfg_required_str(B, config, "name")?;
    let condition_str = cfg_required_str(B, config, "condition")?;
    let priority = cfg_int(B, config, "priority", 0, u32::MAX as i64)?.map_or(50, |p| p as u32);
    let target_str = cfg_str(B, config, "target")?;
    let allow_fallback = cfg_bool(B, config, "allow_fallback")?.unwrap_or(true);

    let condition = if condition_str == "always" {
        RoutingCondition::Always
    } else if condition_str == "has_tools" {
        RoutingCondition::HasTools
    } else if condition_str == "has_vision" {
        RoutingCondition::HasVision
    } else if let Some(pattern) = condition_str.strip_prefix("model:") {
        RoutingCondition::ModelPattern {
            pattern: pattern.to_string(),
        }
    } else if let Some(n) = condition_str.strip_prefix("tokens_over:") {
        let threshold = n.parse::<u32>().map_err(|_| {
            crate::safety::bad_arg(
                B,
                "condition: tokens_over:<N> with N a whole number",
                &condition_str,
            )
        })?;
        RoutingCondition::TokenCountOver { threshold }
    } else {
        return Err(crate::safety::bad_arg(
            B,
            "condition: always, has_tools, has_vision, model:<pattern> or tokens_over:<N>",
            &condition_str,
        ));
    };

    let target_provider = match target_str.as_deref() {
        None => None,
        Some(target) => Some(ProviderType::from_scheme(target).map_err(|_| {
            crate::safety::bad_arg(B, "target: a provider name such as openai", target)
        })?),
    };

    let rule = RoutingRule {
        name: name.clone(),
        priority,
        condition,
        target_provider,
        allow_fallback,
    };

    PROVIDER_REGISTRY.add_routing_rule(rule);

    Ok(Value::Str(format!(
        "Route '{}' added (priority {})",
        name, priority
    )))
}

/// ai_set_default(provider) - Set the default AI provider for registry routing
/// Args: provider name string (e.g., "openai", "anthropic", "ollama")
/// Returns: String confirmation
///
/// Example:
///   ai_set_default("openai")
fn bi_ai_set_default(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::providers::registry::PROVIDER_REGISTRY;
    use crate::providers::ProviderType;
    const B: &str = "ai_set_default";

    refuse_piped(B, &input)?;
    let provider_str = sole_str(B, &args, "a provider name string")?;

    // Refused before the registry is touched: an unknown name changes nothing.
    let provider_type = ProviderType::from_scheme(&provider_str).map_err(|_| {
        crate::safety::bad_arg(B, "a provider name such as openai or ollama", &provider_str)
    })?;

    // Register if not already registered
    if PROVIDER_REGISTRY.get(&provider_type).is_none() {
        let config = crate::providers::ProviderConfig::from_env(provider_type).with_env_key();
        PROVIDER_REGISTRY.register(provider_type, config);
    }

    // Registered just above, so the only failure is a provider the registry
    // does not hold; say which name missed.
    PROVIDER_REGISTRY
        .set_default(provider_type)
        .map_err(|_| crate::safety::not_found(B, "provider", &provider_str))?;

    Ok(Value::Str(format!(
        "Default provider set to '{}'",
        provider_str
    )))
}

/// ai_registry_stats() - Get usage statistics from the provider registry
/// Returns: Record with per-provider request/token/success counts
///
/// Example:
///   ai_registry_stats()
fn bi_ai_registry_stats() -> Result<Value> {
    use crate::providers::registry::PROVIDER_REGISTRY;

    let stats = PROVIDER_REGISTRY.stats();
    let mut rec = std::collections::BTreeMap::new();
    rec.insert(
        "total_requests".to_string(),
        Value::Int(stats.total_requests as i64),
    );
    rec.insert(
        "total_tokens".to_string(),
        Value::Int(stats.total_tokens as i64),
    );

    let mut by_provider = std::collections::BTreeMap::new();
    for (pt, ps) in &stats.by_provider {
        let mut prec = std::collections::BTreeMap::new();
        prec.insert("requests".to_string(), Value::Int(ps.requests as i64));
        prec.insert("successes".to_string(), Value::Int(ps.successes as i64));
        prec.insert("failures".to_string(), Value::Int(ps.failures as i64));
        prec.insert("tokens".to_string(), Value::Int(ps.tokens as i64));
        prec.insert(
            "avg_latency_ms".to_string(),
            Value::Float(ps.avg_latency_ms),
        );
        prec.insert(
            "min_latency_ms".to_string(),
            Value::Float(ps.min_latency_ms),
        );
        prec.insert(
            "max_latency_ms".to_string(),
            Value::Float(ps.max_latency_ms),
        );
        prec.insert(
            "p95_latency_ms".to_string(),
            Value::Float(ps.p95_latency_ms),
        );
        prec.insert(
            "total_cost_usd".to_string(),
            Value::Float(ps.total_cost_usd),
        );
        by_provider.insert(pt.scheme().to_string(), Value::Record(prec));
    }
    rec.insert("by_provider".to_string(), Value::Record(by_provider));

    // Include load balancing strategy
    let strategy = PROVIDER_REGISTRY.load_balancing_strategy();
    rec.insert(
        "load_balancing".to_string(),
        Value::Str(format!("{:?}", strategy)),
    );

    Ok(Value::Record(rec))
}

/// ai_set_load_balancing(strategy) - Set the load balancing strategy for AI providers
/// Args: strategy string: "none", "round_robin", "least_latency", "least_requests", "adaptive"
///       OR a record with {type: "weighted", weights: {openai: 3, anthropic: 1}}
/// Returns: String confirmation
///
/// Example:
///   ai_set_load_balancing("round_robin")
///   ai_set_load_balancing("least_latency")
///   ai_set_load_balancing({type: "weighted", weights: {openai: 3, anthropic: 1}})
fn bi_ai_set_load_balancing(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::providers::registry::{LoadBalancingStrategy, PROVIDER_REGISTRY};
    const B: &str = "ai_set_load_balancing";

    refuse_piped(B, &input)?;
    let strategy = match args.as_slice() {
        [Value::Str(s)] => match s.as_str() {
            "none" => LoadBalancingStrategy::None,
            "round_robin" | "roundrobin" | "rr" => LoadBalancingStrategy::RoundRobin,
            "least_latency" | "latency" => LoadBalancingStrategy::LeastLatency,
            "least_requests" | "requests" => LoadBalancingStrategy::LeastRequests,
            "adaptive" | "auto" => LoadBalancingStrategy::Adaptive,
            other => {
                return Err(crate::safety::bad_arg(
                    B,
                    "a strategy: none, round_robin, least_latency, least_requests, adaptive, or a weighted config record",
                    other,
                ))
            }
        },
        [Value::Record(r)] => weighted_strategy(B, r)?,
        [other] => {
            return Err(crate::safety::bad_arg(
                B,
                "a strategy string or a weighted config record",
                other.type_name(),
            ))
        }
        _ => {
            return Err(crate::safety::bad_arg(
                B,
                "one strategy argument",
                &format!("{} argument(s)", args.len()),
            ))
        }
    };

    let label = format!("{:?}", strategy);
    PROVIDER_REGISTRY.set_load_balancing(strategy);

    Ok(Value::Str(format!("Load balancing set to {}", label)))
}

/// The weighted strategy a config record names. Every key and weight is
/// checked: a misspelt key, a non-integer weight or an empty table is refused,
/// rather than read as weight 1 or as a strategy that does nothing.
fn weighted_strategy(
    builtin: &str,
    r: &std::collections::BTreeMap<String, Value>,
) -> Result<crate::providers::registry::LoadBalancingStrategy> {
    use crate::providers::registry::LoadBalancingStrategy;
    use crate::providers::ProviderType;

    cfg_known_keys(builtin, r, &["type", "weights"])?;
    let lb_type = cfg_str(builtin, r, "type")?.unwrap_or_else(|| "weighted".to_string());
    if lb_type != "weighted" {
        return Err(crate::safety::bad_arg(
            builtin,
            "type: \"weighted\"",
            &lb_type,
        ));
    }
    let weights_rec = match r.get("weights") {
        Some(Value::Record(w)) => w,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "weights: a record of provider name to weight",
                other.type_name(),
            ))
        }
        None => {
            return Err(crate::safety::bad_arg(
                builtin,
                "weights: a record of provider name to weight",
                "missing",
            ))
        }
    };
    if weights_rec.is_empty() {
        return Err(crate::safety::bad_arg(
            builtin,
            "weights: at least one provider",
            "an empty record",
        ));
    }

    let mut weights = std::collections::HashMap::new();
    for (key, value) in weights_rec {
        let provider = ProviderType::from_scheme(key).map_err(|_| {
            crate::safety::bad_arg(
                builtin,
                "weights: keys are provider names such as openai",
                key,
            )
        })?;
        let weight = match value {
            Value::Int(i) if (0..=u32::MAX as i64).contains(i) => *i as u32,
            Value::Float(f)
                if f.is_finite() && f.fract() == 0.0 && *f >= 0.0 && *f <= u32::MAX as f64 =>
            {
                *f as u32
            }
            other => {
                return Err(crate::safety::bad_arg(
                    builtin,
                    &format!("weight for {key}: a whole number from 0 to {}", u32::MAX),
                    &other.to_display_string(),
                ))
            }
        };
        weights.insert(provider, weight);
    }
    Ok(LoadBalancingStrategy::Weighted { weights })
}

/// ai_load_balancing() - Get the current load balancing strategy
/// Returns: String describing the active strategy
///
/// Example:
///   ai_load_balancing()
fn bi_ai_load_balancing() -> Result<Value> {
    use crate::providers::registry::PROVIDER_REGISTRY;

    let strategy = PROVIDER_REGISTRY.load_balancing_strategy();
    Ok(Value::Str(format!("{:?}", strategy)))
}

/// ai_convert_model(config) - Convert a model between formats.
///
/// **Delegates to IronVault.** This used to call an in-tree converter whose
/// every path was `fs::copy` — its own source said "simulate conversion by
/// copying file" — and which then reported `success: true` with a checksum of
/// the unchanged bytes. A conversion that silently does nothing is worse than
/// one that fails, so that path is gone. Format conversion is IronVault's job
/// in this stack, and IronVault addresses models by vault name rather than by
/// file path, so callers holding a loose file must add it to the vault first.
///
/// Args: config record with name and to_format (see `vault_convert`), or the
/// legacy source/target/source_format/target_format form, which is refused.
///
/// Example:
///   ai_convert_model({name: "my-llm", to_format: "gguf", quantization: "q4_k_m"})
fn bi_ai_convert_model(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ai_convert_model";
    refuse_piped(B, &input)?;
    let config = cfg_record(
        B,
        &args,
        "a config record: {name, to_format, quantization?, output?, validate?}",
    )?;

    // The legacy path-based form cannot be honoured: IronVault converts models
    // it stores, and there is no correct way to guess which stored model a
    // loose path corresponds to. Say so precisely rather than half-working.
    if config.contains_key("source") || config.contains_key("target") {
        return Err(crate::safety::arg_err(
            "ai_convert_model: the source/target path form is no longer supported.\n\
             It was backed by an in-tree converter that copied the file and reported \
             success, so it never converted anything.\n\
             Conversion now goes through IronVault, which addresses models by vault name:\n  \
               iv add <path> --name <name>\n  \
               ai_convert_model({name: \"<name>\", to_format: \"gguf\"})",
        ));
    }

    bi_vault_convert(args, None)
}

/// ai_supported_conversions() - List the format conversions available.
///
/// Answered by IronVault, which is what actually performs them. The in-tree
/// table this used to read listed conversions that were implemented as file
/// copies, so it described capability the shell did not have.
///
/// Returns: the vault's supported conversion paths
fn bi_ai_supported_conversions(input: Option<Value>) -> Result<Value> {
    bi_vault_conversions(input)
}

/// ai_detect_format(path) - Detect the format of a model file
/// Args: path (string)
/// Returns: String with detected format name
fn bi_ai_detect_format(args: Vec<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s,
        _ => {
            return Err(crate::safety::arg_err(
                "ai_detect_format: requires a file path string",
            ))
        }
    };

    let ext = std::path::Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");

    let format = match ext.to_lowercase().as_str() {
        "gguf" => "GGUF",
        "safetensors" => "SafeTensors",
        "pt" | "pth" | "bin" => "PyTorch",
        "onnx" => "ONNX",
        "pb" | "savedmodel" => "TensorFlow",
        "trt" | "engine" => "TensorRT",
        _ => "Unknown",
    };

    Ok(Value::Str(format.to_string()))
}

// ========== Local Inference Builtins ==========

// ============================================================================
// THE NERVOSYS STACK — IronGate (routing), IronWorks (inference),
// IronVault (model store and conversion)
// ============================================================================

/// ai_gateway() - Report IronGate: whether it is up, what it will route, and
/// the state of each backend behind it.
///
/// This is the one place a caller can see the shape of the stack it is talking
/// to, including whether the local leg (IronWorks) is actually serving.
///
/// Returns: Record with url, reachable, providers, models, targets
///
/// Example:
///   ai_gateway()
///   ai_gateway().targets | where(fn(t) => t.circuit != "closed")
fn bi_ai_gateway(input: Option<Value>) -> Result<Value> {
    refuse_piped("ai_gateway", &input)?;
    let mut rec = std::collections::BTreeMap::new();
    rec.insert(
        "url".to_string(),
        Value::Str(crate::model_plane::gate_url()),
    );
    rec.insert(
        "default_model".to_string(),
        Value::Str(crate::model_plane::gate_model()),
    );

    let health = match crate::model_plane::gate_health() {
        Ok(h) => h,
        Err(e) => {
            // An unreachable gateway is an answer, not an error: the caller
            // asked about the gateway's state and "down" is a state. Returning
            // Err here would make the common check `ai_gateway().reachable`
            // impossible to write.
            rec.insert("reachable".to_string(), Value::Bool(false));
            rec.insert("error".to_string(), Value::Str(e.to_string()));
            rec.insert("providers".to_string(), Value::Int(0));
            rec.insert("models".to_string(), Value::Array(vec![]));
            rec.insert("targets".to_string(), Value::Array(vec![]));
            return Ok(Value::Record(rec));
        }
    };

    rec.insert("reachable".to_string(), Value::Bool(true));
    rec.insert("providers".to_string(), Value::Int(health.providers as i64));
    rec.insert(
        "models".to_string(),
        Value::Array(health.models.into_iter().map(Value::Str).collect()),
    );

    // Per-target circuit state. Best-effort: /status is a richer endpoint than
    // /health and a gateway can be serving with it unavailable. When it is
    // unavailable the targets are unknown, and the reason is reported as
    // targets_error rather than presented as an empty list.
    let targets = match crate::model_plane::gate_status() {
        Ok(status) => status
            .get("targets")
            .or_else(|| status.get("breakers"))
            .and_then(|t| t.as_array())
            .map(|arr| {
                arr.iter()
                    .cloned()
                    .map(json_to_value)
                    .collect::<Vec<Value>>()
            })
            .unwrap_or_default(),
        Err(e) => {
            rec.insert("targets_error".to_string(), Value::Str(e.to_string()));
            vec![]
        }
    };
    rec.insert("targets".to_string(), Value::Array(targets));

    Ok(Value::Record(rec))
}

/// vault_models() - List the models IronVault is storing.
///
/// Reads the encrypted inventory, so IRONVAULT_PASSPHRASE must be set; the
/// vault reports that failure itself rather than this builtin guessing at it.
///
/// Returns: Array of records, as the vault reports them
///
/// Example:
///   vault_models()
///   vault_models() | where(fn(m) => m.format == "gguf")
fn bi_vault_models(input: Option<Value>) -> Result<Value> {
    refuse_piped("vault_models", &input)?;
    let json = crate::model_plane::vault_list()?;
    Ok(json_to_value(json))
}

/// vault_conversions() - List the format conversions IronVault supports.
///
/// Returns: Array of supported conversion paths
fn bi_vault_conversions(input: Option<Value>) -> Result<Value> {
    refuse_piped("vault_conversions", &input)?;
    let json = crate::model_plane::vault_conversions()?;
    Ok(json_to_value(json))
}

/// vault_convert(config) - Convert a stored model between formats.
///
/// Args: config record with name, to_format, and optionally quantization,
/// output, validate.
///
/// Returns: Record with the vault's own report
///
/// Example:
///   vault_convert({name: "my-llm", to_format: "gguf", quantization: "q4_k_m", validate: true})
fn bi_vault_convert(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "vault_convert";
    refuse_piped(B, &input)?;
    let config = cfg_record(
        B,
        &args,
        "a config record: {name, to_format, quantization?, output?, validate?}",
    )?;
    cfg_known_keys(
        B,
        config,
        &[
            "name",
            "to_format",
            "target_format",
            "quantization",
            "output",
            "validate",
        ],
    )?;

    let name = cfg_required_str(B, config, "name")?;
    let to_format = match (
        cfg_str(B, config, "to_format")?,
        cfg_str(B, config, "target_format")?,
    ) {
        (Some(f), None) | (None, Some(f)) => f,
        (None, None) => {
            return Err(crate::safety::bad_arg(
                B,
                "to_format: a format such as \"gguf\" or \"safetensors\"",
                "missing",
            ))
        }
        (Some(_), Some(_)) => {
            return Err(crate::safety::bad_arg(
                B,
                "one of to_format or target_format",
                "both",
            ))
        }
    };
    let quantization = cfg_str(B, config, "quantization")?;
    let output = cfg_str(B, config, "output")?;
    let validate = cfg_bool(B, config, "validate")?.unwrap_or(false);

    // These reach iv as argv, where a value beginning with '-' is an option.
    let mut values = vec![name.clone(), to_format.clone()];
    values.extend(quantization.iter().cloned());
    values.extend(output.iter().cloned());
    crate::safety::reject_option_like(B, &values)?;

    let stdout = crate::model_plane::vault_convert(
        &name,
        &to_format,
        quantization.as_deref(),
        output.as_deref(),
        validate,
    )?;

    let mut rec = std::collections::BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(name));
    rec.insert("to_format".to_string(), Value::Str(to_format));
    if let Some(q) = quantization {
        rec.insert("quantization".to_string(), Value::Str(q));
    }
    if let Some(o) = output {
        rec.insert("output".to_string(), Value::Str(o));
    }
    rec.insert("validated".to_string(), Value::Bool(validate));
    rec.insert("report".to_string(), Value::Str(stdout.trim().to_string()));
    Ok(Value::Record(rec))
}

/// ai_local_backends() - List available local inference backends
/// Returns: Array of Records with backend name and supported formats
///
/// Example:
///   ai_local_backends()
fn bi_ai_local_backends() -> Result<Value> {
    use crate::local_inference;

    let backends = local_inference::available_backends();
    let names = local_inference::backend_names();

    if backends.is_empty() {
        return Ok(Value::Array(vec![Value::Record({
            let mut r = std::collections::BTreeMap::new();
            r.insert("status".to_string(), Value::Str("none".to_string()));
            r.insert(
                "message".to_string(),
                Value::Str(
                    "No local inference backends compiled. Rebuild with --features candle or --features onnx"
                        .to_string(),
                ),
            );
            r
        })]));
    }

    let mut result = Vec::new();
    for (backend, name) in backends.iter().zip(names.iter()) {
        let mut rec = std::collections::BTreeMap::new();
        rec.insert("name".to_string(), Value::Str(name.to_string()));
        rec.insert(
            "loaded_models".to_string(),
            Value::Array(
                backend
                    .loaded_models()
                    .into_iter()
                    .map(Value::Str)
                    .collect(),
            ),
        );
        let formats: Vec<&str> = ["gguf", "safetensors", "onnx", "pt", "bin"]
            .iter()
            .copied()
            .filter(|ext| backend.supports_format(ext))
            .collect();
        rec.insert(
            "formats".to_string(),
            Value::Array(
                formats
                    .into_iter()
                    .map(|f| Value::Str(f.to_string()))
                    .collect(),
            ),
        );
        result.push(Value::Record(rec));
    }

    Ok(Value::Array(result))
}

/// ai_local_load(path) - Load a local model file into an inference backend
/// Returns: Record with handle, backend name, and estimated memory
///
/// Example:
///   ai_local_load("models/llama-3.2-1b-q4_k_m.gguf")
fn bi_ai_local_load(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::local_inference;
    const B: &str = "ai_local_load";
    refuse_piped(B, &input)?;
    let path = sole_str(B, &args, "a model file path string")?;

    let backend = local_inference::backend_for_model(&path).ok_or_else(|| {
        crate::safety::unimplemented(
            B,
            &format!(
                "no compiled-in backend supports this model format (available: {:?})",
                local_inference::backend_names()
            ),
            "rebuild with --features candle (for .gguf/.safetensors) or --features onnx (for .onnx)",
        )
    })?;

    let mut rec = std::collections::BTreeMap::new();
    // A memory estimate the backend cannot make is unknown, and the reason is
    // reported with it. It is not zero MB.
    match backend.estimate_memory_mb(&path) {
        Ok(mb) => {
            rec.insert("estimated_memory_mb".to_string(), Value::Int(mb as i64));
        }
        Err(e) => {
            rec.insert("estimated_memory_mb".to_string(), Value::Null);
            rec.insert("estimate_error".to_string(), Value::Str(e.to_string()));
        }
    }
    // A backend's coded refusal (an unsupported architecture, say) and a
    // file it cannot open keep their own codes; only what is left is read as
    // a file the backend cannot load.
    let handle = backend.load_model(&path).map_err(|e| {
        if e.downcast_ref::<crate::safety::SafetyError>().is_some() {
            return e;
        }
        if let Some(io) = e.downcast_ref::<std::io::Error>() {
            return crate::safety::fs_error(B, &path, io);
        }
        crate::safety::bad_arg(B, "a model file the backend can load", &e.to_string())
    })?;

    rec.insert("handle".to_string(), Value::Str(handle));
    rec.insert(
        "backend".to_string(),
        Value::Str(backend.name().to_string()),
    );
    rec.insert("path".to_string(), Value::Str(path));

    Ok(Value::Record(rec))
}

/// The prompt `ai_local_generate` was given: text for the backend's `generate`,
/// or chat messages for its `chat`.
enum GeneratePrompt {
    Text(String),
    Chat(Vec<crate::local_inference::ChatMessage>),
}

/// What `ai_local_generate` takes as its prompt, for a refusal to quote.
const GENERATE_PROMPT_EXPECTED: &str = "prompt: a String, or an Array of {role, content} messages";

/// The messages of a chat prompt: an Array of Records with exactly `role` and
/// `content`, both Strings, and a role of system, user, assistant or tool. Every
/// message is checked here, before a backend is looked up, so a malformed
/// conversation is refused the same way whichever model it names.
fn chat_messages_arg(
    builtin: &str,
    items: &[Value],
) -> Result<Vec<crate::local_inference::ChatMessage>> {
    if items.is_empty() {
        return Err(crate::safety::bad_arg(
            builtin,
            GENERATE_PROMPT_EXPECTED,
            "an empty Array",
        ));
    }
    let mut messages = Vec::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        let n = i + 1;
        let Value::Record(rec) = item else {
            return Err(crate::safety::bad_arg(
                builtin,
                GENERATE_PROMPT_EXPECTED,
                &format!("message {n} of type {}", item.type_name()),
            ));
        };
        if rec.len() != 2 || !rec.contains_key("role") || !rec.contains_key("content") {
            let fields: Vec<&str> = rec.keys().map(String::as_str).collect();
            return Err(crate::safety::bad_arg(
                builtin,
                GENERATE_PROMPT_EXPECTED,
                &format!("message {n} with fields {fields:?}"),
            ));
        }
        let (role, content) = match (rec.get("role"), rec.get("content")) {
            (Some(Value::Str(role)), Some(Value::Str(content))) => (role, content),
            _ => {
                return Err(crate::safety::bad_arg(
                    builtin,
                    GENERATE_PROMPT_EXPECTED,
                    &format!("message {n} whose role and content are not both Strings"),
                ))
            }
        };
        if !matches!(role.as_str(), "system" | "user" | "assistant" | "tool") {
            return Err(crate::safety::bad_arg(
                builtin,
                GENERATE_PROMPT_EXPECTED,
                &format!("message {n} with role {role:?}"),
            ));
        }
        messages.push(crate::local_inference::ChatMessage {
            role: role.clone(),
            content: content.clone(),
        });
    }
    Ok(messages)
}

/// ai_local_generate(handle, prompt, params?) - Generate text using a loaded local model
/// The prompt is a String, sent as is, or an Array of {role, content} messages
/// (role: system, user, assistant or tool). A messages Array is formatted by the
/// model's own chat template, and a model with no chat template refuses it.
/// Returns: Record with generated text, token counts, and performance metrics
///
/// Example:
///   ai_local_generate("candle:llama", "What is Rust?")
///   ai_local_generate("candle:llama", [{role: "user", content: "What is Rust?"}])
///   ai_local_generate("candle:llama", "Hello", {max_tokens: 100, temperature: 0.5})
fn bi_ai_local_generate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::local_inference::{self, GenerationParams};
    const B: &str = "ai_local_generate";
    refuse_piped(B, &input)?;

    let handle = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "ai_local_generate: requires handle string as first argument",
            ))
        }
    };

    let prompt = match args.get(1) {
        Some(Value::Str(s)) => GeneratePrompt::Text(s.clone()),
        Some(Value::Array(items)) => GeneratePrompt::Chat(chat_messages_arg(B, items)?),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                B,
                GENERATE_PROMPT_EXPECTED,
                other.type_name(),
            ))
        }
        None => {
            return Err(crate::safety::arg_err(
                "ai_local_generate: requires prompt as second argument",
            ))
        }
    };

    let mut params = GenerationParams::default();
    match args.get(2) {
        None => {}
        Some(Value::Record(r)) => {
            cfg_known_keys(
                B,
                r,
                &[
                    "max_tokens",
                    "temperature",
                    "top_p",
                    "repetition_penalty",
                    "seed",
                ],
            )?;
            if let Some(n) = cfg_int(B, r, "max_tokens", 1, u32::MAX as i64)? {
                params.max_tokens = n as u32;
            }
            if let Some(t) = cfg_float(B, r, "temperature", 0.0, f64::MAX)? {
                params.temperature = t;
            }
            if let Some(p) = cfg_float(B, r, "top_p", 0.0, 1.0)? {
                params.top_p = p;
            }
            if let Some(p) = cfg_float(B, r, "repetition_penalty", f64::MIN_POSITIVE, f64::MAX)? {
                params.repetition_penalty = p;
            }
            if let Some(s) = cfg_int(B, r, "seed", 0, i64::MAX)? {
                params.seed = Some(s as u64);
            }
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                B,
                "params: a record {max_tokens?, temperature?, top_p?, repetition_penalty?, seed?}",
                other.type_name(),
            ))
        }
    }

    // Find the right backend from the handle prefix
    for backend in local_inference::available_backends() {
        if handle.starts_with(&format!("{}:", backend.name())) {
            let result = match &prompt {
                GeneratePrompt::Text(text) => backend.generate(&handle, text, &params)?,
                GeneratePrompt::Chat(messages) => backend.chat(&handle, messages, &params)?,
            };
            let mut rec = std::collections::BTreeMap::new();
            rec.insert("text".to_string(), Value::Str(result.text));
            rec.insert(
                "prompt_tokens".to_string(),
                Value::Int(result.prompt_tokens as i64),
            );
            rec.insert(
                "completion_tokens".to_string(),
                Value::Int(result.completion_tokens as i64),
            );
            rec.insert(
                "generation_ms".to_string(),
                Value::Float(result.generation_ms),
            );
            rec.insert(
                "tokens_per_second".to_string(),
                Value::Float(result.tokens_per_second),
            );
            rec.insert(
                "backend".to_string(),
                Value::Str(backend.name().to_string()),
            );
            return Ok(Value::Record(rec));
        }
    }

    // Nothing in-process can serve this handle. Before failing, try the
    // gateway: in this stack "local inference" means IronWorks behind IronGate,
    // and a build with neither `candle` nor `onnx` compiled in — which is the
    // default build — has no in-process backend at all. Treat the handle as the
    // model name and let the gateway route it.
    // The gateway takes a prompt string, so messages have no route through it.
    let prompt = match prompt {
        GeneratePrompt::Text(text) => text,
        GeneratePrompt::Chat(_) if crate::model_plane::gate_available() => {
            return Err(crate::safety::unimplemented(
                B,
                "chat messages through IronGate",
                "pass a prompt string",
            ))
        }
        GeneratePrompt::Chat(_) => {
            return Err(crate::safety::not_found(B, "local model handle", &handle))
        }
    };
    if crate::model_plane::gate_available() {
        let max_tokens = Some(params.max_tokens);
        let done = crate::model_plane::gate_complete(&handle, &prompt, max_tokens)?;
        let mut rec = std::collections::BTreeMap::new();
        rec.insert("text".to_string(), Value::Str(done.text));
        rec.insert(
            "prompt_tokens".to_string(),
            Value::Int(done.prompt_tokens as i64),
        );
        rec.insert(
            "completion_tokens".to_string(),
            Value::Int(done.completion_tokens as i64),
        );
        rec.insert("generation_ms".to_string(), Value::Float(done.elapsed_ms));
        rec.insert(
            "tokens_per_second".to_string(),
            Value::Float(if done.elapsed_ms > 0.0 {
                done.completion_tokens as f64 / (done.elapsed_ms / 1000.0)
            } else {
                0.0
            }),
        );
        // Which engine answered is part of the answer here: the same call can
        // be served in-process or by a machine across the network, and a caller
        // comparing timings needs to know which.
        rec.insert(
            "backend".to_string(),
            Value::Str(done.target.unwrap_or_else(|| "irongate".to_string())),
        );
        return Ok(Value::Record(rec));
    }

    Err(crate::safety::not_found(B, "local model handle", &handle))
}

/// ai_local_embed(handle, inputs) - Generate embeddings using a loaded local model
/// Returns: Record with embeddings array and token count
///
/// Example:
///   ai_local_embed("candle:embed-model", ["Hello world", "Rust is great"])
fn bi_ai_local_embed(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::local_inference;
    const B: &str = "ai_local_embed";
    refuse_piped(B, &input)?;

    let handle = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "ai_local_embed: requires handle string as first argument",
            ))
        }
    };

    // Every element must be a string. The earlier code rendered a number or a
    // record with to_string and embedded that text, which is a different call.
    let inputs: Vec<String> = match args.get(1) {
        Some(Value::Array(arr)) if arr.is_empty() => {
            return Err(crate::safety::bad_arg(
                B,
                "inputs: at least one string",
                "an empty array",
            ))
        }
        Some(Value::Array(arr)) => arr
            .iter()
            .map(|v| match v {
                Value::Str(s) => Ok(s.clone()),
                other => Err(crate::safety::bad_arg(
                    B,
                    "inputs: an array of strings",
                    other.type_name(),
                )),
            })
            .collect::<Result<Vec<String>>>()?,
        Some(Value::Str(s)) => vec![s.clone()],
        _ => {
            return Err(crate::safety::arg_err(
                "ai_local_embed: requires input string or array of strings",
            ))
        }
    };

    for backend in local_inference::available_backends() {
        if handle.starts_with(&format!("{}:", backend.name())) {
            let result = backend.embed(&handle, &inputs)?;
            let mut rec = std::collections::BTreeMap::new();
            rec.insert(
                "embeddings".to_string(),
                Value::Array(
                    result
                        .embeddings
                        .into_iter()
                        .map(|emb| {
                            Value::Array(emb.into_iter().map(|f| Value::Float(f as f64)).collect())
                        })
                        .collect(),
                ),
            );
            rec.insert(
                "total_tokens".to_string(),
                Value::Int(result.total_tokens as i64),
            );
            return Ok(Value::Record(rec));
        }
    }

    Err(crate::safety::not_found(B, "local model handle", &handle))
}

/// ai_local_unload(handle) - Unload a previously loaded local model
/// Returns: String confirmation
///
/// Example:
///   ai_local_unload("candle:llama")
fn bi_ai_local_unload(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::local_inference;
    const B: &str = "ai_local_unload";
    refuse_piped(B, &input)?;
    let handle = sole_str(B, &args, "a handle string")?;

    for backend in local_inference::available_backends() {
        if handle.starts_with(&format!("{}:", backend.name())) {
            backend.unload_model(&handle)?;
            return Ok(Value::Str(format!("Model '{}' unloaded", handle)));
        }
    }

    Err(crate::safety::not_found(B, "local model handle", &handle))
}

// ========== Runtime Type Introspection ==========

/// typeof(value) - Get the runtime type name of a value
/// Returns: String with the type name
///
/// Example:
///   typeof(42)              # => "Int"
///   typeof("hello")         # => "String"
///   typeof([1,2])           # => "Array"
///   typeof({a: 1})          # => "Record"
///   42 | typeof()           # => "Int"
fn bi_typeof(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input) = input {
        input
    } else if let Some(v) = args.first() {
        v.clone()
    } else {
        return Err(crate::safety::arg_err(
            "typeof: requires a value (argument or piped input)",
        ));
    };

    Ok(Value::Str(val.type_name().to_string()))
}

/// type_name(value) - Get detailed type description with inner types
/// Returns: String with detailed type info
///
/// Example:
///   type_name([1,2,3])       # => "Array<Int>"
///   type_name({a: 1, b: "x"})  # => "Record{a: Int, b: String}"
fn bi_type_name(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input) = input {
        input
    } else if let Some(v) = args.first() {
        v.clone()
    } else {
        return Err(crate::safety::arg_err("type_name: requires a value"));
    };

    let type_desc = detailed_type_name(&val);
    Ok(Value::Str(type_desc))
}

fn detailed_type_name(val: &Value) -> String {
    match val {
        Value::Int(_) => "Int".into(),
        Value::Float(_) => "Float".into(),
        Value::Str(_) => "String".into(),
        Value::Bool(_) => "Bool".into(),
        Value::Null => "Null".into(),
        Value::Uri(_) => "Uri".into(),
        Value::Error(e) => format!("Error({})", e),
        Value::Builtin(b) => format!("Builtin({})", b.name),
        Value::AsyncLambda(al) => format!("AsyncLambda({})", al.params.len()),
        Value::Future(_) => "Future".into(),
        Value::Array(items) => {
            if items.is_empty() {
                "Array<Any>".into()
            } else {
                let inner = detailed_type_name(&items[0]);
                format!("Array<{}>", inner)
            }
        }
        Value::Record(fields) => {
            let parts: Vec<String> = fields
                .iter()
                .take(6)
                .map(|(k, v)| format!("{}: {}", k, detailed_type_name(v)))
                .collect();
            let suffix = if fields.len() > 6 { ", …" } else { "" };
            format!("Record{{{}{}}}", parts.join(", "), suffix)
        }
        Value::Lambda(l) => format!("Lambda({})", l.params.len()),
        Value::Table(t) => {
            format!("Table({} cols, {} rows)", t.schema.len(), t.rows.len())
        }
    }
}

/// type_fields(record) - Get the field names and types of a record
/// Returns: Array of records with name, type, value_preview
///
/// Example:
///   type_fields({name: "ae", version: 3, active: true})
fn bi_type_fields(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input) = input {
        input
    } else if let Some(v) = args.first() {
        v.clone()
    } else {
        return Err(crate::safety::arg_err(
            "type_fields: requires a record value",
        ));
    };

    match val {
        Value::Record(fields) => {
            let result: Vec<Value> = fields
                .iter()
                .map(|(name, value)| {
                    let mut r = std::collections::BTreeMap::new();
                    r.insert("name".to_string(), Value::Str(name.clone()));
                    r.insert("type".to_string(), Value::Str(detailed_type_name(value)));
                    // Brief preview of value
                    let preview = match value {
                        Value::Str(s) if s.chars().nth(50).is_some() => {
                            format!("\"{}…\"", s.chars().take(50).collect::<String>())
                        }
                        Value::Array(a) => format!("[…] ({} items)", a.len()),
                        Value::Record(r) => format!("{{…}} ({} fields)", r.len()),
                        Value::Str(s) => format!("\"{s}\""),
                        other => other.to_display_string(),
                    };
                    r.insert("preview".to_string(), Value::Str(preview));
                    Value::Record(r)
                })
                .collect();
            Ok(Value::Array(result))
        }
        Value::Table(t) => {
            let result: Vec<Value> = t
                .schema
                .iter()
                .map(|h| {
                    let mut r = std::collections::BTreeMap::new();
                    r.insert("name".to_string(), Value::Str(h.clone()));
                    r.insert("type".to_string(), Value::Str("Any".to_string()));
                    r.insert("preview".to_string(), Value::Str("(column)".to_string()));
                    Value::Record(r)
                })
                .collect();
            Ok(Value::Array(result))
        }
        _ => Err(crate::safety::bad_arg(
            "type_fields",
            "a Record or Table",
            &detailed_type_name(&val),
        )),
    }
}

/// type_schema(value) - Generate a JSON Schema for a value's structure
/// Returns: Record representing a JSON Schema
///
/// Example:
///   type_schema({name: "ae", version: 3})
///   # => {type: "object", properties: {name: {type: "string"}, version: {type: "integer"}}}
fn bi_type_schema(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if let Some(input) = input {
        input
    } else if let Some(v) = args.first() {
        v.clone()
    } else {
        return Err(crate::safety::arg_err("type_schema: requires a value"));
    };

    let schema = value_to_json_schema(&val);
    Ok(Value::from_json(&schema))
}

fn value_to_json_schema(val: &Value) -> serde_json::Value {
    use serde_json::json;
    match val {
        Value::Int(_) => json!({"type": "integer"}),
        Value::Float(_) => json!({"type": "number"}),
        Value::Str(_) => json!({"type": "string"}),
        Value::Bool(_) => json!({"type": "boolean"}),
        Value::Null => json!({"type": "null"}),
        Value::Uri(_) => json!({"type": "string", "format": "uri"}),
        Value::Error(_) => json!({"type": "string", "description": "error"}),
        Value::Builtin(_) => json!({"type": "string", "description": "builtin reference"}),
        Value::AsyncLambda(_) => json!({"type": "function", "async": true}),
        Value::Future(_) => json!({"type": "object", "description": "future"}),
        Value::Array(items) => {
            if items.is_empty() {
                json!({"type": "array", "items": {}})
            } else {
                let item_schema = value_to_json_schema(&items[0]);
                json!({"type": "array", "items": item_schema})
            }
        }
        Value::Record(fields) => {
            let mut properties = serde_json::Map::new();
            let required: Vec<String> = fields.keys().cloned().collect();
            for (k, v) in fields {
                properties.insert(k.clone(), value_to_json_schema(v));
            }
            json!({
                "type": "object",
                "properties": serde_json::Value::Object(properties),
                "required": required,
            })
        }
        Value::Lambda(l) => {
            json!({"type": "function", "parameters": l.params.len()})
        }
        Value::Table(t) => {
            let mut properties = serde_json::Map::new();
            for h in &t.schema {
                properties.insert(h.clone(), json!({}));
            }
            json!({
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": serde_json::Value::Object(properties),
                }
            })
        }
    }
}

/// is_type(value, type_name) - Check if a value matches a type name
/// Returns: Bool
///
/// Example:
///   is_type(42, "Int")       # => true
///   is_type("hi", "String")  # => true
///   is_type([], "Array")     # => true
fn bi_is_type(args: Vec<Value>) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "is_type: requires (value, type_name) arguments",
        ));
    }
    let type_name = match &args[1] {
        Value::Str(s) => s.to_lowercase(),
        other => {
            return Err(crate::safety::bad_arg(
                "is_type",
                "type_name: String",
                other.type_name(),
            ))
        }
    };

    let matches = match (&args[0], type_name.as_str()) {
        (Value::Int(_), "int" | "integer" | "number") => true,
        (Value::Float(_), "float" | "number" | "double") => true,
        (Value::Str(_), "string" | "str" | "text") => true,
        (Value::Bool(_), "bool" | "boolean") => true,
        (Value::Array(_), "array" | "list") => true,
        (Value::Record(_), "record" | "object" | "map") => true,
        (Value::Uri(_), "uri" | "url") => true,
        (Value::Lambda(_), "lambda" | "function" | "fn") => true,
        (Value::AsyncLambda(_), "asynclambda" | "async_lambda" | "function" | "fn") => true,
        (Value::Null, "null" | "nil" | "none") => true,
        (Value::Table(_), "table") => true,
        (Value::Error(_), "error") => true,
        (Value::Future(_), "future") => true,
        (Value::Builtin(_), "builtin") => true,
        (_, "any") => true,
        _ => false,
    };

    Ok(Value::Bool(matches))
}

// ========== Ontology Export Functions ==========

/// ontology_json() - Export the OS ontology as JSON Schema
/// Returns: Record with the full JSON Schema representation
fn bi_ontology_json() -> Result<Value> {
    let schema = crate::providers::ontology::OS_ONTOLOGY.to_json_schema();
    Ok(Value::from_json(&schema))
}

/// ontology_jsonld() - Export the OS ontology as JSON-LD (Linked Data)
/// Returns: Record with JSON-LD representation for semantic web
fn bi_ontology_jsonld() -> Result<Value> {
    let ld = crate::providers::ontology::OS_ONTOLOGY.to_json_ld();
    Ok(Value::from_json(&ld))
}

/// ontology_owl() - Export the OS ontology as OWL/RDF Turtle format
/// Returns: String with OWL Turtle serialization
fn bi_ontology_owl() -> Result<Value> {
    let turtle = crate::providers::ontology::OS_ONTOLOGY.to_owl_turtle();
    Ok(Value::Str(turtle))
}

/// ontology_shacl() - Export the OS ontology as SHACL shapes for validation
/// Returns: Record with SHACL shapes graph
fn bi_ontology_shacl() -> Result<Value> {
    let shacl = crate::providers::ontology::OS_ONTOLOGY.to_shacl();
    Ok(Value::from_json(&shacl))
}

// ========== MCP Server Detection Functions ==========

/// mcp_servers() - Detect all available MCP servers
/// Returns: Array of records with MCP server information
///
/// Each record contains:
///   - name: String - Server name (e.g., "filesystem", "git")
///   - endpoint: String - Server endpoint URL
///   - available: Bool - Whether server is reachable
///   - tools: Array[String] - List of available tool names
///
/// Example:
///   let servers = mcp_servers()
///   servers | foreach(fn(s) => print(s.name + ": " + str(len(s.tools)) + " tools"))
fn mcp_server_record(server: &crate::ai::McpServerInfo) -> Value {
    let mut record = BTreeMap::new();
    record.insert("name".to_string(), Value::Str(server.name.clone()));
    record.insert("endpoint".to_string(), Value::Str(server.endpoint.clone()));
    record.insert("available".to_string(), Value::Bool(server.available));
    let tools: Vec<Value> = server.tools.iter().map(|t| Value::Str(t.clone())).collect();
    record.insert("tools".to_string(), Value::Array(tools));
    Value::Record(record)
}

fn bi_mcp_servers(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("mcp_servers", &input)?;
    let servers = crate::ai::detect_mcp_servers();
    Ok(Value::Array(
        servers.iter().map(mcp_server_record).collect(),
    ))
}

/// mcp_detect(endpoint?) - Detect MCP server at specific endpoint or find first available
/// Args:
///   - endpoint (optional): String - Specific endpoint to check
/// Returns: Record with MCP server info, or null when no detected server matches
///
/// Null is the answer for "nothing is listening" (`examples/22_tui_mcp.ish`
/// relies on it); a found server is a full record.
///
/// Example:
///   let fs_server = mcp_detect("http://localhost:3001")
///   let any_server = mcp_detect()
fn bi_mcp_detect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("mcp_detect", &input)?;
    let servers = crate::ai::detect_mcp_servers();
    match args.first() {
        Some(v) => {
            let endpoint = expect_string("mcp_detect", v)?;
            Ok(servers
                .iter()
                .find(|s| s.endpoint == endpoint)
                .map(mcp_server_record)
                .unwrap_or(Value::Null))
        }
        None => Ok(servers
            .first()
            .map(mcp_server_record)
            .unwrap_or(Value::Null)),
    }
}

/// mcp_cache_clear() - Clear the MCP detection cache
/// Returns: Bool - true if cache was cleared successfully
///
/// Example:
///   mcp_cache_clear()
///   let servers = mcp_servers()  # This will re-detect servers
fn bi_mcp_cache_clear(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("mcp_cache_clear", &input)?;
    // A failed clear used to be `let _ =`, and `true` came back regardless.
    crate::ai::clear_mcp_cache().map_err(|e| {
        crate::safety::bad_state_with_hint(
            "mcp_cache_clear",
            &format!("the MCP cache could not be cleared: {e}"),
            "a new ish process",
        )
    })?;
    Ok(Value::Bool(true))
}

/// mcp_cache_status() - Get MCP cache status information
/// Returns: Record with cache status details
///
/// Example:
///   let status = mcp_cache_status()
///   print("Cache TTL: " + status.ttl_seconds)
fn bi_mcp_cache_status(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("mcp_cache_status", &input)?;
    let mut record = BTreeMap::new();

    // The cache is always on, and its TTL is the one `detect_mcp_servers` uses.
    record.insert("enabled".to_string(), Value::Bool(true));
    record.insert("ttl_seconds".to_string(), Value::Int(30));

    // A poisoned lock used to read as "no cached data": a failure to look was
    // reported as an empty cache.
    let has_cached_data = match crate::ai::MCP_CACHE.lock() {
        Ok(cache_guard) => cache_guard.is_some(),
        Err(_) => {
            return Err(crate::safety::bad_state_with_hint(
                "mcp_cache_status",
                "the MCP cache lock is poisoned by an earlier panic",
                "a new ish process",
            ))
        }
    };
    record.insert("has_cached_data".to_string(), Value::Bool(has_cached_data));

    Ok(Value::Record(record))
}

// ==================== MCP Server/Client Functions ====================

/// Helper function to map category strings to ToolCategory enum
fn parse_tool_category(s: &str) -> Option<crate::os_tools::ToolCategory> {
    use crate::os_tools::ToolCategory;
    match s.to_lowercase().as_str() {
        "filesystem" | "file_system" => Some(ToolCategory::FileSystem),
        "textprocessing" | "text_processing" | "text" => Some(ToolCategory::TextProcessing),
        "networktools" | "network_tools" | "network" => Some(ToolCategory::NetworkTools),
        "systeminfo" | "system_info" | "system" => Some(ToolCategory::SystemInfo),
        "processmanagement" | "process_management" | "process" => {
            Some(ToolCategory::ProcessManagement)
        }
        "archives" | "archive" => Some(ToolCategory::Archives),
        "searchtools" | "search_tools" | "search" => Some(ToolCategory::SearchTools),
        "monitoring" => Some(ToolCategory::Monitoring),
        "development" | "dev" => Some(ToolCategory::Development),
        "media" => Some(ToolCategory::Media),
        "security" => Some(ToolCategory::Security),
        "utilities" | "util" => Some(ToolCategory::Utilities),
        "webtools" | "web_tools" | "web" => Some(ToolCategory::WebTools),
        "cybersecurity" | "cyber_security" | "cyber" => Some(ToolCategory::CyberSecurity),
        "reconnaissance" | "recon" => Some(ToolCategory::Reconnaissance),
        "forensics" => Some(ToolCategory::Forensics),
        "cryptography" | "crypto" => Some(ToolCategory::Cryptography),
        "cloudaws" | "cloud_aws" | "aws" => Some(ToolCategory::CloudAWS),
        "cloudazure" | "cloud_azure" | "azure" => Some(ToolCategory::CloudAzure),
        "cloudgcp" | "cloud_gcp" | "gcp" => Some(ToolCategory::CloudGCP),
        "kubernetes" | "k8s" => Some(ToolCategory::Kubernetes),
        "containers" | "docker" | "podman" => Some(ToolCategory::Containers),
        "infrastructure" | "terraform" | "ansible" => Some(ToolCategory::Infrastructure),
        "database" | "db" => Some(ToolCategory::Database),
        "dataprocessing" | "data_processing" | "data" => Some(ToolCategory::DataProcessing),
        "machinelearning" | "machine_learning" | "ml" => Some(ToolCategory::MachineLearning),
        _ => None,
    }
}

/// mcp_server(config?) - Create a local MCP server instance for AI tool access
/// Args:
///   - config (optional): Record with configuration options
///     - max_safety_level: String - "safe", "caution", "dangerous", "critical" (default: "caution")
///     - allow_admin: Bool - Allow admin tools (default: false)
///     - categories: Array[String] - Limit to specific tool categories (default: all)
///     - blocked_tools: Array[String] - Tools to block (default: [])
/// Returns: Record with MCP server information
///
/// Example:
///   let server = mcp_server()
///   let safe_server = mcp_server({ max_safety_level: "safe" })
///   let k8s_server = mcp_server({ categories: ["kubernetes", "containers"] })
fn bi_mcp_server(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    use crate::mcp::{McpConfig, McpServer};
    use crate::os_tools::SafetyLevel;

    // Parse config from args
    let mut config = McpConfig::default();
    let mut allowed_categories = None;

    if !args.is_empty() {
        if let Value::Record(rec) = &args[0] {
            // Parse safety level
            if let Some(Value::Str(level)) = rec.get("max_safety_level") {
                config.max_safety_level = match level.to_lowercase().as_str() {
                    "safe" => SafetyLevel::Safe,
                    "caution" => SafetyLevel::Caution,
                    "dangerous" => SafetyLevel::Dangerous,
                    "critical" => SafetyLevel::Critical,
                    // An unknown level ("dangerus") silently became Caution.
                    other => {
                        return Err(crate::safety::bad_arg(
                            "mcp_server",
                            "max_safety_level safe, caution, dangerous or critical",
                            other,
                        ))
                    }
                };
            }

            // Parse allow_admin
            if let Some(Value::Bool(b)) = rec.get("allow_admin") {
                config.allow_admin_tools = *b;
            }

            // Parse blocked_tools
            if let Some(Value::Array(arr)) = rec.get("blocked_tools") {
                config.blocked_tools = arr
                    .iter()
                    .filter_map(|v| {
                        if let Value::Str(s) = v {
                            Some(s.clone())
                        } else {
                            None
                        }
                    })
                    .collect();
            }

            // Parse categories
            if let Some(Value::Array(arr)) = rec.get("categories") {
                let cats: Vec<_> = arr
                    .iter()
                    .filter_map(|v| {
                        if let Value::Str(s) = v {
                            parse_tool_category(s)
                        } else {
                            None
                        }
                    })
                    .collect();
                if !cats.is_empty() {
                    allowed_categories = Some(cats);
                }
            }
        }
    }

    // Set allowed_categories in config
    config.allowed_categories = allowed_categories;

    // Create MCP server
    let server = McpServer::with_config(config);
    let init_result = server.initialize();

    // Return server info as record
    let mut record = BTreeMap::new();
    record.insert(
        "protocol_version".to_string(),
        Value::Str(init_result.protocol_version),
    );
    record.insert(
        "server_name".to_string(),
        Value::Str(init_result.server_info.name),
    );
    record.insert(
        "server_version".to_string(),
        Value::Str(init_result.server_info.version),
    );
    record.insert(
        "tool_count".to_string(),
        Value::Int(server.list_tools().len() as i64),
    );

    let capabilities: Vec<Value> = vec![
        Value::Str("tools".to_string()),
        Value::Str("resources".to_string()),
        Value::Str("prompts".to_string()),
    ];
    record.insert("capabilities".to_string(), Value::Array(capabilities));

    Ok(Value::Record(record))
}

/// mcp_tools(config?) - List available MCP tools with their schemas
/// Args:
///   - config (optional): Record with filter options
///     - category: String - Filter by category
///     - search: String - Search by name/description
///     - safety_level: String - Max safety level
/// Returns: Array of tool records with name, description, and input schema
///
/// Example:
///   let all_tools = mcp_tools()
///   let k8s_tools = mcp_tools({ category: "kubernetes" })
///   let git_tools = mcp_tools({ search: "git" })
fn bi_mcp_tools(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::mcp::{McpConfig, McpServer};
    use crate::os_tools::SafetyLevel;

    refuse_piped("mcp_tools", &input)?;

    // Parse filters. A filter that is not understood is refused: an unknown
    // category used to list every tool, and an unknown safety level used to
    // mean Caution, both without a word.
    let mut config = McpConfig::default();
    let mut search_filter: Option<String> = None;

    if let Some(first) = args.first() {
        let Value::Record(rec) = first else {
            return Err(crate::safety::bad_arg(
                "mcp_tools",
                "config: Record",
                first.type_name(),
            ));
        };
        for key in rec.keys() {
            if !matches!(key.as_str(), "category" | "search" | "safety_level") {
                return Err(crate::safety::bad_arg(
                    "mcp_tools",
                    "config keys category, search, safety_level",
                    key,
                ));
            }
        }

        // Parse category filter
        if let Some(v) = rec.get("category") {
            let cat_str = expect_string("mcp_tools", v)?;
            let cat = parse_tool_category(cat_str)
                .ok_or_else(|| crate::safety::bad_arg("mcp_tools", "a known category", cat_str))?;
            config.allowed_categories = Some(vec![cat]);
        }

        // Parse search filter
        if let Some(v) = rec.get("search") {
            search_filter = Some(expect_string("mcp_tools", v)?.to_string());
        }

        // Parse safety level
        if let Some(v) = rec.get("safety_level") {
            let level = expect_string("mcp_tools", v)?;
            config.max_safety_level = match level.to_lowercase().as_str() {
                "safe" => SafetyLevel::Safe,
                "caution" => SafetyLevel::Caution,
                "dangerous" => SafetyLevel::Dangerous,
                "critical" => SafetyLevel::Critical,
                _ => {
                    return Err(crate::safety::bad_arg(
                        "mcp_tools",
                        "safety_level safe, caution, dangerous or critical",
                        level,
                    ))
                }
            };
        }
    }

    let server = McpServer::with_config(config);
    let tools = server.list_tools();

    // Apply search filter
    let filtered_tools: Vec<_> = if let Some(ref search) = search_filter {
        let search_lower = search.to_lowercase();
        tools
            .into_iter()
            .filter(|t| {
                t.name.to_lowercase().contains(&search_lower)
                    || t.description.to_lowercase().contains(&search_lower)
            })
            .collect()
    } else {
        tools
    };

    let tool_records: Vec<Value> = filtered_tools
        .into_iter()
        .map(|tool| {
            let mut rec = BTreeMap::new();
            rec.insert("name".to_string(), Value::Str(tool.name));
            rec.insert("description".to_string(), Value::Str(tool.description));
            rec.insert(
                "input_schema".to_string(),
                Value::Str(tool.input_schema.to_string()),
            );
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(tool_records))
}

/// mcp_call(name, args?) - Call an MCP tool by name with arguments
/// Args:
///   - name: String - Tool name to call
///   - args (optional): Record - Arguments for the tool
/// Returns: Record with result content or error
///
/// Example:
///   let result = mcp_call("ls", { path: "." })
///   let files = mcp_call("find", { directory: "/home", pattern: "*.rs" })
fn bi_mcp_call(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::mcp::{McpContent, McpServer, McpToolCall};
    use std::collections::HashMap;

    refuse_piped("mcp_call", &input)?;

    let Some(first) = args.first() else {
        return Err(crate::safety::bad_arg(
            "mcp_call",
            "a tool name as the first argument",
            "nothing",
        ));
    };
    let tool_name = expect_string("mcp_call", first)?;

    // Build arguments HashMap. A non-record second argument used to be dropped
    // and the tool run without its arguments.
    let tool_args: HashMap<String, serde_json::Value> = match args.get(1) {
        None => HashMap::new(),
        Some(Value::Record(rec)) => rec
            .iter()
            .map(|(k, v)| (k.clone(), value_to_json_owned(v.clone())))
            .collect(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "mcp_call",
                "args: Record",
                other.type_name(),
            ))
        }
    };

    let server = McpServer::new();
    // An unknown tool used to come back as a record with is_error set.
    if server.get_tool(tool_name).is_none() {
        if server.tools_db().get_tool(tool_name).is_some() {
            return Err(crate::safety::policy_deny(
                "mcp_call",
                format!("tool `{tool_name}` is not available under the default MCP policy"),
                "the tool is blocked or above the default safety level",
            ));
        }
        return Err(crate::safety::not_found("mcp_call", "tool", tool_name));
    }

    let call = McpToolCall {
        name: tool_name.to_string(),
        arguments: tool_args,
    };

    let result = server.call_tool(call);

    // A tool that failed is a coded tool failure, not a record the caller has
    // to remember to check.
    if result.is_error == Some(true) {
        let text: Vec<&str> = result
            .content
            .iter()
            .filter_map(|c| match c {
                McpContent::Text { text } => Some(text.as_str()),
                _ => None,
            })
            .collect();
        return Err(mcp_tool_failed(tool_name, &text.join("\n")));
    }

    let mut record = BTreeMap::new();
    record.insert(
        "is_error".to_string(),
        Value::Bool(result.is_error.unwrap_or(false)),
    );

    let content_values: Vec<Value> = result
        .content
        .into_iter()
        .map(|c| {
            let mut content_rec = BTreeMap::new();
            match c {
                McpContent::Text { text } => {
                    content_rec.insert("type".to_string(), Value::Str("text".to_string()));
                    content_rec.insert("text".to_string(), Value::Str(text));
                }
                McpContent::Image { data, mime_type } => {
                    content_rec.insert("type".to_string(), Value::Str("image".to_string()));
                    content_rec.insert("data".to_string(), Value::Str(data));
                    content_rec.insert("mime_type".to_string(), Value::Str(mime_type));
                }
                McpContent::Resource { uri, mime_type } => {
                    content_rec.insert("type".to_string(), Value::Str("resource".to_string()));
                    content_rec.insert("uri".to_string(), Value::Str(uri));
                    if let Some(mt) = mime_type {
                        content_rec.insert("mime_type".to_string(), Value::Str(mt));
                    }
                }
            }
            Value::Record(content_rec)
        })
        .collect();
    record.insert("content".to_string(), Value::Array(content_values));

    Ok(Value::Record(record))
}

/// mcp_resources(type?) - List available MCP resources
/// Args:
///   - type (optional): String - Filter by resource type ("text", "blob", etc.)
/// Returns: Array of resource records
///
/// Example:
///   let resources = mcp_resources()
///   let text_resources = mcp_resources("text")
fn bi_mcp_resources(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    use crate::mcp::McpServer;

    let type_filter = if !args.is_empty() {
        if let Value::Str(s) = &args[0] {
            Some(s.clone())
        } else {
            None
        }
    } else {
        None
    };

    let server = McpServer::new();
    let resources = server.list_resources();

    let filtered: Vec<_> = if let Some(ref t) = type_filter {
        resources
            .into_iter()
            .filter(|r| r.mime_type.as_ref().map(|m| m.contains(t)).unwrap_or(false))
            .collect()
    } else {
        resources
    };

    let resource_records: Vec<Value> = filtered
        .into_iter()
        .map(|res| {
            let mut rec = BTreeMap::new();
            rec.insert("uri".to_string(), Value::Str(res.uri));
            rec.insert("name".to_string(), Value::Str(res.name));
            if let Some(desc) = res.description {
                rec.insert("description".to_string(), Value::Str(desc));
            }
            if let Some(mime) = res.mime_type {
                rec.insert("mime_type".to_string(), Value::Str(mime));
            }
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(resource_records))
}

/// mcp_prompts(name?) - List available MCP prompts or get specific prompt
/// Args:
///   - name (optional): String - Get specific prompt by name
/// Returns: Array of prompt records or single prompt
///
/// Example:
///   let prompts = mcp_prompts()
///   let find_prompt = mcp_prompts("find-tool")
fn bi_mcp_prompts(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    use crate::mcp::McpServer;

    let server = McpServer::new();
    let prompts = server.list_prompts();

    if !args.is_empty() {
        if let Value::Str(name) = &args[0] {
            if let Some(prompt) = prompts.into_iter().find(|p| &p.name == name) {
                let mut rec = BTreeMap::new();
                rec.insert("name".to_string(), Value::Str(prompt.name));
                if let Some(desc) = prompt.description {
                    rec.insert("description".to_string(), Value::Str(desc));
                }
                if let Some(arguments) = prompt.arguments {
                    let args_values: Vec<Value> = arguments
                        .into_iter()
                        .map(|arg| {
                            let mut arg_rec = BTreeMap::new();
                            arg_rec.insert("name".to_string(), Value::Str(arg.name));
                            if let Some(desc) = arg.description {
                                arg_rec.insert("description".to_string(), Value::Str(desc));
                            }
                            arg_rec.insert(
                                "required".to_string(),
                                Value::Bool(arg.required.unwrap_or(false)),
                            );
                            Value::Record(arg_rec)
                        })
                        .collect();
                    rec.insert("arguments".to_string(), Value::Array(args_values));
                }
                return Ok(Value::Record(rec));
            }
            // An unknown prompt name answered null.
            return Err(crate::safety::not_found("mcp_prompts", "prompt", name));
        }
    }

    let prompt_records: Vec<Value> = prompts
        .into_iter()
        .map(|prompt| {
            let mut rec = BTreeMap::new();
            rec.insert("name".to_string(), Value::Str(prompt.name));
            if let Some(desc) = prompt.description {
                rec.insert("description".to_string(), Value::Str(desc));
            }
            if let Some(arguments) = prompt.arguments {
                let args_values: Vec<Value> = arguments
                    .into_iter()
                    .map(|arg| {
                        let mut arg_rec = BTreeMap::new();
                        arg_rec.insert("name".to_string(), Value::Str(arg.name));
                        if let Some(desc) = arg.description {
                            arg_rec.insert("description".to_string(), Value::Str(desc));
                        }
                        arg_rec.insert(
                            "required".to_string(),
                            Value::Bool(arg.required.unwrap_or(false)),
                        );
                        Value::Record(arg_rec)
                    })
                    .collect();
                rec.insert("arguments".to_string(), Value::Array(args_values));
            }
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(prompt_records))
}

/// mcp_connect(endpoint) - Connect to an external MCP server
/// Args:
///   - endpoint: String - Server endpoint URL (e.g., "http://localhost:3001")
/// Returns: Record with connection info and available tools
///
/// Example:
///   let client = mcp_connect("http://localhost:3001")
///   let tools = client.tools
fn bi_mcp_connect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("mcp_connect", &input)?;
    if args.is_empty() {
        return Err(crate::safety::bad_arg(
            "mcp_connect",
            "endpoint: String",
            "nothing",
        ));
    }

    // Only the endpoints `detect_mcp_servers` probes on loopback are ever
    // matched. Nothing here opens a connection to an address the caller gave.
    let endpoint = expect_string("mcp_connect", &args[0])?;

    // Try to detect MCP server at endpoint
    let servers = crate::ai::detect_mcp_servers();
    if let Some(server) = servers.iter().find(|s| s.endpoint == endpoint) {
        let mut record = BTreeMap::new();
        record.insert("endpoint".to_string(), Value::Str(server.endpoint.clone()));
        record.insert("name".to_string(), Value::Str(server.name.clone()));
        record.insert("available".to_string(), Value::Bool(server.available));

        let tools: Vec<Value> = server.tools.iter().map(|t| Value::Str(t.clone())).collect();
        record.insert("tools".to_string(), Value::Array(tools));

        return Ok(Value::Record(record));
    }

    // Server not detected, return basic info indicating unavailable
    let mut record = BTreeMap::new();
    record.insert("endpoint".to_string(), Value::Str(endpoint.to_string()));
    record.insert("name".to_string(), Value::Str("unknown".to_string()));
    record.insert("available".to_string(), Value::Bool(false));
    record.insert("tools".to_string(), Value::Array(vec![]));
    record.insert(
        "error".to_string(),
        Value::Str("Server not responding or not detected".to_string()),
    );

    Ok(Value::Record(record))
}

// Helper function to convert owned Value to serde_json::Value
fn value_to_json_owned(v: Value) -> serde_json::Value {
    match v {
        Value::Null => serde_json::Value::Null,
        Value::Bool(b) => serde_json::Value::Bool(b),
        Value::Int(i) => serde_json::Value::Number(serde_json::Number::from(i)),
        Value::Float(f) => serde_json::Number::from_f64(f)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        Value::Str(s) => serde_json::Value::String(s),
        Value::Array(arr) => {
            serde_json::Value::Array(arr.into_iter().map(value_to_json_owned).collect())
        }
        Value::Record(rec) => {
            let map: serde_json::Map<String, serde_json::Value> = rec
                .into_iter()
                .map(|(k, v)| (k, value_to_json_owned(v)))
                .collect();
            serde_json::Value::Object(map)
        }
        _ => serde_json::Value::Null,
    }
}

/// first(n?) - Get first n elements from array input (default: 1)
/// Args:
///   - n (optional): Int - Number of elements to take (default: 1)
/// Returns: the first element when n is omitted; an Array of the first n
/// elements when n is given, even n=1 (so `first(1) | map(...)` works)
///
/// Example:
///   [1,2,3,4,5] | first()      # Returns 1
///   [1,2,3,4,5] | first(1)     # Returns [1]
///   [1,2,3,4,5] | first(3)     # Returns [1,2,3]
fn bi_first(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (arr_val, count_arg) = if let Some(inp) = input {
        // Piped: input is array, args[0] is optional count
        (inp, args.first())
    } else if !args.is_empty() {
        // Not piped: args[0] is array, args[1] is optional count
        (args[0].clone(), args.get(1))
    } else {
        return Err(crate::safety::arg_err("first requires array input"));
    };

    let arr = expect_array("first", &arr_val)?;

    let count = if let Some(c_arg) = count_arg {
        expect_int("first", c_arg)?
    } else {
        1
    };

    // A negative count was taken as 0 and answered [], as take did before it
    // refused the same thing.
    if count < 0 {
        return Err(crate::safety::arg_err(
            "first count must be a nonnegative Int",
        ));
    }
    if count == 0 {
        return Ok(Value::Array(vec![]));
    }

    // Fast path for the bare call (most common case). An explicit count of 1
    // is an Array like every other count: `first(1) | map(...)` must map over
    // a list, not a scalar. The bare call names one element, and an empty
    // array has none: null, not an empty array.
    if count == 1 && count_arg.is_none() {
        return if arr.is_empty() {
            Ok(Value::Null)
        } else {
            Ok(arr[0].clone())
        };
    }

    // Use iterator for all other cases (proven to be fastest)
    let result: Vec<Value> = arr.iter().take(count as usize).cloned().collect();
    Ok(Value::Array(result))
}

/// last(n?) - Get last n elements from array input (default: 1)
/// Args:
///   - n (optional): Int - Number of elements to take (default: 1)
/// Returns: the last element when n is omitted; an Array of the last n
/// elements when n is given, even n=1 (so `last(1) | map(...)` works)
///
/// Example:
///   [1,2,3,4,5] | last()       # Returns 5
///   [1,2,3,4,5] | last(1)      # Returns [5]
///   [1,2,3,4,5] | last(3)      # Returns [3,4,5]
fn bi_last(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (arr_val, count_arg) = if let Some(inp) = input {
        // Piped: input is array, args[0] is optional count
        (inp, args.first())
    } else if !args.is_empty() {
        // Not piped: args[0] is array, args[1] is optional count
        (args[0].clone(), args.get(1))
    } else {
        return Err(crate::safety::arg_err("last requires array input"));
    };

    let arr = expect_array("last", &arr_val)?;

    let count = if let Some(c_arg) = count_arg {
        expect_int("last", c_arg)?
    } else {
        1
    };

    if count < 0 {
        return Err(crate::safety::arg_err(
            "last count must be a nonnegative Int",
        ));
    }
    if count == 0 {
        return Ok(Value::Array(vec![]));
    }

    // Fast path for the bare call (most common case). An explicit count of 1
    // is an Array like every other count, as in `first`; the bare call on an
    // empty array is null, as `first` is.
    if count == 1 && count_arg.is_none() {
        return if arr.is_empty() {
            Ok(Value::Null)
        } else {
            Ok(arr[arr.len() - 1].clone())
        };
    }

    // Use slice for all other cases (proven to be fastest)
    let start_idx = if arr.len() > count as usize {
        arr.len() - count as usize
    } else {
        0
    };

    let result: Vec<Value> = arr[start_idx..].to_vec();
    Ok(Value::Array(result))
}

/// any(predicate?) - Check if any element matches predicate (or any truthy if no predicate)
/// Args:
///   - predicate (optional): Lambda - Function to test each element
/// Returns: Bool - true if any element matches
///
/// Example:
///   [1,2,3] | any(fn(x) => x > 2)     # Returns true
///   [false, true, false] | any()      # Returns true
///   any([1,2,3], fn(x) => x > 2)      # Also works as function call
fn bi_any(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    // Determine input array and predicate
    // If input is provided via pipe, first arg is predicate (optional)
    // If input is first arg (array), second arg is predicate (optional)
    let (arr, predicate): (Vec<Value>, Option<Value>) = if let Some(inp) = input {
        let arr = expect_array("any", &inp)?.to_vec();
        let pred = args.first().cloned();
        (arr, pred)
    } else if !args.is_empty() {
        if let Value::Array(a) = &args[0] {
            // First arg is array
            let pred = args.get(1).cloned();
            (a.clone(), pred)
        } else if matches!(&args[0], Value::Lambda(_)) {
            // First arg is lambda with empty array (edge case)
            return Err(crate::safety::arg_err("any requires an array as input"));
        } else {
            return Err(crate::safety::arg_err(format!(
                "any expects array, got {:?}",
                args[0]
            )));
        }
    } else {
        return Err(crate::safety::arg_err("any requires an array input"));
    };

    if let Some(pred_val) = predicate {
        // Use predicate function
        let predicate = need_lambda(&pred_val, "any")?;

        for val in arr {
            let result = call_lambda(predicate, &[val.clone()], env)?;
            if is_truthy(&result) {
                return Ok(Value::Bool(true));
            }
        }
        Ok(Value::Bool(false))
    } else {
        // No predicate - check for any truthy values
        for val in arr {
            if is_truthy(&val) {
                return Ok(Value::Bool(true));
            }
        }
        Ok(Value::Bool(false))
    }
}

/// all(predicate?) - Check if all elements match predicate (or all truthy if no predicate)
/// Args:
///   - predicate (optional): Lambda - Function to test each element
/// Returns: Bool - true if all elements match
///
/// Example:
///   [1,2,3] | all(fn(x) => x > 0)     # Returns true
///   [true, true, false] | all()       # Returns false
///   all([1,2,3], fn(x) => x > 0)      # Also works as function call
fn bi_all(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    // Determine input array and predicate
    // If input is provided via pipe, first arg is predicate (optional)
    // If input is first arg (array), second arg is predicate (optional)
    let (arr, predicate): (Vec<Value>, Option<Value>) = if let Some(inp) = input {
        let arr = expect_array("all", &inp)?.to_vec();
        let pred = args.first().cloned();
        (arr, pred)
    } else if !args.is_empty() {
        if let Value::Array(a) = &args[0] {
            // First arg is array
            let pred = args.get(1).cloned();
            (a.clone(), pred)
        } else if matches!(&args[0], Value::Lambda(_)) {
            // First arg is lambda with empty array (edge case)
            return Err(crate::safety::arg_err("all requires an array as input"));
        } else {
            return Err(crate::safety::arg_err(format!(
                "all expects array, got {:?}",
                args[0]
            )));
        }
    } else {
        return Err(crate::safety::arg_err("all requires an array input"));
    };

    if let Some(pred_val) = predicate {
        // Use predicate function
        let predicate = need_lambda(&pred_val, "all")?;

        for val in arr {
            let result = call_lambda(predicate, &[val.clone()], env)?;
            if !is_truthy(&result) {
                return Ok(Value::Bool(false));
            }
        }
        Ok(Value::Bool(true))
    } else {
        // No predicate - check if all values are truthy
        for val in arr {
            if !is_truthy(&val) {
                return Ok(Value::Bool(false));
            }
        }
        Ok(Value::Bool(true))
    }
}

/// Helper function to determine truthiness of a Value
fn is_truthy(val: &Value) -> bool {
    match val {
        Value::Bool(b) => *b,
        Value::Int(i) => *i != 0,
        Value::Float(f) => *f != 0.0,
        Value::Str(s) => !s.is_empty(),
        Value::Array(a) => !a.is_empty(),
        Value::Record(r) => !r.is_empty(),
        Value::Null => false,
        Value::Lambda(_) => true,              // Functions are truthy
        Value::AsyncLambda(_) => true,         // Async lambdas are truthy
        Value::Future(_) => true,              // Futures are truthy
        Value::Uri(_) => true,                 // URIs are truthy if they exist
        Value::Table(t) => !t.rows.is_empty(), // Tables are truthy if they have data
        Value::Error(_) => false,              // Errors are falsy
        Value::Builtin(_) => true,             // Builtins are truthy
    }
}

// ==================== String Functions ====================

/// split(delimiter, limit?) - Split string into array by delimiter
/// Args:
///   - delimiter: String - The delimiter to split on
///   - limit: Int (optional) - the most pieces to answer, 1 or more (Rust's splitn); the last piece keeps the rest of the text
/// Returns: Array - Array of string parts
///
/// Example:
///   "a,b,c" | split(",")     # Returns ["a", "b", "c"]
///   "a,b,c" | split(",", 2)  # Returns ["a", "b,c"]
fn bi_split(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (text_val, delim_arg, limit_arg) = if let Some(inp) = input {
        // Piped: input is string, args[0] is delimiter, args[1] the limit
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("split requires delimiter argument"))?,
            args.get(1),
        )
    } else {
        // Not piped: args[0] is string, args[1] is delimiter, args[2] the limit
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("split requires string input"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("split requires delimiter argument"))?,
            args.get(2),
        )
    };

    let text = expect_string("split", &text_val)?;
    let delimiter = expect_string("split", delim_arg)?;
    // limit: the most pieces to answer (Rust's splitn); the last piece holds the
    // rest of the text unsplit. Absent means no limit.
    let limit: Option<usize> = match limit_arg {
        None => None,
        Some(Value::Int(n)) if *n >= 1 => Some(usize::try_from(*n).unwrap_or(usize::MAX)),
        Some(Value::Int(n)) => {
            return Err(crate::safety::bad_arg_in(
                "split",
                format!("split: limit {n} is not at least 1: it is the most pieces to answer"),
                "pass a limit of 1 or more, or leave it out to split on every delimiter",
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "split",
                "an Int limit, the most pieces",
                other.type_name(),
            ))
        }
    };

    // Rust's `split("")` yields an empty piece at each end and between every
    // character, so `"abc" | split("")` gave ["", "a", "b", "c", ""]. An empty
    // delimiter splits into characters instead, so "café" gives four items.
    let parts: Vec<Value> = if delimiter.is_empty() {
        let chars: Vec<char> = text.chars().collect();
        match limit {
            Some(n) if n < chars.len() => {
                let mut parts: Vec<Value> = chars[..n - 1]
                    .iter()
                    .map(|c| Value::Str(c.to_string()))
                    .collect();
                parts.push(Value::Str(chars[n - 1..].iter().collect()));
                parts
            }
            _ => chars.iter().map(|c| Value::Str(c.to_string())).collect(),
        }
    } else if let Some(n) = limit {
        text.splitn(n, delimiter)
            .map(|s| Value::Str(s.to_string()))
            .collect()
    } else {
        text.split(delimiter)
            .map(|s| Value::Str(s.to_string()))
            .collect()
    };

    Ok(Value::Array(parts))
}

/// join(delimiter) - Join array elements into string with delimiter
/// Args:
///   - delimiter: String - The delimiter to join with
/// Returns: String - Joined string
///
/// Example:
///   ["a", "b", "c"] | join(",")     # Returns "a,b,c"
fn bi_join(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (arr_val, delim_arg) = if let Some(inp) = input {
        // Piped: input is array, args[0] is delimiter
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("join requires delimiter argument"))?,
        )
    } else {
        // Not piped: args[0] is array, args[1] is delimiter
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("join requires array input"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("join requires delimiter argument"))?,
        )
    };

    let arr = expect_array("join", &arr_val)?;
    let delimiter = expect_string("join", delim_arg)?;

    let strings: Result<Vec<String>> = arr
        .iter()
        .map(|v| match v {
            Value::Str(s) => Ok(s.clone()),
            Value::Int(i) => Ok(i.to_string()),
            Value::Float(f) => Ok(crate::value::float_text(*f)),
            Value::Bool(b) => Ok(b.to_string()),
            _ => Err(crate::safety::arg_err(
                "join requires array of strings or numbers",
            )),
        })
        .collect();

    Ok(Value::Str(strings?.join(delimiter)))
}

/// trim(text, chars?) - Remove leading and trailing characters from a string.
/// Args:
///   - text: String (or the piped text)
///   - chars: String (optional) - every character in it is stripped from both
///     ends, as Python's str.strip(chars) does; "" strips nothing
/// Returns: String
///
/// Without `chars` the ends lose Unicode whitespace.
///
/// Example:
///   "  hello  " | trim()          # "hello"
///   trim("xxhixx", "x")           # "hi"
fn bi_trim(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (text, rest) = text_subject("trim", args, input)?;
    let strip: Option<String> = match rest.as_slice() {
        [] => None,
        [Value::Str(chars)] => Some(chars.clone()),
        [other] => {
            return Err(crate::safety::bad_arg(
                "trim",
                "a String of characters to strip",
                other.type_name(),
            ))
        }
        _ => {
            return Err(arity_error(
                "trim",
                "a text and an optional String of characters",
                rest.len(),
            ))
        }
    };
    Ok(Value::Str(match strip {
        None => text.trim().to_string(),
        Some(chars) => text.trim_matches(|c: char| chars.contains(c)).to_string(),
    }))
}

/// Whether a character belongs to a word for `title`: a letter, a digit, or an
/// apostrophe. Every other character separates words.
/// The titlecase form of a Unicode digraph letter (U+01C4..U+01CC and
/// U+01F1..U+01F3). Its upper case is the wrong form: `to_uppercase` gives
/// DŽ where titlecase is Dž, as Python's `capitalize` does. `None` for every
/// other character.
fn titlecase_digraph(c: char) -> Option<char> {
    match c {
        '\u{01C4}'..='\u{01C6}' => Some('\u{01C5}'),
        '\u{01C7}'..='\u{01C9}' => Some('\u{01C8}'),
        '\u{01CA}'..='\u{01CC}' => Some('\u{01CB}'),
        '\u{01F1}'..='\u{01F3}' => Some('\u{01F2}'),
        _ => None,
    }
}

fn is_title_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '\''
}

/// title(text) - Title-case a string: in each word, the first letter is upper
/// case and every other letter is lower case.
/// Args:
///   - text: String (or the piped text)
/// Returns: String
///
/// A word is a maximal run of letters, digits and apostrophes. Any other
/// character (a space, a hyphen, punctuation) ends a word and is kept as it is.
/// Digits and apostrophes are kept too, and a word's first letter is the first
/// letter in it, so "3rd" becomes "3Rd" and "they're" becomes "They're".
/// Letters use Unicode case mapping one character at a time: "élan vital" is
/// "Élan Vital", and a letter whose upper case is two characters, such as ß,
/// becomes both.
///
/// Example:
///   title("hello WORLD")        # "Hello World"
///   "well-known fact" | title() # "Well-Known Fact"
fn bi_title(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (text, rest) = text_subject("title", args, input)?;
    if !rest.is_empty() {
        return Err(arity_error("title", "a text only", rest.len()));
    }
    let mut out = String::with_capacity(text.len());
    let mut at_word_start = true;
    for c in text.chars() {
        if is_title_word_char(c) {
            if c.is_alphabetic() {
                if at_word_start {
                    match titlecase_digraph(c) {
                        Some(t) => out.push(t),
                        None => out.extend(c.to_uppercase()),
                    }
                } else {
                    out.extend(c.to_lowercase());
                }
                at_word_start = false;
            } else {
                out.push(c);
            }
        } else {
            out.push(c);
            at_word_start = true;
        }
    }
    Ok(Value::Str(out))
}

/// capitalize(text) - The first character upper case, every other character
/// lower case. Unlike `title`, a space or a hyphen does not start a new word.
/// Args:
///   - text: String (or the piped text)
/// Returns: String
///
/// Example:
///   capitalize("hELLO wORLD")   # "Hello world"
///   "élan" | capitalize()       # "Élan"
///   "džungla" | capitalize()     # "Džungla" (titlecase, not DŽ)
fn bi_capitalize(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (text, rest) = text_subject("capitalize", args, input)?;
    if !rest.is_empty() {
        return Err(arity_error("capitalize", "a text only", rest.len()));
    }
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars();
    if let Some(first) = chars.next() {
        match titlecase_digraph(first) {
            Some(t) => out.push(t),
            None => out.extend(first.to_uppercase()),
        }
    }
    for c in chars {
        out.extend(c.to_lowercase());
    }
    Ok(Value::Str(out))
}

/// The most bytes `repeat` will build: 100 MB (100,000,000 bytes). A larger
/// result is refused with E_BAD_VALUE rather than allocated.
const REPEAT_BYTES_MAX: usize = 100_000_000;

/// repeat(text, count) - The text, `count` times in a row.
/// Args:
///   - text: String (or the piped text)
///   - count: Int - 0 or more; a negative count is E_BAD_ARG
/// Returns: String
///
/// A result over 100 MB is E_BAD_VALUE. An empty text repeats to "" whatever
/// the count.
///
/// Example:
///   repeat("ab", 3)     # "ababab"
///   "-" | repeat(5)     # "-----"
fn bi_repeat(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (text, rest) = text_subject("repeat", args, input)?;
    let count = match rest.as_slice() {
        [] => return Err(crate::safety::bad_arg("repeat", "a count Int", "nothing")),
        [Value::Int(n)] => *n,
        [other] => {
            return Err(crate::safety::bad_arg(
                "repeat",
                "a count Int",
                other.type_name(),
            ))
        }
        _ => return Err(arity_error("repeat", "a text and a count", rest.len())),
    };
    if count < 0 {
        return Err(crate::safety::bad_arg(
            "repeat",
            "a count of 0 or more",
            &count.to_string(),
        ));
    }
    if text.is_empty() {
        return Ok(Value::Str(String::new()));
    }
    let bytes = usize::try_from(count)
        .ok()
        .and_then(|n| n.checked_mul(text.len()));
    match bytes {
        Some(total) if total <= REPEAT_BYTES_MAX => Ok(Value::Str(text.repeat(count as usize))),
        _ => Err(crate::safety::value_not_representable(
            "repeat",
            format!(
                "repeat: {} copies of {} bytes is more than {} bytes",
                count,
                text.len(),
                REPEAT_BYTES_MAX
            ),
            "repeat fewer times, or build the text in pieces",
        )),
    }
}

/// words(text) - The words of a string: the text split on any run of
/// whitespace, with the empty pieces dropped.
/// Args:
///   - text: String (or the piped text)
/// Returns: Array<String>
///
/// Whitespace is Unicode whitespace: spaces, tabs, newlines and CRs alike.
///
/// Example:
///   words("  the  quick\tfox\n")   # ["the", "quick", "fox"]
///   "a b" | words() | len          # 2
fn bi_words(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (text, rest) = text_subject("words", args, input)?;
    if !rest.is_empty() {
        return Err(arity_error("words", "a text only", rest.len()));
    }
    Ok(Value::Array(
        text.split_whitespace()
            .map(|w| Value::Str(w.to_string()))
            .collect(),
    ))
}

/// upper() - Convert string to uppercase
/// Returns: String - Uppercase string
///
/// Example:
///   "hello" | upper()     # Returns "HELLO"
fn bi_upper(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let input_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("upper requires input string"))?;
    let text = expect_string("upper", &input_val)?;
    Ok(Value::Str(text.to_uppercase()))
}

/// lower() - Convert string to lowercase
/// Returns: String - Lowercase string
///
/// Example:
///   "HELLO" | lower()     # Returns "hello"
fn bi_lower(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let input_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("lower requires input string"))?;
    let text = expect_string("lower", &input_val)?;
    Ok(Value::Str(text.to_lowercase()))
}

/// replace(old, new) - Replace all occurrences of substring
/// Args:
///   - old: String - Substring to replace
///   - new: String - Replacement substring
/// Returns: String - String with replacements
///
/// Example:
///   "hello world" | replace("world", "universe")     # Returns "hello universe"
fn bi_replace(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (input_val, old_arg, new_arg) = if let Some(inp) = input {
        // Piped: input is string, args[0] is old, args[1] is new
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("replace requires old substring argument"))?,
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("replace requires new substring argument"))?,
        )
    } else {
        // Not piped: args[0] is string, args[1] is old, args[2] is new
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("replace requires string input"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("replace requires old substring argument"))?,
            args.get(2)
                .ok_or_else(|| crate::safety::arg_err("replace requires new substring argument"))?,
        )
    };

    let text = expect_string("replace", &input_val)?;
    let old = expect_string("replace", old_arg)?;
    let new = expect_string("replace", new_arg)?;

    Ok(Value::Str(text.replace(old, new)))
}

/// contains(substring) - Check if string contains substring
/// Args:
///   - substring: String - Substring to search for
/// Returns: Bool - true if substring found
///
/// Example:
///   "hello world" | contains("world")     # Returns true
fn bi_contains(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (input_val, substring_arg) = if let Some(inp) = input {
        // Piped: input is string, args[0] is substring
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("contains requires substring argument"))?,
        )
    } else {
        // Not piped: args[0] is string, args[1] is substring
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("contains requires string input"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("contains requires substring argument"))?,
        )
    };

    // An array is the usual reason for this error: `contains` searches a string,
    // and array membership is `in`.
    if let Value::Array(_) = input_val {
        return Err(crate::safety::bad_arg_with_hint(
            "contains",
            "a string",
            "Array",
            "contains searches a string for a substring; to test whether an array holds a value, pipe the value to in: `value | in(array)`",
        ));
    }
    let text = expect_string("contains", &input_val)?;
    let substring = expect_string("contains", substring_arg)?;
    Ok(Value::Bool(text.contains(substring)))
}

/// starts_with(prefix) - Check if string starts with prefix
/// Args:
///   - prefix: String - Prefix to check
/// Returns: Bool - true if string starts with prefix
///
/// Example:
///   "hello world" | starts_with("hello")     # Returns true
fn bi_starts_with(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (input_val, prefix_arg) = if let Some(inp) = input {
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("starts_with requires prefix argument"))?,
        )
    } else {
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("starts_with requires string input"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("starts_with requires prefix argument"))?,
        )
    };

    let text = expect_string("starts_with", &input_val)?;
    let prefix = expect_string("starts_with", prefix_arg)?;
    Ok(Value::Bool(text.starts_with(prefix)))
}

/// ends_with(suffix) - Check if string ends with suffix
/// Args:
///   - suffix: String - Suffix to check
/// Returns: Bool - true if string ends with suffix
///
/// Example:
///   "hello world" | ends_with("world")     # Returns true
fn bi_ends_with(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (input_val, suffix_arg) = if let Some(inp) = input {
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("ends_with requires suffix argument"))?,
        )
    } else {
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("ends_with requires string input"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("ends_with requires suffix argument"))?,
        )
    };

    let text = expect_string("ends_with", &input_val)?;
    let suffix = expect_string("ends_with", suffix_arg)?;
    Ok(Value::Bool(text.ends_with(suffix)))
}

// ==================== Array Functions (Extended) ====================

/// flatten() - Flatten nested arrays one level deep
/// Returns: Array - Flattened array
///
/// Example:
///   [[1,2],[3,4],[5]] | flatten()     # Returns [1,2,3,4,5]
///   flatten([[1,2],[3,4]])            # Also works as function call
fn bi_flatten(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let input_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("flatten requires input array"))?;
    let arr = expect_array("flatten", &input_val)?;

    let mut result = Vec::new();
    for val in arr {
        match val {
            Value::Array(inner) => {
                crate::eval::check_array_len(result.len().saturating_add(inner.len()))?;
                result.extend(inner.clone())
            }
            other => result.push(other.clone()),
        }
    }

    Ok(Value::Array(result))
}

/// reverse() - Reverse array or string
/// Returns: Array or String - Reversed input
///
/// Example:
///   [1,2,3,4,5] | reverse()     # Returns [5,4,3,2,1]
fn bi_reverse(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let input_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("reverse requires input"))?;

    match input_val {
        Value::Array(mut arr) => {
            arr.reverse();
            Ok(Value::Array(arr))
        }
        Value::Str(s) => Ok(Value::Str(s.chars().rev().collect())),
        _ => Err(crate::safety::arg_err(
            "reverse requires array or string input",
        )),
    }
}

/// A slice index as Python reads one: a negative index counts from the end, and
/// the result is clamped to `0..=len`. `-3` of a length-5 sequence is 2.
fn slice_index(index: i64, len: usize) -> usize {
    let len = len as i64;
    let resolved = if index < 0 {
        index.saturating_add(len)
    } else {
        index
    };
    resolved.clamp(0, len) as usize
}

/// slice(start, end?) - Extract slice of array or string
/// Args:
///   - start: Int - Start index (inclusive); negative counts from the end
///   - end: Int (optional) - End index (exclusive); negative counts from the end
/// Returns: Array or String - Sliced input; empty when start is not before end
///
/// Example:
///   [1,2,3,4,5] | slice(1, 3)     # Returns [2,3]
///   [1,2,3,4,5] | slice(-2)       # Returns [4,5]
///   slice([1,2,3,4,5], 1, 3)      # Also works as function call
fn bi_slice(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Determine input and index arguments
    // If input is provided via pipe, args are (start, end?)
    // If input is first arg, args are (array, start, end?)
    let (input_val, start_idx, end_arg) = if let Some(inp) = input {
        // Piped input: args are start, end?
        if args.is_empty() {
            return Err(crate::safety::arg_err(
                "slice requires at least start index",
            ));
        }
        let start = expect_int("slice", &args[0])?;
        let end = args.get(1);
        (inp, start, end)
    } else {
        // Function call: first arg is array, then start, end?
        if args.len() < 2 {
            return Err(crate::safety::arg_err(
                "slice(array, start, end?) requires at least array and start",
            ));
        }
        let arr = args[0].clone();
        let start = expect_int("slice", &args[1])?;
        let end = args.get(2);
        (arr, start, end)
    };

    match input_val {
        Value::Array(arr) => {
            let end = match end_arg {
                Some(e) => slice_index(expect_int("slice", e)?, arr.len()),
                None => arr.len(),
            };
            let start = slice_index(start_idx, arr.len()).min(end);

            Ok(Value::Array(arr[start..end].to_vec()))
        }
        Value::Str(s) => {
            // Counted by character, as len counts them.
            let chars: Vec<char> = s.chars().collect();
            let end = match end_arg {
                Some(e) => slice_index(expect_int("slice", e)?, chars.len()),
                None => chars.len(),
            };
            let start = slice_index(start_idx, chars.len()).min(end);

            Ok(Value::Str(chars[start..end].iter().collect()))
        }
        other => Err(crate::safety::bad_arg_in(
            "slice",
            format!(
                "slice takes a String or Array and Int indices; got {}",
                other.type_name()
            ),
            "pass the text or the array first: slice(x, start, end?), or x | slice(start, end?)",
        )),
    }
}

/// Most elements `range` will build. A longer range is refused before any
/// element is allocated, as a coded `BudgetExceeded` error, so
/// `range(0, 1000000000000)` cannot exhaust memory.
const RANGE_MAX: i128 = 10_000_000;

/// range(start, end?, step?) - Generate array of integers
/// Args:
///   - start: Int - Start value (or end if only one arg)
///   - end: Int (optional) - End value (exclusive)
///   - step: Int (optional) - Step size (default 1)
/// Returns: Array - Array of integers
///
/// Example:
///   range(5)           # Returns [0,1,2,3,4]
///   range(2, 7)        # Returns [2,3,4,5,6]
///   range(0, 10, 2)    # Returns [0,2,4,6,8]
fn bi_range(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err(
            "range requires at least one argument",
        ));
    }

    let (start, end, step) = if args.len() == 1 {
        // range(n) -> 0..n
        (0, expect_int("range", &args[0])?, 1)
    } else if args.len() == 2 {
        // range(start, end) -> start..end
        (
            expect_int("range", &args[0])?,
            expect_int("range", &args[1])?,
            1,
        )
    } else {
        // range(start, end, step)
        (
            expect_int("range", &args[0])?,
            expect_int("range", &args[1])?,
            expect_int("range", &args[2])?,
        )
    };

    if step == 0 {
        return Err(crate::safety::arg_err("range step cannot be zero"));
    }

    // Count first, in i128, so no step or offset can overflow i64. The count
    // is refused before anything is allocated.
    let (s, e, st) = (start as i128, end as i128, step as i128);
    let count: i128 = if st > 0 {
        if s < e {
            (e - s + st - 1) / st
        } else {
            0
        }
    } else if s > e {
        (s - e - st - 1) / -st
    } else {
        0
    };
    if count > RANGE_MAX {
        return Err(crate::safety::budget_exceeded(
            "range",
            format!("{count} elements exceed the {RANGE_MAX} element limit"),
            "split the range: e.g. arr.range(0, 10000000) then arr.range(10000000, 20000000), or reduce the count",
        ));
    }

    let mut result = Vec::with_capacity(count as usize);
    for i in 0..count {
        // Each element lies between start and end, so it fits in i64.
        result.push(Value::Int((s + i * st) as i64));
    }

    Ok(Value::Array(result))
}

/// zip(array2) - Zip two arrays into array of pairs
/// Args:
///   - array2: Array - Second array to zip with
/// Returns: Array - Array of [item1, item2] pairs
///
/// Example:
///   [1,2,3] | zip(["a","b","c"])     # Returns [[1,"a"],[2,"b"],[3,"c"]]
fn bi_zip(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (arr1_val, arr2_val) = if let Some(inp) = input {
        // Piped: input is first array, args[0] is second array
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("zip requires second array argument"))?
                .clone(),
        )
    } else {
        // Not piped: args[0] is first array, args[1] is second array
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("zip requires two array arguments"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("zip requires two array arguments"))?
                .clone(),
        )
    };

    let arr1 = expect_array("zip", &arr1_val)?;
    let arr2 = expect_array("zip", &arr2_val)?;
    let mut result = Vec::new();

    for (a, b) in arr1.iter().zip(arr2.iter()) {
        result.push(Value::Array(vec![a.clone(), b.clone()]));
    }

    Ok(Value::Array(result))
}

/// push(item) - Add item to end of array
/// Args:
///   - item: Any - Item to add
/// Returns: Array - Array with item added
///
/// Example:
///   [1,2,3] | push(4)     # Returns [1,2,3,4]
fn bi_push(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (arr_val, item) = if let Some(inp) = input {
        // Piped: input is array, args[0] is item
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("push requires item argument"))?,
        )
    } else {
        // Not piped: args[0] is array, args[1] is item
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("push requires array input"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("push requires item argument"))?,
        )
    };

    let mut arr = expect_array("push", &arr_val)?.to_vec();
    arr.push(item.clone());
    Ok(Value::Array(arr))
}

/// concat(array2) - Concatenate two arrays
/// Args:
///   - array2: Array - Array to concatenate
/// Returns: Array - Combined array
///
/// Example:
///   [1,2,3] | concat([4,5,6])     # Returns [1,2,3,4,5,6]
fn bi_concat(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (arr1_val, arr2_val) = if let Some(inp) = input {
        // Piped: input is first array, args[0] is second array
        (
            inp,
            args.first()
                .ok_or_else(|| crate::safety::arg_err("concat requires second array argument"))?
                .clone(),
        )
    } else {
        // Not piped: args[0] is first array, args[1] is second array
        (
            args.first()
                .ok_or_else(|| crate::safety::arg_err("concat requires two array arguments"))?
                .clone(),
            args.get(1)
                .ok_or_else(|| crate::safety::arg_err("concat requires two array arguments"))?
                .clone(),
        )
    };

    let mut arr1 = expect_array("concat", &arr1_val)?.to_vec();
    let arr2 = expect_array("concat", &arr2_val)?;
    crate::eval::check_array_len(arr1.len().saturating_add(arr2.len()))?;
    arr1.extend(arr2.iter().cloned());

    Ok(Value::Array(arr1))
}

// ==================== Math Functions ====================

/// abs(number?) - Get absolute value
/// Args:
///   - number: Number (optional if piped)
/// Returns: Number - Absolute value
///
/// Example:
///   abs(-5)     # Returns 5
fn bi_abs(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if args.is_empty() {
        input.ok_or_else(|| crate::safety::arg_err("abs requires number argument"))?
    } else {
        args[0].clone()
    };

    match val {
        // abs(i64::MIN) does not fit in an Int: refused, as `-x` on it is.
        Value::Int(n) => n
            .checked_abs()
            .map(Value::Int)
            .ok_or_else(|| crate::safety::integer_overflow("Abs")),
        Value::Float(f) => Ok(Value::Float(f.abs())),
        _ => Err(crate::safety::arg_err("abs requires numeric input")),
    }
}

/// min(a, b) - Get minimum of two numbers
/// Args:
///   - a: Number
///   - b: Number
/// Returns: Number - Minimum value
///
/// Example:
///   min(3, 7)     # Returns 3
/// The array `min`/`max` should aggregate over, if this is the aggregate form.
///
/// Both builtins were binary-only: `min(a, b)`. The ontology advertised them
/// under `Aggregation` as "Get minimum value" / "Get maximum value" with an
/// empty parameter list, so an agent reading the ontology writes `max(xs)` or
/// `xs | max` and is told "max requires two arguments" -- a discovery surface
/// describing a function that does not exist. The aggregate form is accepted
/// here; the two-number form below is untouched.
fn aggregate_operand<'a>(args: &'a [Value], input: &'a Option<Value>) -> Option<&'a Vec<Value>> {
    match (args.first(), args.len()) {
        (Some(Value::Array(items)), 1) => Some(items),
        (None, _) => match input {
            Some(Value::Array(items)) => Some(items),
            _ => None,
        },
        _ => None,
    }
}

/// Largest (`want_max`) or smallest element of a numeric array.
fn fold_extremum(items: &[Value], want_max: bool) -> Result<Value> {
    if items.is_empty() {
        return Err(crate::safety::arg_err(if want_max {
            "max of an empty array is undefined"
        } else {
            "min of an empty array is undefined"
        }));
    }
    let name = if want_max { "max" } else { "min" };
    // Strings order by code point, as sort orders them, so an array of Strings
    // has a least and a greatest. A mix of Strings and numbers has neither.
    if items.iter().all(|v| matches!(v, Value::Str(_))) {
        let mut best: Option<&String> = None;
        for v in items {
            if let Value::Str(s) = v {
                best = Some(match best {
                    None => s,
                    Some(b) if want_max && s > b => s,
                    Some(b) if !want_max && s < b => s,
                    Some(b) => b,
                });
            }
        }
        if let Some(b) = best {
            return Ok(Value::Str(b.clone()));
        }
    }
    // Stay in Int while every element is one, so `[1, 5, 3] | max` is `5` and
    // not `5.0`: an agent comparing the answer to a literal should not have to
    // know whether the aggregate silently promoted.
    // The winning element is returned unchanged (an Int stays an Int in a mix
    // of Ints and Floats), as `sort` keeps its elements.
    let mut best: Option<(f64, &Value)> = None;
    for v in items {
        let n =
            match v {
                Value::Int(i) => *i as f64,
                Value::Float(f) => *f,
                other => return Err(crate::safety::bad_arg_in(
                    name,
                    format!(
                        "{name}: elements must all be numbers or all Strings, found {}",
                        other.type_name()
                    ),
                    "min and max take a list of numbers or a list of Strings, not a mix of them",
                )),
            };
        best = Some(match best {
            None => (n, v),
            Some((b, _)) if want_max && n > b => (n, v),
            Some((b, _)) if !want_max && n < b => (n, v),
            Some(keep) => keep,
        });
    }
    let (_, winner) = best.expect("non-empty array yields a value");
    Ok(winner.clone())
}

fn bi_min(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if let Some(items) = aggregate_operand(&args, &input) {
        return fold_extremum(items, false);
    }
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "min requires two numbers, one array, or a piped array",
        ));
    }

    if args.len() > 2
        && args
            .iter()
            .all(|a| matches!(a, Value::Int(_) | Value::Float(_)))
    {
        return fold_extremum(&args, false);
    }
    match (&args[0], &args[1]) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(*a.min(b))),
        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a.min(*b))),
        (Value::Int(a), Value::Float(b)) => Ok(if (*a as f64) <= *b {
            Value::Int(*a)
        } else {
            Value::Float(*b)
        }),
        (Value::Float(a), Value::Int(b)) => Ok(if *a <= (*b as f64) {
            Value::Float(*a)
        } else {
            Value::Int(*b)
        }),
        _ => Err(crate::safety::arg_err("min requires numeric arguments")),
    }
}

/// max(a, b) - Get maximum of two numbers
/// Args:
///   - a: Number
///   - b: Number
/// Returns: Number - Maximum value
///
/// Example:
///   max(3, 7)     # Returns 7
fn bi_max(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if let Some(items) = aggregate_operand(&args, &input) {
        return fold_extremum(items, true);
    }
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "max requires two numbers, one array, or a piped array",
        ));
    }

    if args.len() > 2
        && args
            .iter()
            .all(|a| matches!(a, Value::Int(_) | Value::Float(_)))
    {
        return fold_extremum(&args, true);
    }
    match (&args[0], &args[1]) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(*a.max(b))),
        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a.max(*b))),
        (Value::Int(a), Value::Float(b)) => Ok(if (*a as f64) >= *b {
            Value::Int(*a)
        } else {
            Value::Float(*b)
        }),
        (Value::Float(a), Value::Int(b)) => Ok(if *a >= (*b as f64) {
            Value::Float(*a)
        } else {
            Value::Int(*b)
        }),
        _ => Err(crate::safety::arg_err("max requires numeric arguments")),
    }
}

/// A whole-valued Float as an Int, refused (as `int` refuses it) when it lies
/// outside the Int range rather than saturating at i64::MIN / i64::MAX.
fn float_to_int_checked(name: &str, whole: f64) -> Result<Value> {
    if !whole.is_finite()
        || whole < -9_223_372_036_854_775_808.0
        || whole >= 9_223_372_036_854_775_808.0
    {
        return Err(crate::safety::value_not_representable(
            name,
            format!("{name}: {whole} has no Int value"),
            "an Int holds whole numbers from -9223372036854775808 to 9223372036854775807",
        ));
    }
    Ok(Value::Int(whole as i64))
}

/// floor(number) - Round down to nearest integer
/// Args:
///   - number: Number
/// Returns: Int - Rounded down value
///
/// Example:
///   floor(3.7)     # Returns 3
fn bi_floor(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if args.is_empty() {
        input.ok_or_else(|| crate::safety::arg_err("floor requires number argument"))?
    } else {
        args[0].clone()
    };

    match val {
        Value::Int(n) => Ok(Value::Int(n)),
        Value::Float(f) => float_to_int_checked("floor", f.floor()),
        _ => Err(crate::safety::arg_err("floor requires numeric input")),
    }
}

/// ceil(number) - Round up to nearest integer
/// Args:
///   - number: Number
/// Returns: Int - Rounded up value
///
/// Example:
///   ceil(3.2)     # Returns 4
fn bi_ceil(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if args.is_empty() {
        input.ok_or_else(|| crate::safety::arg_err("ceil requires number argument"))?
    } else {
        args[0].clone()
    };

    match val {
        Value::Int(n) => Ok(Value::Int(n)),
        Value::Float(f) => float_to_int_checked("ceil", f.ceil()),
        _ => Err(crate::safety::arg_err("ceil requires numeric input")),
    }
}

/// round(number) - Round to nearest integer
/// Args:
///   - number: Number
/// Returns: Int - Rounded value
///
/// Example:
///   round(3.5)     # Returns 4
fn bi_round(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // In a pipeline the piped value is the subject and the arguments are
    // parameters -- `xs | map(f)`, `xs | nth(2)`. `round` inherited the unary
    // convention "first argument if present, else the input", so
    // `mean | round(2)` took 2 as the number to round and answered 2. It is
    // the same defect as discarding `digits`, wearing a pipe.
    let piped_subject = input.is_some() && args.len() == 1;
    let (val, digit_arg) = if piped_subject {
        (input.clone().expect("checked"), args.first())
    } else if args.is_empty() {
        (
            input.ok_or_else(|| crate::safety::arg_err("round requires number argument"))?,
            None,
        )
    } else {
        (args[0].clone(), args.get(1))
    };

    // `round(x, digits)` used to parse, run, and silently discard `digits`:
    // `round(4.966, 2)` answered `5`. A wrong number returned without an error
    // is the worst shape a failure can take for an agent, because nothing in
    // the result says to look again. Absent or zero `digits` keeps the old
    // Int-returning behaviour exactly.
    let digits = match digit_arg {
        None => None,
        Some(Value::Int(d)) if (0..=17).contains(d) => Some(*d as u32),
        Some(other) => {
            return Err(crate::safety::arg_err(&format!(
                "round: digits must be an integer in 0..=17, got {}",
                other.type_name()
            )))
        }
    };

    match (val, digits) {
        (Value::Int(n), _) => Ok(Value::Int(n)),
        (Value::Float(f), None) | (Value::Float(f), Some(0)) => {
            float_to_int_checked("round", f.round())
        }
        (Value::Float(f), Some(d)) => {
            // The same rule as format_number: round the exact binary value, half
            // away from zero, so round(2.675, 2) is 2.67 (2.675 is stored as
            // 2.67499999...) and round(0.125, 2) is 0.13. A Float of 1e15 or more
            // has no fraction digits to round.
            if f.abs() >= 1.0e15 {
                return Ok(Value::Float(f));
            }
            let (int_digits, frac_digits) = round_exact_decimal(f.abs(), d as usize);
            let rounded: f64 = format!("{int_digits}.{frac_digits}")
                .parse()
                .map_err(|_| crate::safety::arg_err("round: the result is not a number"))?;
            Ok(Value::Float(if f < 0.0 && rounded != 0.0 {
                -rounded
            } else {
                rounded
            }))
        }
        _ => Err(crate::safety::arg_err("round requires numeric input")),
    }
}

/// A number argument of a math builtin, as a Float. An Int is promoted; a value
/// that is not finite is refused, since IronShell numbers are finite.
fn math_number(builtin: &str, value: &Value) -> Result<f64> {
    let x = match value {
        Value::Int(n) => *n as f64,
        Value::Float(f) => *f,
        other => {
            return Err(crate::safety::bad_arg(
                builtin,
                "a number",
                other.type_name(),
            ))
        }
    };
    if x.is_finite() {
        Ok(x)
    } else {
        Err(crate::safety::value_not_representable(
            builtin,
            format!("{builtin}: {} is not a finite number", float_for_message(x)),
            "IronShell numbers are finite; pass a number such as 2.5",
        ))
    }
}

/// The subject of a math builtin as a Float, and the arguments after it.
fn math_subject(
    builtin: &str,
    args: Vec<Value>,
    input: Option<Value>,
) -> Result<(f64, Vec<Value>)> {
    let (subject, rest) = subject_and_rest(builtin, args, input)?;
    Ok((math_number(builtin, &subject)?, rest))
}

/// A Float result, refused when it is not finite (an overflow, never an inf).
fn math_result(builtin: &str, value: f64) -> Result<Value> {
    if value.is_finite() {
        Ok(Value::Float(value))
    } else {
        Err(crate::safety::value_not_representable(
            builtin,
            format!("{builtin}: the result is not a finite Float"),
            "use a number whose result fits in a Float",
        ))
    }
}

/// The refusal for a logarithm of zero or less.
fn log_domain(builtin: &str, x: f64) -> anyhow::Error {
    crate::safety::value_not_representable(
        builtin,
        format!(
            "{builtin}: log of a non-positive number, got {}",
            float_for_message(x)
        ),
        "a logarithm is defined for numbers above 0",
    )
}

/// The shared body of log10, log2 and ln: one number, its logarithm in `f`.
fn math_logarithm(
    builtin: &str,
    args: Vec<Value>,
    input: Option<Value>,
    f: fn(f64) -> f64,
) -> Result<Value> {
    let (x, rest) = math_subject(builtin, args, input)?;
    if !rest.is_empty() {
        return Err(arity_error(builtin, "one number", rest.len()));
    }
    if x <= 0.0 {
        return Err(log_domain(builtin, x));
    }
    math_result(builtin, f(x))
}

/// ln(x) - The natural logarithm of a number above 0.
/// Args:
///   - x: Number (or the piped number)
/// Returns: Float
///
/// Example:
///   ln(1)          # 0
///   0 | ln()        # E_BAD_VALUE: log of a non-positive number
fn bi_ln(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    math_logarithm("ln", args, input, f64::ln)
}

/// log(x, base?) - The logarithm of a number above 0: natural by default, or in
/// the base given (above 0, and not 1).
/// Args:
///   - x: Number (or the piped number)
///   - base: Number (optional) - above 0 and not 1; e by default
/// Returns: Float
///
/// Example:
///   log(1)          # 0
///   log(1, 2)       # 0
///   8 | log2()      # 3
///   log(0)          # E_BAD_VALUE: log of a non-positive number
fn bi_log(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (x, rest) = math_subject("log", args, input)?;
    let base = match rest.as_slice() {
        [] => None,
        [b] => Some(math_number("log", b)?),
        _ => {
            return Err(arity_error(
                "log",
                "a number and an optional base",
                rest.len(),
            ))
        }
    };
    if x <= 0.0 {
        return Err(log_domain("log", x));
    }
    match base {
        None => math_result("log", x.ln()),
        Some(b) if b <= 0.0 || b == 1.0 => Err(crate::safety::value_not_representable(
            "log",
            format!(
                "log: the base must be above 0 and not 1, got {}",
                float_for_message(b)
            ),
            "a logarithm base is a number such as 2, 10 or e",
        )),
        Some(b) => math_result("log", x.ln() / b.ln()),
    }
}

/// log10(x) - The base-10 logarithm of a number above 0.
/// Example:
///   log10(1)        # 0
fn bi_log10(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    math_logarithm("log10", args, input, f64::log10)
}

/// log2(x) - The base-2 logarithm of a number above 0.
/// Example:
///   log2(8)         # 3
fn bi_log2(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    math_logarithm("log2", args, input, f64::log2)
}

/// exp(x) - e raised to x. A result too large for a Float is E_BAD_VALUE, never
/// an inf.
/// Args:
///   - x: Number (or the piped number)
/// Returns: Float
///
/// Example:
///   exp(0)          # 1
///   exp(1000)       # E_BAD_VALUE: the result is not a finite Float
fn bi_exp(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (x, rest) = math_subject("exp", args, input)?;
    if !rest.is_empty() {
        return Err(arity_error("exp", "one number", rest.len()));
    }
    math_result("exp", x.exp())
}

/// sqrt(number) - Calculate square root
/// Args:
///   - number: Number
/// Returns: Float - Square root
///
/// Example:
///   sqrt(16)     # Returns 4.0
fn bi_sqrt(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let val = if args.is_empty() {
        input.ok_or_else(|| crate::safety::arg_err("sqrt requires number argument"))?
    } else {
        args[0].clone()
    };

    let num = match val {
        Value::Int(n) => n as f64,
        Value::Float(f) => f,
        _ => return Err(crate::safety::arg_err("sqrt requires numeric input")),
    };

    if num < 0.0 {
        // A domain error, not a type error: the generic hint would restate the
        // signature ("sqrt takes Number"), which the argument already matches.
        return Err(crate::safety::bad_arg_with_hint(
            "sqrt",
            "a number >= 0",
            &format!("{num}"),
            "sqrt is undefined below zero: take sqrt of abs(x), or check the sign first",
        ));
    }

    Ok(Value::Float(num.sqrt()))
}

/// pow(base, exponent) - Calculate power
/// Args:
///   - base: Number
///   - exponent: Number
/// Returns: Number - base ^ exponent
///
/// Example:
///   pow(2, 8)     # Returns 256
/// A number in an error message. The operand may have been an Int that the
/// builtin widened (`pow(0, -1)`), so an integral value stays bare (`0 ** -1`).
/// Rust's `{}` prints a huge or tiny Float in full (1e300 is 301 digits), so
/// those use the exponent form.
fn float_for_message(x: f64) -> String {
    let a = x.abs();
    if a != 0.0 && (a >= 1e16 || a < 1e-4) {
        format!("{x:e}")
    } else {
        format!("{x}")
    }
}

fn bi_pow(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "pow requires two arguments: base and exponent",
        ));
    }

    let base = match &args[0] {
        Value::Int(n) => *n as f64,
        Value::Float(f) => *f,
        _ => return Err(crate::safety::arg_err("pow requires numeric base")),
    };

    let exp = match &args[1] {
        Value::Int(n) => *n as f64,
        Value::Float(f) => *f,
        _ => return Err(crate::safety::arg_err("pow requires numeric exponent")),
    };

    // Int to a non-negative Int stays an exact Int, as the `**` operator does. An
    // overflow is refused, never saturated: the same refusal as `2 * 4611686018427387904`.
    if let (Value::Int(b), Value::Int(e)) = (&args[0], &args[1]) {
        if *e >= 0 {
            let overflow = || {
                crate::safety::value_not_representable(
                    "pow",
                    format!(
                        "integer overflow in operator Pow: {b} ** {e} does not fit in a 64-bit Int"
                    ),
                    "use a Float: pow(2.0, 100)",
                )
            };
            let exp32 = u32::try_from(*e).map_err(|_| overflow())?;
            return b.checked_pow(exp32).map(Value::Int).ok_or_else(overflow);
        }
    }

    // Zero to a negative power is 1 / 0, which `/` refuses as a division by zero.
    if base == 0.0 && exp < 0.0 {
        return Err(crate::safety::bad_value_in(
            "pow",
            format!(
                "division by zero: {} ** {}",
                float_for_message(base),
                float_for_message(exp)
            ),
            "a zero base needs an exponent of 0 or more; guard the base before raising it",
        ));
    }

    let result = base.powf(exp);
    // IronShell numbers are finite: an overflow (10 ** 400) or a NaN (a negative
    // base to a fractional power) is refused rather than returned as inf or NaN.
    if result.is_infinite() {
        return Err(crate::safety::value_not_representable(
            "pow",
            format!(
                "math_pow: {} ** {} overflows a Float",
                float_for_message(base),
                float_for_message(exp)
            ),
            "use a smaller base or exponent: the largest Float is about 1.8e308",
        ));
    }
    if result.is_nan() {
        return Err(crate::safety::value_not_representable(
            "pow",
            format!(
                "math_pow: {} ** {} is not a real number",
                float_for_message(base),
                float_for_message(exp)
            ),
            "a negative base needs a whole-number exponent",
        ));
    }

    // Return Int if result is a whole number and both inputs were Int
    if matches!((&args[0], &args[1]), (Value::Int(_), Value::Int(_))) && result.fract() == 0.0 {
        Ok(Value::Int(result as i64))
    } else {
        Ok(Value::Float(result))
    }
}

// ==================== Utility Functions ====================

/// The arguments the running script was given (`ish script.ish a b`). Set once
/// at startup by `main`; empty for `-c`, stdin and the REPL.
static SCRIPT_ARGS: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();

/// Record the arguments of the script about to run. Only the first call counts.
pub fn set_script_args(args: Vec<String>) {
    let _ = SCRIPT_ARGS.set(args);
}

/// Set when the program came from `ish -c`, where `args()` is always empty.
static RUN_UNDER_C: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Record that the program is a `-c` one-liner. Called once by `main`.
pub fn set_run_under_c() {
    RUN_UNDER_C.store(true, std::sync::atomic::Ordering::Relaxed);
}

/// Whether the program came from `ish -c` (no script file, so no `args()`).
pub fn run_under_c() -> bool {
    RUN_UNDER_C.load(std::sync::atomic::Ordering::Relaxed)
}

/// The script's arguments in order: what `args()` returns and what `$1`..`$9`
/// name under `ish -b script.sh a b`.
pub fn script_args() -> &'static [String] {
    match SCRIPT_ARGS.get() {
        Some(args) => args.as_slice(),
        None => &[],
    }
}

/// args() - The arguments the running script was given, as an Array of Strings.
///
/// `ish script.ish a b` gives `["a", "b"]`. The array is empty when there are no
/// arguments, and always under `-c`, stdin and the REPL, where no script runs.
///
/// Example:
///   args()     # [] in the REPL
fn bi_args(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("args", &input)?;
    if !args.is_empty() {
        return Err(crate::safety::bad_arg(
            "args",
            "no arguments",
            &format!("{} arguments", args.len()),
        ));
    }
    Ok(Value::Array(
        script_args()
            .iter()
            .map(|a| Value::Str(a.clone()))
            .collect(),
    ))
}

/// The operand of a conversion: its first argument, or the pipeline input.
fn conversion_operand<'a>(
    builtin: &str,
    args: &'a [Value],
    input: &'a Option<Value>,
) -> Result<&'a Value> {
    if args.len() > 1 {
        return Err(crate::safety::bad_arg(
            builtin,
            "one value to convert",
            &format!("{} arguments", args.len()),
        ));
    }
    match args.first().or(input.as_ref()) {
        Some(value) => Ok(value),
        None => Err(crate::safety::bad_arg(
            builtin,
            "a value to convert",
            "nothing",
        )),
    }
}

/// The hint for text that is not a number of the wanted kind. It names the
/// other conversion, because that is the one that accepts the text.
const NUMBER_TEXT_HINT: &str = "float(\"1.5\") parses decimals; int(\"42\") parses whole numbers";

/// int(x) - Convert a value to an Int.
/// Args:
///   - x: Int, Float, String or Bool (or the pipeline input)
/// Returns: Int
///
/// An Int is returned as it is, and a Bool is 1 or 0. A Float is truncated
/// toward zero; NaN, infinity and a Float outside the Int range are refused. A
/// String is parsed as a whole number, with surrounding whitespace and an
/// optional sign allowed. Anything else, such as "1.5", "abc" or "", is refused
/// and the refusal names the text.
///
/// Example:
///   int("42")      # 42
///   int(3.9)       # 3
fn bi_int(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let value = conversion_operand("int", &args, &input)?;
    match value {
        Value::Int(n) => Ok(Value::Int(*n)),
        Value::Bool(b) => Ok(Value::Int(i64::from(*b))),
        Value::Float(f) => {
            // The bounds are the Int range as Floats: 2^63 is the first value
            // past i64::MAX, and -2^63 is i64::MIN exactly.
            let truncated = f.trunc();
            if !f.is_finite()
                || truncated < -9_223_372_036_854_775_808.0
                || truncated >= 9_223_372_036_854_775_808.0
            {
                return Err(crate::safety::value_not_representable(
                    "int",
                    format!("int: {f} has no Int value"),
                    "an Int holds whole numbers from -9223372036854775808 to 9223372036854775807",
                ));
            }
            Ok(Value::Int(truncated as i64))
        }
        Value::Str(text) => match text.trim().parse::<i64>() {
            Ok(n) => Ok(Value::Int(n)),
            // A whole number too large for an Int is named as such, not as
            // "not a whole number", which it is.
            Err(e)
                if matches!(
                    e.kind(),
                    std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow
                ) =>
            {
                Err(crate::safety::value_not_representable(
                    "int",
                    format!(
                        "int: {text:?} does not fit in a 64-bit Int (-9223372036854775808 to 9223372036854775807)"
                    ),
                    &format!(
                        "float({text:?}) reads it as a Float instead, which is approximate for a number this large"
                    ),
                ))
            }
            Err(_) => Err(crate::safety::value_not_representable(
                "int",
                format!("int: {text:?} is not a decimal integer (digits with an optional sign)"),
                NUMBER_TEXT_HINT,
            )),
        },
        other => Err(crate::safety::bad_arg(
            "int",
            "an Int, Float, String or Bool",
            other.type_name(),
        )),
    }
}

/// float(x) - Convert a value to a Float.
/// Args:
///   - x: Int, Float or String (or the pipeline input)
/// Returns: Float
///
/// A String is parsed as a decimal, with surrounding whitespace allowed and
/// exponents such as "1e3" accepted. Text that is not a finite number, such as
/// "abc", "" or "inf", is refused and the refusal names the text.
///
/// Example:
///   float("1e3")   # 1000.0
///   float(2)       # 2.0
fn bi_float(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let value = conversion_operand("float", &args, &input)?;
    match value {
        Value::Float(f) => Ok(Value::Float(*f)),
        Value::Int(n) => Ok(Value::Float(*n as f64)),
        Value::Str(text) => match text.trim().parse::<f64>() {
            Ok(f) if f.is_finite() => Ok(Value::Float(f)),
            // "inf", "infinity" and "nan" parse as Floats, and are refused here.
            Ok(_) => Err(crate::safety::value_not_representable(
                "float",
                format!("float: IronShell numbers are finite: {text:?} is not accepted"),
                "write the number itself, such as 1.5 or 1e300; there is no infinity or NaN",
            )),
            _ => Err(crate::safety::value_not_representable(
                "float",
                format!("float: {text:?} is not a number"),
                NUMBER_TEXT_HINT,
            )),
        },
        other => Err(crate::safety::bad_arg(
            "float",
            "an Int, Float or String",
            other.type_name(),
        )),
    }
}

/// now_iso(zone?) - The current time as an ISO 8601 / RFC 3339 String.
/// Args:
///   - zone: String (optional) - "utc" (the default) or "local"
/// Returns: String, to the second
///
/// In UTC it ends in `Z`: 2026-11-08T14:03:05Z. With "local" it is the local
/// time with its offset from UTC: 2026-11-08T06:03:05-08:00.
///
/// Example:
///   now_iso()          # e.g. "2026-11-08T14:03:05Z"
fn bi_now_iso(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("now_iso", &input)?;
    let local = match args.as_slice() {
        [] => false,
        [Value::Str(zone)] if zone.as_str() == "utc" => false,
        [Value::Str(zone)] if zone.as_str() == "local" => true,
        [Value::Str(zone)] => {
            return Err(crate::safety::bad_arg_in(
                "now_iso",
                format!("now_iso: expected \"utc\" or \"local\", got {zone:?}"),
                "only utc and local are supported",
            ))
        }
        [other] => {
            return Err(crate::safety::bad_arg(
                "now_iso",
                "\"utc\" or \"local\"",
                other.type_name(),
            ))
        }
        _ => {
            return Err(crate::safety::bad_arg(
                "now_iso",
                "at most one argument, the zone",
                &format!("{} arguments", args.len()),
            ))
        }
    };
    let text = if local {
        chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, false)
    } else {
        chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
    };
    Ok(Value::Str(text))
}

// --- Strings, dates and TOML (round 9) ---

/// The largest a compiled string regex may be, in bytes. `regex` refuses a
/// pattern whose program or lazy DFA would exceed it, so a hostile pattern
/// cannot take the shell's memory.
const REGEX_SIZE_LIMIT: usize = 1 << 20;

/// The widest a padded text may be, in characters. A larger width is refused
/// rather than allocated.
const PAD_WIDTH_MAX: i64 = 1_000_000;

/// The text a string builtin works on, and the arguments after it. A piped text
/// is the subject, so every argument is a parameter; a direct call takes the
/// text first, as `replace` does.
fn text_subject(
    builtin: &str,
    args: Vec<Value>,
    input: Option<Value>,
) -> Result<(String, Vec<Value>)> {
    match input {
        Some(Value::Str(text) | Value::Uri(text)) => Ok((text, args)),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            "a String as the piped text",
            other.type_name(),
        )),
        None => {
            let mut args = args;
            if args.is_empty() {
                return Err(crate::safety::bad_arg(builtin, "a String text", "nothing"));
            }
            let first = args.remove(0);
            let text = string_arg(builtin, "a String text", &first)?.to_string();
            Ok((text, args))
        }
    }
}

/// A String argument, or a Uri, which is text too.
fn string_arg<'a>(builtin: &str, expected: &str, value: &'a Value) -> Result<&'a str> {
    match value {
        Value::Str(s) | Value::Uri(s) => Ok(s.as_str()),
        other => Err(crate::safety::bad_arg(builtin, expected, other.type_name())),
    }
}

/// The refusal for the wrong number of arguments.
fn arity_error(builtin: &str, expected: &str, got: usize) -> anyhow::Error {
    crate::safety::bad_arg(builtin, expected, &format!("{got} arguments"))
}

/// pad_left(text, width, fill?) - Pad a String on the left to a width.
/// Args:
///   - text: String (or the piped text)
///   - width: Int - the width in characters, 0 to 1000000
///   - fill: String (optional) - exactly one character, " " by default
/// Returns: String
///
/// A text already at or over the width is returned unchanged.
///
/// Example:
///   pad_left("7", 3, "0")    # "007"
///   "7" | pad_left(3)        # "  7"
fn bi_pad_left(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pad_text("pad_left", args, input, true)
}

/// pad_right(text, width, fill?) - Pad a String on the right to a width. The
/// same as pad_left, with the fill after the text.
///
/// Example:
///   pad_right("ab", 4, ".")  # "ab.."
fn bi_pad_right(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pad_text("pad_right", args, input, false)
}

fn pad_text(builtin: &str, args: Vec<Value>, input: Option<Value>, left: bool) -> Result<Value> {
    let (text, rest) = text_subject(builtin, args, input)?;
    let (width, fill) = match rest.as_slice() {
        [] => return Err(crate::safety::bad_arg(builtin, "a width Int", "nothing")),
        [Value::Int(width)] => (*width, " "),
        [Value::Int(width), fill] => (
            *width,
            string_arg(builtin, "a one-character String fill", fill)?,
        ),
        [_, _, _, ..] => {
            return Err(arity_error(
                builtin,
                "a width and an optional fill",
                rest.len(),
            ));
        }
        [other, ..] => {
            return Err(crate::safety::bad_arg(
                builtin,
                "a width Int",
                other.type_name(),
            ))
        }
    };
    if width < 0 {
        return Err(crate::safety::bad_arg(
            builtin,
            "a width of 0 or more",
            &width.to_string(),
        ));
    }
    if width > PAD_WIDTH_MAX {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("a width of at most {PAD_WIDTH_MAX}"),
            &width.to_string(),
        ));
    }
    let mut marks = fill.chars();
    let fill_char = match (marks.next(), marks.next()) {
        (Some(c), None) => c,
        _ => {
            return Err(crate::safety::bad_arg(
                builtin,
                "a fill of exactly one character",
                &format!("{fill:?}"),
            ))
        }
    };
    let wanted = usize::try_from(width).unwrap_or(0);
    let len = text.chars().count();
    if len >= wanted {
        return Ok(Value::Str(text));
    }
    let pad = fill_char.to_string().repeat(wanted - len);
    Ok(Value::Str(if left { pad + &text } else { text + &pad }))
}

/// A regex compiled the way the string regex builtins need it. A pattern the
/// regex crate refuses, including one over the size cap, is E_BAD_ARG, and the
/// refusal names the pattern and the regex error.
fn text_regex(builtin: &str, pattern: &str) -> Result<regex::Regex> {
    regex::RegexBuilder::new(pattern)
        .size_limit(REGEX_SIZE_LIMIT)
        .dfa_size_limit(REGEX_SIZE_LIMIT)
        .build()
        .map_err(|e| {
            crate::safety::bad_arg_in(
                builtin,
                format!(
                    "{builtin}: invalid regex {}: {}",
                    quoted_pattern(pattern),
                    regex_error_detail(&e)
                ),
                "write the pattern in Rust regex syntax; escape a literal . ( ) [ ] * + ? with a backslash; compiled patterns are limited to 1 MiB",
            )
        })
}

/// The reason a regex was refused, without the copy of the whole pattern that
/// the regex crate's syntax error prints above it: its `error:` line alone.
fn regex_error_detail(e: &regex::Error) -> String {
    let full = e.to_string();
    full.lines()
        .find_map(|l| l.trim().strip_prefix("error: "))
        .map(str::to_string)
        .unwrap_or(full)
}

/// A regex pattern as an error quotes it: at most its first 60 characters,
/// then the length in characters, so a huge pattern does not fill the error.
fn quoted_pattern(pattern: &str) -> String {
    const SHOWN: usize = 60;
    let total = pattern.chars().count();
    if total <= SHOWN {
        return format!("{pattern:?}");
    }
    let head: String = pattern.chars().take(SHOWN).collect();
    format!("{head:?}… ({total} characters)")
}

/// A character offset for a byte offset a regex reported.
fn char_offset(text: &str, byte: usize) -> i64 {
    (text.get(..byte).map_or(0, |s| s.chars().count())) as i64
}

/// A regex match as a Record: its text, its capture groups (null for a group
/// that did not take part), where it sits in characters, and its named groups
/// as a Record of name to String or null (empty when the pattern names none).
fn match_record(re: &regex::Regex, text: &str, caps: &regex::Captures<'_>) -> Value {
    let (matched, start, end) = match caps.get(0) {
        Some(m) => (
            m.as_str().to_string(),
            char_offset(text, m.start()),
            char_offset(text, m.end()),
        ),
        None => (String::new(), 0, 0),
    };
    fn group_value(group: Option<regex::Match<'_>>) -> Value {
        match group {
            Some(g) => Value::Str(g.as_str().to_string()),
            None => Value::Null,
        }
    }
    let groups = caps.iter().skip(1).map(group_value).collect();
    let named: BTreeMap<String, Value> = re
        .capture_names()
        .enumerate()
        .filter_map(|(index, name)| {
            name.map(|name| (name.to_string(), group_value(caps.get(index))))
        })
        .collect();
    let mut record = BTreeMap::new();
    record.insert("match".to_string(), Value::Str(matched));
    record.insert("groups".to_string(), Value::Array(groups));
    record.insert("named".to_string(), Value::Record(named));
    record.insert("start".to_string(), Value::Int(start));
    record.insert("end".to_string(), Value::Int(end));
    Value::Record(record)
}

/// regex_match(text, pattern) - Whether a regex matches anywhere in a String.
/// Args:
///   - text: String (or the piped text)
///   - pattern: String - a Rust regex pattern
/// Returns: Bool
///
/// Example:
///   "abc" | regex_match("b")     # true
fn bi_regex_match(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "regex_match";
    let (text, rest) = text_subject(B, args, input)?;
    let [pattern] = rest.as_slice() else {
        return Err(arity_error(B, "a pattern", rest.len()));
    };
    let re = text_regex(B, string_arg(B, "a String pattern", pattern)?)?;
    Ok(Value::Bool(re.is_match(&text)))
}

/// regex_find(text, pattern) - The first match of a regex, as a Record.
/// Args:
///   - text: String (or the piped text)
///   - pattern: String - a Rust regex pattern
/// Returns: Record {match: String, groups: Array, named: Record, start: Int, end: Int}, or null
///
/// groups holds each capture group as a String, or null for a group that did
/// not take part. named holds each named group (?P<name>...) as a String or
/// null, and is an empty Record when the pattern names no group. start and end
/// are character offsets, end exclusive.
///
/// Example:
///   regex_find("a1b22", "[0-9]+").start   # 1
///   regex_find("ab", "b").end             # 2
///   regex_find("2024-02", "(?P<y>[0-9]+)-(?P<m>[0-9]+)").named.m   # "02"
///   regex_find("abc", "z")                # null
fn bi_regex_find(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "regex_find";
    let (text, rest) = text_subject(B, args, input)?;
    let [pattern] = rest.as_slice() else {
        return Err(arity_error(B, "a pattern", rest.len()));
    };
    let re = text_regex(B, string_arg(B, "a String pattern", pattern)?)?;
    Ok(match re.captures(&text) {
        Some(caps) => match_record(&re, &text, &caps),
        None => Value::Null,
    })
}

/// regex_find_all(text, pattern) - Every match of a regex, left to right.
/// Args:
///   - text: String (or the piped text)
///   - pattern: String - a Rust regex pattern
/// Returns: Array of the records regex_find returns; [] when nothing matches
///
/// Example:
///   regex_find_all("a1b22", "[0-9]+") | len    # 2
fn bi_regex_find_all(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "regex_find_all";
    let (text, rest) = text_subject(B, args, input)?;
    let [pattern] = rest.as_slice() else {
        return Err(arity_error(B, "a pattern", rest.len()));
    };
    let re = text_regex(B, string_arg(B, "a String pattern", pattern)?)?;
    Ok(Value::Array(
        re.captures_iter(&text)
            .map(|caps| match_record(&re, &text, &caps))
            .collect(),
    ))
}

/// regex_split(text, pattern) - Split a String at every match of a regex.
/// Args:
///   - text: String (or the piped text)
///   - pattern: String - a Rust regex pattern
/// Returns: Array of String
///
/// Rust regex split semantics: a match at the start or end of the text gives an
/// empty piece there, and text with no match is one piece.
///
/// Example:
///   regex_split("a1b22c", "[0-9]+")    # ["a", "b", "c"]
///   "a, b;c" | regex_split("[,;] *")   # ["a", "b", "c"]
fn bi_regex_split(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "regex_split";
    let (text, rest) = text_subject(B, args, input)?;
    let [pattern] = rest.as_slice() else {
        return Err(arity_error(B, "a pattern", rest.len()));
    };
    let re = text_regex(B, string_arg(B, "a String pattern", pattern)?)?;
    Ok(Value::Array(
        re.split(&text).map(|s| Value::Str(s.to_string())).collect(),
    ))
}

/// index_of(text, sub) / last_index_of(text, sub): the character offset of the
/// first (or last) occurrence of `sub` in `text`, or -1.
fn index_of_impl(
    builtin: &str,
    args: Vec<Value>,
    input: Option<Value>,
    last: bool,
) -> Result<Value> {
    let (text, rest) = text_subject(builtin, args, input)?;
    let [sub] = rest.as_slice() else {
        return Err(arity_error(builtin, "a substring", rest.len()));
    };
    let sub = string_arg(builtin, "a String substring", sub)?;
    let at = if last {
        text.rfind(sub)
    } else {
        text.find(sub)
    };
    Ok(Value::Int(match at {
        Some(byte) => text[..byte].chars().count() as i64,
        None => -1,
    }))
}

/// index_of(text, sub) - The character offset of the first occurrence of sub.
/// Args:
///   - text: String (or the piped text)
///   - sub: String - the text to look for
/// Returns: Int - the offset in characters (not bytes), or -1 when absent
///
/// Example:
///   index_of("hello", "l")    # 2
///   index_of("héllo", "l")    # 2
///   index_of("hello", "z")    # -1
fn bi_index_of(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    index_of_impl("index_of", args, input, false)
}

/// last_index_of(text, sub) - The character offset of the last occurrence of sub.
///
/// Example:
///   last_index_of("hello", "l")    # 3
fn bi_last_index_of(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    index_of_impl("last_index_of", args, input, true)
}

/// regex_replace(text, pattern, replacement) - Replace every regex match.
/// Args:
///   - text: String (or the piped text)
///   - pattern: String - a Rust regex pattern
///   - replacement: String - $1, ${name} and $$ expand as the regex crate expands them
/// Returns: String
///
/// Example:
///   regex_replace("a1b2", "([0-9])", "<$1>")    # "a<1>b<2>"
fn bi_regex_replace(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "regex_replace";
    let (text, rest) = text_subject(B, args, input)?;
    let [pattern, replacement] = rest.as_slice() else {
        return Err(arity_error(B, "a pattern and a replacement", rest.len()));
    };
    let re = text_regex(B, string_arg(B, "a String pattern", pattern)?)?;
    let replacement = string_arg(B, "a String replacement", replacement)?;
    check_replacement_groups(B, &re, replacement)?;
    Ok(Value::Str(re.replace_all(&text, replacement).into_owned()))
}

/// The group references a replacement makes, read as the regex crate reads
/// them: `$` then the longest run of letters, digits and underscores is a name,
/// `${name}` braces it, and `$$` is a literal dollar. Any other `$` is literal.
fn replacement_references(replacement: &str) -> Vec<&str> {
    let bytes = replacement.as_bytes();
    let is_name = |b: u8| b == b'_' || b.is_ascii_alphanumeric();
    let mut refs = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'$' {
            i += 1;
            continue;
        }
        if bytes.get(i + 1) == Some(&b'$') {
            i += 2;
            continue;
        }
        let braced = bytes.get(i + 1) == Some(&b'{');
        let start = i + 1 + usize::from(braced);
        let mut end = start;
        while end < bytes.len() && is_name(bytes[end]) {
            end += 1;
        }
        if end == start || (braced && bytes.get(end) != Some(&b'}')) {
            i += 1;
            continue;
        }
        refs.push(&replacement[start..end]);
        i = if braced { end + 1 } else { end };
    }
    refs
}

/// The refusal for a replacement that names a group the pattern does not have.
/// The regex crate expands such a reference to nothing, so "<$5>" silently lost
/// its text. A reference to a group the pattern has is unchanged.
fn check_replacement_groups(builtin: &str, re: &regex::Regex, replacement: &str) -> Result<()> {
    let count = re.captures_len() - 1;
    let names: Vec<Option<&str>> = re.capture_names().skip(1).collect();
    for reference in replacement_references(replacement) {
        let numeric = reference.bytes().all(|b| b.is_ascii_digit());
        let known = if numeric {
            reference.parse::<usize>().is_ok_and(|n| n <= count)
        } else {
            names.contains(&Some(reference))
        };
        if known {
            continue;
        }
        let listed = if count == 0 {
            "the pattern has no groups besides the whole match, group 0".to_string()
        } else {
            let items: Vec<String> = (1..=count)
                .map(|i| match names.get(i - 1).copied().flatten() {
                    Some(name) => format!("{i} ({name})"),
                    None => i.to_string(),
                })
                .collect();
            format!("the pattern has {count} group(s): {}", items.join(", "))
        };
        let digits = reference.bytes().take_while(u8::is_ascii_digit).count();
        let hint = if digits > 0 && !numeric {
            let (number, rest) = reference.split_at(digits);
            format!("write ${{{number}}}{rest} to put {rest} after group {number}")
        } else if count == 0 {
            "write $0 for the whole match, or add a group to the pattern".to_string()
        } else {
            format!("use a group number from 0 to {count}, or the name of a group the pattern has")
        };
        return Err(crate::safety::bad_arg_in(
            builtin,
            format!(
                "{builtin}: the replacement refers to group '{reference}', which the pattern does not have; {listed}"
            ),
            &hint,
        ));
    }
    Ok(())
}

/// The plural name of a unit the date builtins take. The case is ignored and
/// the singular is accepted, so "DAY", "Week" and "months" all name a unit.
fn canonical_unit(unit: &str) -> Option<&'static str> {
    Some(match unit.to_ascii_lowercase().as_str() {
        "day" | "days" => "days",
        "week" | "weeks" => "weeks",
        "month" | "months" => "months",
        "year" | "years" => "years",
        "hour" | "hours" => "hours",
        "minute" | "minutes" => "minutes",
        "second" | "seconds" => "seconds",
        _ => return None,
    })
}

/// The seconds in one of the units the date builtins take.
fn unit_seconds(builtin: &str, unit: &str) -> Result<i64> {
    match unit {
        "days" => Ok(86_400),
        "hours" => Ok(3_600),
        "minutes" => Ok(60),
        "seconds" => Ok(1),
        other => Err(crate::safety::bad_arg(
            builtin,
            "a unit: days, hours, minutes or seconds",
            other,
        )),
    }
}

/// An ISO 8601 / RFC 3339 datetime, or a `YYYY-MM-DD` date, as a UTC instant.
/// The flag is true for a date alone, which is midnight UTC.
fn iso_instant(text: &str) -> Option<(chrono::DateTime<chrono::Utc>, bool)> {
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(text) {
        return Some((dt.with_timezone(&chrono::Utc), false));
    }
    // A datetime with a space or a T and no zone is UTC, as the RFC 3339 form is.
    let naive = chrono::NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S")
        .or_else(|_| chrono::NaiveDateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S"));
    if let Ok(naive) = naive {
        return Some((naive.and_utc(), false));
    }
    let date = chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d").ok()?;
    Some((date.and_hms_opt(0, 0, 0)?.and_utc(), true))
}

/// The refusal for text that is not a date in the form asked for.
fn not_a_date(builtin: &str, text: &str) -> anyhow::Error {
    crate::safety::value_not_representable(
        builtin,
        format!("{builtin}: {text:?} is not a date"),
        "write an ISO 8601 date such as 2024-02-29, or a datetime such as 2024-02-29T10:00:00Z",
    )
}

/// The refusal for a year outside 0001 to 9999, the four-digit years of ISO 8601.
fn year_out_of_range(builtin: &str, text: &str) -> anyhow::Error {
    crate::safety::value_not_representable(
        builtin,
        format!("{builtin}: {text:?} is out of range: the year must be from 0001 to 9999"),
        "ISO 8601 years are four digits, 0001 to 9999, with no sign",
    )
}

/// Whether a year is one the date builtins read and write.
fn year_in_range(year: i32) -> bool {
    (1..=9999).contains(&year)
}

/// Refuse date text that is date-shaped but not in the strict ISO form: a
/// signed or five-digit year (E_BAD_VALUE), a field that is not zero-padded
/// (`2024-2-9`, `T1:2:3`), or a leap second (`23:59:60`) (E_BAD_ARG). Text that
/// does not look like a date is left to the parser, which refuses it as not a date.
fn check_iso_shape(builtin: &str, text: &str, canon: &str) -> Result<()> {
    let b = canon.as_bytes();
    let signed = matches!(b.first(), Some(b'+' | b'-')) && b.get(1).is_some_and(u8::is_ascii_digit);
    let start = usize::from(signed);
    let year_len = b[start..].iter().take_while(|c| c.is_ascii_digit()).count();
    if year_len == 0 || b.get(start + year_len) != Some(&b'-') {
        return Ok(());
    }
    if signed || year_len > 4 {
        return Err(year_out_of_range(builtin, text));
    }
    let digits = |s: &[u8]| s.iter().all(u8::is_ascii_digit);
    let not_padded = |what: &str| {
        crate::safety::bad_arg_in(
            builtin,
            format!("{builtin}: {text:?} is not zero-padded: expected {what}"),
            "write every field with its full width: 2024-02-09, or 2024-02-09T08:05:03Z",
        )
    };
    let padded_date = year_len == 4
        && b.len() >= 10
        && b[4] == b'-'
        && digits(&b[5..7])
        && b[7] == b'-'
        && digits(&b[8..10]);
    if !padded_date {
        return Err(not_padded("YYYY-MM-DD"));
    }
    if let Some(&sep) = b.get(10) {
        if sep == b'T' || sep == b' ' {
            let t = &b[11..];
            let padded_clock = t.len() >= 5 && digits(&t[0..2]) && t[2] == b':' && digits(&t[3..5]);
            if !padded_clock {
                return Err(not_padded("YYYY-MM-DDTHH:MM[:SS]"));
            }
            if t.get(5) == Some(&b':') {
                if !(t.len() >= 8 && digits(&t[6..8])) {
                    return Err(not_padded("YYYY-MM-DDTHH:MM:SS"));
                }
                if &t[6..8] == b"60" {
                    return Err(leap_second(builtin, text));
                }
            }
        }
    }
    Ok(())
}

fn leap_second(builtin: &str, text: &str) -> anyhow::Error {
    crate::safety::bad_arg_in(
        builtin,
        format!("{builtin}: {text:?} has a leap second: leap seconds are not supported"),
        "write second 59 or the next minute; seconds run from 00 to 59",
    )
}

/// The checks on a parsed instant: no leap second, and a year from 0001 to 9999.
fn check_instant(builtin: &str, text: &str, instant: chrono::DateTime<chrono::Utc>) -> Result<()> {
    use chrono::{Datelike as _, Timelike as _};
    if instant.nanosecond() >= 1_000_000_000 {
        return Err(leap_second(builtin, text));
    }
    if !year_in_range(instant.year()) {
        return Err(year_out_of_range(builtin, text));
    }
    Ok(())
}

/// The extended ISO 8601 spelling of text written in one of the other forms the
/// date builtins read: the basic date `20240229`, a time without seconds
/// (`13:05`, `1305`), the basic time `130509`, a `t` or space before the time,
/// and an offset written `+0530`, `-08` or `z`. Text in none of those forms is
/// returned as it is, for the checks and the parser to refuse by name.
fn canonical_iso(text: &str) -> String {
    if !text.is_ascii() {
        return text.to_string();
    }
    let b = text.as_bytes();
    let digits = |s: &[u8]| s.iter().all(u8::is_ascii_digit);
    let (date, rest) = if b.len() >= 10
        && digits(&b[0..4])
        && b[4] == b'-'
        && digits(&b[5..7])
        && b[7] == b'-'
        && digits(&b[8..10])
    {
        (text[..10].to_string(), &text[10..])
    } else if b.len() >= 8 && digits(&b[0..8]) {
        (
            format!("{}-{}-{}", &text[0..4], &text[4..6], &text[6..8]),
            &text[8..],
        )
    } else {
        return text.to_string();
    };
    if rest.is_empty() {
        return date;
    }
    if !matches!(rest.as_bytes()[0], b'T' | b't' | b' ') {
        return text.to_string();
    }
    let body = &rest[1..];
    let zone_at = body.find(['Z', 'z', '+', '-']).unwrap_or(body.len());
    let (time, zone) = body.split_at(zone_at);
    let (clock, frac) = match time.find('.') {
        Some(i) => time.split_at(i),
        None => (time, ""),
    };
    let c = clock.as_bytes();
    let (clock, has_seconds) = if c.len() == 6 && digits(c) {
        (
            format!("{}:{}:{}", &clock[0..2], &clock[2..4], &clock[4..6]),
            true,
        )
    } else if c.len() == 4 && digits(c) {
        (format!("{}:{}:00", &clock[0..2], &clock[2..4]), false)
    } else if c.len() == 5 && digits(&c[0..2]) && c[2] == b':' && digits(&c[3..5]) {
        (format!("{clock}:00"), false)
    } else if c.len() == 8
        && digits(&c[0..2])
        && c[2] == b':'
        && digits(&c[3..5])
        && c[5] == b':'
        && digits(&c[6..8])
    {
        (clock.to_string(), true)
    } else {
        return text.to_string();
    };
    if !has_seconds && !frac.is_empty() {
        return text.to_string();
    }
    let z = zone.as_bytes();
    let zone = if z.is_empty() {
        String::new()
    } else if zone == "Z" || zone == "z" {
        "Z".to_string()
    } else if matches!(z[0], b'+' | b'-') && digits(&z[1..]) && z.len() == 3 {
        format!("{zone}:00")
    } else if matches!(z[0], b'+' | b'-') && digits(&z[1..]) && z.len() == 5 {
        format!("{}:{}", &zone[..3], &zone[3..])
    } else if matches!(z[0], b'+' | b'-')
        && z.len() == 6
        && digits(&z[1..3])
        && z[3] == b':'
        && digits(&z[4..6])
    {
        zone.to_string()
    } else {
        return text.to_string();
    };
    format!("{date}T{clock}{frac}{zone}")
}

fn parse_iso(builtin: &str, text: &str) -> Result<(chrono::DateTime<chrono::Utc>, bool)> {
    let canon = canonical_iso(text);
    check_iso_shape(builtin, text, &canon)?;
    let (instant, date_only) = iso_instant(&canon).ok_or_else(|| not_a_date(builtin, text))?;
    check_instant(builtin, text, instant)?;
    Ok((instant, date_only))
}

/// The ISO 8601 text of an instant: `2024-02-29` for a date, otherwise the UTC
/// datetime to the second, or with its fraction, ending in `Z`.
fn iso_text(instant: chrono::DateTime<chrono::Utc>, date_only: bool) -> String {
    if date_only {
        instant.format("%Y-%m-%d").to_string()
    } else {
        instant.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)
    }
}

/// A strftime layout is refused when chrono cannot read one of its specifiers.
fn check_strftime(builtin: &str, layout: &str) -> Result<()> {
    let has_error = |text: &str| {
        chrono::format::StrftimeItems::new(text)
            .any(|item| matches!(item, chrono::format::Item::Error))
    };
    if has_error(layout) {
        // Name the first specifier chrono cannot read: each `%` with its flags
        // and width, up to the letter that ends it, is tried on its own.
        let mut rest = layout;
        let mut bad = None;
        while let Some(i) = rest.find('%') {
            let tail = &rest[i..];
            if tail[1..].starts_with('%') {
                rest = &tail[2..];
                continue;
            }
            let end = match tail[1..]
                .char_indices()
                .find(|(_, c)| c.is_alphabetic() || *c == '%')
            {
                Some((k, c)) if c == '%' => 1 + k,
                Some((k, c)) => 1 + k + c.len_utf8(),
                None => tail.len(),
            };
            if has_error(&tail[..end]) {
                bad = Some(&tail[..end]);
                break;
            }
            rest = &tail[end..];
        }
        let message = match bad {
            Some(spec) => format!(
                "{builtin}: {layout:?} is not a strftime format: {spec:?} is not a specifier chrono reads"
            ),
            None => format!("{builtin}: {layout:?} is not a strftime format"),
        };
        return Err(crate::safety::bad_arg_in(
            builtin,
            message,
            "use chrono's strftime specifiers, such as %Y-%m-%d or %d %B %Y",
        ));
    }
    Ok(())
}

/// Parse text in a strftime layout: with an offset it is that instant, without
/// one it is UTC, and a layout with no time is midnight UTC.
fn parse_with_layout(builtin: &str, text: &str, layout: &str) -> Result<Value> {
    if let Ok(dt) = chrono::DateTime::parse_from_str(text, layout) {
        let instant = dt.with_timezone(&chrono::Utc);
        check_instant(builtin, text, instant)?;
        return Ok(Value::Str(iso_text(instant, false)));
    }
    if let Ok(naive) = chrono::NaiveDateTime::parse_from_str(text, layout) {
        check_instant(builtin, text, naive.and_utc())?;
        return Ok(Value::Str(iso_text(naive.and_utc(), false)));
    }
    if let Some(midnight) = chrono::NaiveDate::parse_from_str(text, layout)
        .ok()
        .and_then(|date| date.and_hms_opt(0, 0, 0))
    {
        check_instant(builtin, text, midnight.and_utc())?;
        return Ok(Value::Str(iso_text(midnight.and_utc(), true)));
    }
    // With a format the format is what failed: naming the text as "not a date"
    // sent the agent to the ISO forms when its layout was the problem.
    Err(crate::safety::value_not_representable(
        builtin,
        format!("{builtin}: `{text}` does not match the format `{layout}`"),
        "the format is a chrono strftime layout: %Y year, %m month, %d day, %B month name, %H:%M:%S time, %z offset; every part of the text must be matched, so a layout with only %Y does not read a full date. Leave the format out to read ISO 8601",
    ))
}

/// date_parse(text, format?) - Read a date or datetime and answer it as ISO 8601.
/// Args:
///   - text: String (or the piped text)
///   - format: String (optional) - a chrono strftime layout, such as "%d/%m/%Y"
/// Returns: String
///
/// Without a format, RFC 3339 and `YYYY-MM-DD` are read, and so are the other
/// ISO 8601 spellings: seconds may be left out (`13:05`, read as `13:05:00`), the
/// date and time may be basic (`20240229T130509Z`), the separator may be `T`,
/// `t` or a space, and an offset may be `Z`, `+05:30`, `+0530` or `-08`. A datetime is answered
/// in UTC, ending in Z; an offset in the text is converted. A date is answered
/// as a date. Text that is not a date is E_BAD_VALUE and the refusal names it.
///
/// Example:
///   date_parse("2024-02-29")                        # "2024-02-29"
///   date_parse("2024-02-29T10:00:00+02:00")         # "2024-02-29T08:00:00Z"
///   date_parse("29/02/2024", "%d/%m/%Y")            # "2024-02-29"
///   date_parse("2024-02-29T13:05")                  # "2024-02-29T13:05:00Z"
///   date_parse("20240229T130509+0530")              # "2024-02-29T07:35:09Z"
fn bi_date_parse(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "date_parse";
    let (text, rest) = text_subject(B, args, input)?;
    match rest.as_slice() {
        [] => {
            let (instant, date_only) = parse_iso(B, &text)?;
            Ok(Value::Str(iso_text(instant, date_only)))
        }
        [layout] => {
            let layout = string_arg(B, "a strftime format String", layout)?;
            check_strftime(B, layout)?;
            parse_with_layout(B, &text, layout)
        }
        _ => Err(arity_error(B, "an optional format", rest.len())),
    }
}

/// date_diff(a, b, unit?) - The time from a to b, in whole units.
/// Args:
///   - a: String (or the piped text) - an ISO date or datetime, as date_parse answers
///   - b: String - the later date, in the same form
///   - unit: String (optional) - "days" (the default: whole 24-hour periods of elapsed time), "weeks", "months", "years", "hours", "minutes" or "seconds"; any case, and the singular, is accepted
/// Returns: Int - b minus a, in whole units, truncated toward zero
///
/// Months and years are calendar units, the inverse of date_add: the count is
/// the most whole months n for which date_add(a, n, "months") does not pass b.
///
/// Example:
///   date_diff("2024-02-29", "2026-11-09")                                # 984
///   date_diff("2024-02-29", "2026-11-09", "hours")                       # 23616
///   date_diff("2024-01-31", "2024-02-29", "months")                      # 1
///   date_diff("2026-11-01T23:00:00Z", "2026-11-02T01:00:00Z")            # 0
///   date_diff("2026-11-01T23:00:00Z", "2026-11-02T01:00:00Z", "hours")   # 2
fn bi_date_diff(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "date_diff";
    let (first, rest) = text_subject(B, args, input)?;
    let (second, unit) = match rest.as_slice() {
        [second] => (string_arg(B, "a second ISO date String", second)?, "days"),
        [second, unit] => (
            string_arg(B, "a second ISO date String", second)?,
            string_arg(
                B,
                "a unit String: days, weeks, months, years, hours, minutes or seconds",
                unit,
            )?,
        ),
        _ => {
            return Err(arity_error(
                B,
                "a second date and an optional unit",
                rest.len(),
            ))
        }
    };
    let (a, _) = parse_iso(B, &first)?;
    let (b, _) = parse_iso(B, second)?;
    let unit = canonical_unit(unit).ok_or_else(|| {
        crate::safety::bad_arg(
            B,
            "a unit: days, weeks, months, years, hours, minutes or seconds",
            unit,
        )
    })?;
    match unit {
        "weeks" => Ok(Value::Int((b - a).num_seconds() / (7 * 86_400))),
        "months" => Ok(Value::Int(whole_calendar_months(a, b))),
        "years" => Ok(Value::Int(whole_calendar_months(a, b) / 12)),
        _ => {
            let per = unit_seconds(B, unit).map_err(|_| {
                crate::safety::bad_arg(
                    B,
                    "a unit: days, weeks, months, years, hours, minutes or seconds",
                    unit,
                )
            })?;
            Ok(Value::Int((b - a).num_seconds() / per))
        }
    }
}

/// The whole calendar months from `a` to `b`, truncated toward zero: the
/// largest n (by magnitude, with b's sign) for which add_calendar_months(a, n)
/// does not pass b. The inverse of date_add's "months".
fn whole_calendar_months(
    a: chrono::DateTime<chrono::Utc>,
    b: chrono::DateTime<chrono::Utc>,
) -> i64 {
    use chrono::Datelike as _;
    let index = |d: chrono::DateTime<chrono::Utc>| i64::from(d.year()) * 12 + i64::from(d.month0());
    let mut n = index(b) - index(a);
    let passes = |n: i64| match add_calendar_months(a, n) {
        Some(d) if n >= 0 => d > b,
        Some(d) => d < b,
        None => true,
    };
    while n != 0 && passes(n) {
        n -= n.signum();
    }
    n
}

/// date_format(iso, format) - Format a date or datetime with a strftime layout.
/// Args:
///   - iso: String (or the piped text) - an ISO date or datetime; a date is midnight UTC
///   - format: String - a chrono strftime layout; `%f` is the nanoseconds (nine digits), `%6f` or `%.6f` the microseconds, `%3f` or `%.3f` the milliseconds; an unsupported specifier (`%^a`, `%L`) is refused by name
/// Returns: String
///
/// Example:
///   date_format("2024-02-29T10:00:00Z", "%d %B %Y")    # "29 February 2024"
///   date_format("2024-02-29T10:00:00.123456789Z", "%f")    # "123456789"
///   date_format("2024-02-29T10:00:00.123456789Z", "%6f")   # "123456"
fn bi_date_format(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use std::fmt::Write as _;
    const B: &str = "date_format";
    let (text, rest) = text_subject(B, args, input)?;
    let [layout] = rest.as_slice() else {
        return Err(arity_error(B, "a strftime format String", rest.len()));
    };
    let layout = string_arg(B, "a strftime format String", layout)?;
    check_strftime(B, layout)?;
    let (instant, _) = parse_iso(B, &text)?;
    let mut out = String::new();
    write!(out, "{}", instant.format(layout)).map_err(|_| {
        crate::safety::bad_arg_in(
            B,
            format!("{B}: {layout:?} cannot be written for {text:?}"),
            "use chrono's strftime specifiers, such as %Y-%m-%d or %d %B %Y",
        )
    })?;
    Ok(Value::Str(out))
}

/// The date a whole number of calendar months from `instant`. The day of the
/// month is kept, or clamped to the last day of the month it lands in, and the
/// time of day is kept. None when the date would leave chrono's range.
fn add_calendar_months(
    instant: chrono::DateTime<chrono::Utc>,
    months: i64,
) -> Option<chrono::DateTime<chrono::Utc>> {
    use chrono::Datelike as _;
    let index = i64::from(instant.year())
        .checked_mul(12)?
        .checked_add(i64::from(instant.month0()))?
        .checked_add(months)?;
    let year = i32::try_from(index.div_euclid(12)).ok()?;
    if !year_in_range(year) {
        return None;
    }
    let month = u32::try_from(index.rem_euclid(12)).ok()? + 1;
    let date = (1..=instant.day())
        .rev()
        .find_map(|day| chrono::NaiveDate::from_ymd_opt(year, month, day))?;
    Some(date.and_time(instant.time()).and_utc())
}

/// date_add(iso, amount, unit) - Move a date or datetime by a whole amount.
/// Args:
///   - iso: String (or the piped text) - an ISO date or datetime
///   - amount: Int - may be negative
///   - unit: String - "weeks", "days", "months", "years", "hours", "minutes" or "seconds"; any case, and the singular, is accepted
/// Returns: String - a date when the input is a date and the unit is weeks, days, months or years; otherwise a UTC datetime ending in Z
///
/// Months and years are calendar units: 2024-01-31 plus one month is
/// 2024-02-29, the last day of the month it lands in. The time of day is kept.
///
/// Example:
///   date_add("2024-02-28", 1, "days")                  # "2024-02-29"
///   date_add("2024-02-28T23:00:00Z", 2, "hours")       # "2024-02-29T01:00:00Z"
///   date_add("2024-01-31", 1, "months")                # "2024-02-29"
fn bi_date_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "date_add";
    const UNITS: &str = "a unit String: weeks, days, months, years, hours, minutes or seconds";
    let (text, rest) = text_subject(B, args, input)?;
    let [amount, unit] = rest.as_slice() else {
        return Err(arity_error(B, "an amount Int and a unit", rest.len()));
    };
    let Value::Int(amount) = amount else {
        return Err(crate::safety::bad_arg(
            B,
            "an Int amount",
            amount.type_name(),
        ));
    };
    let unit = string_arg(B, UNITS, unit)?;
    let unit = canonical_unit(unit).ok_or_else(|| crate::safety::bad_arg(B, UNITS, unit))?;
    // Months and years are calendar steps; the other units are fixed lengths.
    let (months, per): (Option<i64>, i64) = match unit {
        "months" => (Some(1), 0),
        "years" => (Some(12), 0),
        "weeks" => (None, 604_800),
        "days" | "hours" | "minutes" | "seconds" => (None, unit_seconds(B, unit)?),
        other => return Err(crate::safety::bad_arg(B, UNITS, other)),
    };
    let (instant, date_only) = parse_iso(B, &text)?;
    let moved = match months {
        Some(per_unit) => amount
            .checked_mul(per_unit)
            .and_then(|total| add_calendar_months(instant, total)),
        None => amount
            .checked_mul(per)
            .and_then(chrono::TimeDelta::try_seconds)
            .and_then(|delta| instant.checked_add_signed(delta)),
    };
    // The answer stays in the years 0001 to 9999, the four-digit years of ISO 8601.
    let moved = moved.filter(|m| {
        use chrono::Datelike as _;
        year_in_range(m.year())
    });
    let Some(moved) = moved else {
        return Err(crate::safety::value_not_representable(
            B,
            format!("{B}: {amount} {unit} moves {text:?} out of range"),
            "use a smaller amount: dates run from 0001-01-01 to 9999-12-31",
        ));
    };
    let whole_days = matches!(unit, "weeks" | "days" | "months" | "years");
    Ok(Value::Str(iso_text(moved, date_only && whole_days)))
}

/// The path of a key under `path`, as a refusal names it: `app.servers[1].note`.
fn path_key(path: &str, key: &str) -> String {
    if path.is_empty() {
        key.to_string()
    } else {
        format!("{path}.{key}")
    }
}

/// A Record as a TOML table. A null, or a value TOML has no form for, is
/// refused with the path to it.
fn toml_table(
    builtin: &str,
    map: &BTreeMap<String, Value>,
    path: &str,
) -> Result<toml::map::Map<String, toml::Value>> {
    let mut table = toml::map::Map::new();
    for (key, item) in map {
        table.insert(
            key.clone(),
            toml_value(builtin, item, &path_key(path, key))?,
        );
    }
    Ok(table)
}

fn toml_value(builtin: &str, value: &Value, path: &str) -> Result<toml::Value> {
    Ok(match value {
        Value::Bool(b) => toml::Value::Boolean(*b),
        Value::Int(i) => toml::Value::Integer(*i),
        Value::Float(f) => toml::Value::Float(*f),
        Value::Str(s) | Value::Uri(s) => toml::Value::String(s.clone()),
        Value::Array(items) => toml::Value::Array(
            items
                .iter()
                .enumerate()
                .map(|(i, item)| toml_value(builtin, item, &format!("{path}[{i}]")))
                .collect::<Result<Vec<_>>>()?,
        ),
        Value::Record(map) => toml::Value::Table(toml_table(builtin, map, path)?),
        Value::Table(table) => toml::Value::Array(
            table
                .rows
                .iter()
                .enumerate()
                .map(|(i, row)| -> Result<toml::Value> {
                    Ok(toml::Value::Table(toml_table(
                        builtin,
                        row,
                        &format!("{path}[{i}]"),
                    )?))
                })
                .collect::<Result<Vec<_>>>()?,
        ),
        Value::Null => {
            return Err(crate::safety::bad_arg_in(
                builtin,
                format!("{builtin}: null at {path} has no TOML value"),
                "TOML has no null: leave the key out, or give it a value",
            ))
        }
        other => {
            return Err(crate::safety::bad_arg_in(
                builtin,
                format!(
                    "{builtin}: a {} at {path} has no TOML value",
                    other.type_name()
                ),
                "TOML holds booleans, numbers, strings, arrays, tables and dates",
            ))
        }
    })
}

/// to_toml(record) - Write a Record as a TOML document.
/// Args:
///   - record: Record (or the piped record)
/// Returns: String
///
/// The top level must be a Record. A null, or a value TOML cannot hold, is
/// E_BAD_ARG and the refusal names its path.
///
/// Example:
///   from_toml(to_toml({a: 1, b: "x"})).b    # "x"
///   (try { to_toml([1]) } catch e { e.error.code })    # "E_BAD_ARG"
fn bi_to_toml(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "to_toml";
    let value = match (input, args.as_slice()) {
        (Some(value), []) => value,
        (None, [value]) => value.clone(),
        _ => return Err(arity_error(B, "one Record to convert", args.len())),
    };
    let Value::Record(map) = &value else {
        return Err(crate::safety::bad_arg_in(
            B,
            format!("{B}: the top level is {}, not a Record", value.type_name()),
            "a TOML document is a Record of named values; wrap an array or a scalar in a record",
        ));
    };
    let table = toml_table(B, map, "")?;
    toml::to_string(&toml::Value::Table(table))
        .map(Value::Str)
        .map_err(|e| {
            crate::safety::bad_arg_in(
                B,
                format!("{B}: {e}"),
                "TOML cannot hold this record; check its keys and values",
            )
        })
}

/// from_toml(text) - Read a TOML document as a Record.
/// Args:
///   - text: String (or the piped text)
/// Returns: Record
///
/// Datetimes come back as their String form. Text that is not TOML is
/// E_BAD_VALUE and the refusal says why.
///
/// Example:
///   from_toml("a = 1").a    # 1
fn bi_from_toml(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "from_toml";
    let (text, rest) = text_subject(B, args, input)?;
    if !rest.is_empty() {
        return Err(arity_error(B, "the TOML text alone", rest.len()));
    }
    let parsed: toml::Value = toml::from_str(&text).map_err(|e| {
        // An integer past 64 bits is valid TOML that this reader cannot hold, so
        // the refusal says so instead of calling the text not TOML.
        let message = match oversized_toml_integer(&text) {
            Some((line, literal)) if e.message().contains("too large") => format!(
                "{B}: the integer {literal} at line {line} is out of the 64-bit Int range (the text is valid TOML)"
            ),
            _ => format!("{B}: the text is not TOML: {}", toml_reason(&text, &e)),
        };
        crate::safety::value_not_representable(B, message, &toml_failure_hint(&text, &e))
    })?;
    if let Some(refusal) = toml_nonfinite_refusal(B, &parsed) {
        return Err(refusal);
    }
    Ok(crate::plugins::toml_to_value(parsed))
}

/// The first `inf` or `nan` in a parsed TOML document, as a refusal naming its
/// key path. IronShell numbers are finite (`float("inf")` is refused), so
/// TOML's `inf` and `nan` are not read as Floats.
pub(crate) fn toml_nonfinite_refusal(builtin: &str, value: &toml::Value) -> Option<anyhow::Error> {
    fn walk(value: &toml::Value, path: &str) -> Option<(String, f64)> {
        match value {
            toml::Value::Float(f) if !f.is_finite() => Some((path.to_string(), *f)),
            toml::Value::Array(items) => items
                .iter()
                .enumerate()
                .find_map(|(i, v)| walk(v, &format!("{path}[{i}]"))),
            toml::Value::Table(table) => table.iter().find_map(|(k, v)| {
                let child = if path.is_empty() {
                    k.to_string()
                } else {
                    format!("{path}.{k}")
                };
                walk(v, &child)
            }),
            _ => None,
        }
    }
    let (path, number) = walk(value, "")?;
    let word = if number.is_nan() {
        "nan"
    } else if number < 0.0 {
        "-inf"
    } else {
        "inf"
    };
    let at = if path.is_empty() {
        "the document".to_string()
    } else {
        path.clone()
    };
    Some(crate::safety::value_not_representable(
        builtin,
        format!("{builtin}: {word} at {at} is not a finite number; IronShell numbers are finite"),
        &format!("quote it as a string to keep the text, such as {path} = \"{word}\""),
    ))
}

/// merge(a, b) - Shallow-merge two Records; b's fields win.
/// Args:
///   - a: Record (or the piped record)
///   - b: Record
/// Returns: Record
///
/// Only the top level merges: a field both Records have takes b's value whole,
/// and a nested Record is replaced, not merged. A non-Record argument is
/// E_BAD_ARG.
///
/// Example:
///   merge({a: 1, b: 2}, {b: 3}).b    # 3
///   {a: 1} | merge({a: 0, c: 4}).a   # 0
fn bi_merge(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "merge";
    let (first, second) = match (input, args.as_slice()) {
        (Some(first), [second]) => (first, second.clone()),
        (None, [first, second]) => (first.clone(), second.clone()),
        _ => {
            return Err(arity_error(
                B,
                "two Records: merge(a, b), or a | merge(b)",
                args.len(),
            ))
        }
    };
    let mut merged = match first {
        Value::Record(map) => map,
        other => {
            return Err(crate::safety::bad_arg_in(
                B,
                format!(
                    "{B}: the first Record is {}, not a Record",
                    other.type_name()
                ),
                "merge takes two Records; wrap a scalar or an array in a record first",
            ))
        }
    };
    let overrides = match second {
        Value::Record(map) => map,
        other => {
            return Err(crate::safety::bad_arg_in(
                B,
                format!(
                    "{B}: the second Record is {}, not a Record",
                    other.type_name()
                ),
                "merge takes two Records; wrap a scalar or an array in a record first",
            ))
        }
    };
    merged.extend(overrides);
    Ok(Value::Record(merged))
}

/// The integer and fraction digits of a non-negative finite Float rounded to
/// `cut` decimals, half away from zero, on its exact binary value: 2.675 is
/// stored as 2.67499999..., so it rounds to 2.67, and an exact tie (0.125, 2.5)
/// goes up. Every fraction digit of an f64 is written out (at most 1074), so the
/// digit after the cut is exact. `format_number` and `round(x, digits)` share it.
fn round_exact_decimal(magnitude: f64, cut: usize) -> (String, String) {
    let exact = format!("{magnitude:.1100}");
    let (whole, fraction) = exact.split_once('.').unwrap_or((exact.as_str(), ""));
    let fraction = fraction.as_bytes();
    let mut digits: Vec<u8> = whole
        .bytes()
        .chain((0..cut).map(|k| fraction.get(k).copied().unwrap_or(b'0')))
        .map(|b| b - b'0')
        .collect();
    if fraction.get(cut).copied().unwrap_or(b'0') >= b'5' {
        // Add one to the last digit, carrying leftwards.
        let mut k = digits.len();
        loop {
            if k == 0 {
                digits.insert(0, 1);
                break;
            }
            k -= 1;
            if digits[k] == 9 {
                digits[k] = 0;
            } else {
                digits[k] += 1;
                break;
            }
        }
    }
    let split = digits.len() - cut;
    let text: String = digits.iter().map(|d| char::from(d + b'0')).collect();
    let int_digits = match text[..split].trim_start_matches('0') {
        "" => "0".to_string(),
        s => s.to_string(),
    };
    (int_digits, text[split..].to_string())
}

/// The most decimals `format_number` writes; past this the scaled value would
/// not fit the integer arithmetic it uses.
const FORMAT_NUMBER_MAX_DECIMALS: i64 = 15;

/// ps_add(a, b) - PowerShell's `+`: the right operand is converted to the left
/// operand's type. Added for the PowerShell transpiler, which cannot know the
/// operand types when it translates `$x + $y`.
/// Args:
///   - a, b: any two values (or `a` piped)
/// Returns: the sum or the concatenation
///
/// A String on the left concatenates the text of the right (`'a' + 1` is
/// "a1"). A number on the left converts a String on the right to a number
/// (`1 + '2'` is 3, `1 + '2.5'` is 3.5) and refuses text that is not numeric,
/// as PowerShell does. Anything else adds as `+` does.
///
/// Example:
///   ps_add("a", 1)     # "a1"
///   ps_add(1, "2")     # 3
///   ps_add(1, 2.5)     # 3.5
fn bi_ps_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use crate::ast::BinOp;
    const B: &str = "ps_add";
    let (a, b) = match (input, args.as_slice()) {
        (Some(a), [b]) => (a, b.clone()),
        (None, [a, b]) => (a.clone(), b.clone()),
        (_, rest) => return Err(arity_error(B, "two values", rest.len())),
    };
    let b = match (&a, b) {
        (Value::Str(_), b) => Value::Str(b.to_display_string()),
        (Value::Int(_) | Value::Float(_), Value::Str(text)) => {
            let t = text.trim();
            if let Ok(n) = t.parse::<i64>() {
                Value::Int(n)
            } else {
                match t.parse::<f64>() {
                    Ok(f) if f.is_finite() => Value::Float(f),
                    _ => {
                        return Err(crate::safety::bad_arg_in(
                            B,
                            format!("{B}: cannot convert {text:?} to a number"),
                            "PowerShell converts the right operand to the left one's type; the text must be numeric",
                        ))
                    }
                }
            }
        }
        (_, b) => b,
    };
    crate::eval::binop(&BinOp::Add, a, b)
}

/// format_number(x, decimals, separator?) - Format a number with fixed decimals./// Args:
///   - x: Int or Float (or the piped number)
///   - decimals: Int, 0 to 15 - digits after the point; 0 writes no point
///   - separator: String (optional) - groups the integer part, such as ","
/// Returns: String
///
/// A Float rounds half away from zero, and a negative value keeps its sign
/// unless it rounds to zero. NaN and the infinities are E_BAD_ARG.
///
/// Example:
///   format_number(1234567.891, 2, ",")    # "1,234,567.89"
///   format_number(1000, 2)                # "1000.00"
///   format_number(-0.5, 0)                # "-1"
fn bi_format_number(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "format_number";
    let (number, rest) = match input {
        Some(number) => (number, args.as_slice()),
        None => match args.split_first() {
            Some((number, rest)) => (number.clone(), rest),
            None => {
                return Err(arity_error(
                    B,
                    "a number, then decimals and an optional separator",
                    0,
                ))
            }
        },
    };
    let (decimals, separator) = match rest {
        [decimals] => (decimals, None),
        [decimals, Value::Str(separator)] => (decimals, Some(separator.as_str())),
        [_, other] => {
            return Err(crate::safety::bad_arg_in(
                B,
                format!("{B}: the separator is {}, not a String", other.type_name()),
                "pass the separator as a String, such as \",\"",
            ))
        }
        _ => {
            return Err(arity_error(
                B,
                "decimals, then an optional separator",
                rest.len(),
            ))
        }
    };
    let decimals = match decimals {
        Value::Int(d) if (0..=FORMAT_NUMBER_MAX_DECIMALS).contains(d) => *d as u32,
        Value::Int(d) => {
            return Err(crate::safety::bad_arg_in(
                B,
                format!("{B}: decimals must be from 0 to {FORMAT_NUMBER_MAX_DECIMALS}, got {d}"),
                "pass the number of digits after the point, such as 2",
            ))
        }
        other => {
            return Err(crate::safety::bad_arg_in(
                B,
                format!(
                    "{B}: decimals must be an Int from 0 to {FORMAT_NUMBER_MAX_DECIMALS}, got {}",
                    other.type_name()
                ),
                "pass the number of digits after the point, such as 2",
            ))
        }
    };

    // The sign, the integer digits and the fraction digits, each as text.
    let (negative, int_digits, frac_digits) = match number {
        Value::Int(i) => (
            i < 0,
            i.unsigned_abs().to_string(),
            "0".repeat(decimals as usize),
        ),
        Value::Float(f) => {
            if !f.is_finite() {
                return Err(crate::safety::bad_arg_in(
                    B,
                    format!("{B}: the number is {f}, which has no decimal form"),
                    "pass a finite number; NaN and the infinities cannot be written with decimals",
                ));
            }
            // Round the exact binary value, not a scaled copy of it: 2.675 is
            // stored as 2.67499999..., so it writes "2.67". Every fraction digit
            // of an f64 is written out (at most 1074), so the digit after the cut
            // is exact. It decides: 5 or more goes up, which also rounds an exact
            // tie (0.125, 2.5) away from zero.
            let magnitude = f.abs();
            // The cap is on the scaled value: the number times 10^decimals must
            // stay below 1e38. Fewer decimals only help when there are some.
            if magnitude * 10f64.powi(decimals as i32) >= 1.0e38 {
                let hint = if decimals > 0 {
                    "pass fewer decimals or a smaller number"
                } else {
                    "pass a number below 1e38"
                };
                return Err(crate::safety::bad_arg_in(
                    B,
                    format!(
                        "{B}: the number is too large to write: it times 10^{decimals} must stay below 1e38"
                    ),
                    hint,
                ));
            }
            let (int_digits, frac_digits) = round_exact_decimal(magnitude, decimals as usize);
            (f < 0.0, int_digits, frac_digits)
        }
        other => {
            return Err(crate::safety::bad_arg_in(
                B,
                format!(
                    "{B}: the number is {}, not an Int or Float",
                    other.type_name()
                ),
                "format_number takes an Int or a Float",
            ))
        }
    };

    let is_zero = int_digits == "0" && frac_digits.bytes().all(|b| b == b'0');
    let grouped = match separator {
        Some(sep) if !sep.is_empty() => group_thousands(&int_digits, sep),
        _ => int_digits,
    };
    let mut out = String::new();
    if negative && !is_zero {
        out.push('-');
    }
    out.push_str(&grouped);
    if decimals > 0 {
        out.push('.');
        out.push_str(&frac_digits);
    }
    Ok(Value::Str(out))
}

/// Insert `sep` between each group of three digits, counted from the right.
fn group_thousands(digits: &str, sep: &str) -> String {
    let n = digits.len();
    let mut out = String::with_capacity(n + n / 3 * sep.len());
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (n - i).is_multiple_of(3) {
            out.push_str(sep);
        }
        out.push(c);
    }
    out
}

/// exit(code?) - Exit the shell process with a status.
/// Args:
///   - code: Int (optional) - 0..=255, default 0
/// Returns: never; the process ends
///
/// A code outside 0..=255 was truncated by the OS (256 exited 0, -1 exited
/// 255), and pipeline input and surplus arguments were dropped. All three are
/// refused before anything ends.
///
/// Example:
///   exit(0)     # Exit with success
fn bi_exit(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("exit", &input)?;
    if args.len() > 1 {
        return Err(crate::safety::bad_arg(
            "exit",
            "at most one argument, the exit code",
            &format!("{} arguments", args.len()),
        ));
    }
    let code = match args.first() {
        None => 0,
        Some(Value::Int(n)) if (0..=255).contains(n) => *n as i32,
        Some(Value::Int(n)) => {
            return Err(crate::safety::bad_arg(
                "exit",
                "code: Int 0..=255",
                &n.to_string(),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "exit",
                "code: Int 0..=255",
                other.type_name(),
            ))
        }
    };
    std::process::exit(code);
}

/// env(key) - Get environment variable
/// Args:
///   - key: String - Environment variable name
/// Returns: String or Null - Variable value or null if not set
///
/// Example:
///   env("HOME")     # Returns home directory path
fn bi_env(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err(
            "env requires variable name argument",
        ));
    }

    let key = expect_string("env", &args[0])?;
    match env_read("env", key, std::env::var(key))? {
        Some(val) => Ok(gate_env_secret(key, val)),
        // `env(name, default)` returns `default` when the variable is unset.
        //
        // The second argument used to be accepted and discarded, so an unset
        // variable was always `null` — the same defect shape as `round(x, n)`
        // ignoring `n`. It matters most in bash compatibility mode, where
        // `echo $NOPE` must print an empty line as bash does, not the word
        // "null".
        None => Ok(args.get(1).cloned().unwrap_or(Value::Null)),
    }
}

/// Gate an env-var read against the secret policy (§7.6): in agent mode, reading
/// a secret-named var (e.g. `*_KEY`, `*TOKEN*`) returns an opaque
/// `[REDACTED:NAME]` handle instead of the value, so the credential never enters
/// the program's value space — unless `IRONSHELL_SECRETS=allow`. Human mode and
/// non-secret names return the value unchanged.
fn gate_env_secret(key: &str, val: String) -> Value {
    if crate::safety::env_secret_gated(key) {
        Value::Str(format!("[REDACTED:{}]", key))
    } else {
        Value::Str(val)
    }
}

/// set_env(key, value) - Set environment variable
/// Args:
///   - key: String - Environment variable name
///   - value: String - Value to set
/// Returns: Null
///
/// Example:
///   set_env("MY_VAR", "value")
fn bi_set_env(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "set_env";
    k8s_no_input(B, &input)?;
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "set_env requires key and value arguments",
        ));
    }
    let key = env_name(B, &args[0])?;
    refuse_gate_env(B, &key)?;
    let value = env_value(B, &args[1])?;
    std::env::set_var(key, value);
    Ok(Value::Null)
}

/// An environment variable name. `set_var` panics on an empty name, one with
/// '=' or NUL, and a value with NUL, so each is refused here as E_BAD_ARG.
fn env_name(builtin: &str, value: &Value) -> Result<String> {
    let name = expect_string(builtin, value)?;
    if name.is_empty() || name.len() > 1024 || name.contains(['=', '\0']) {
        return Err(crate::safety::bad_arg(
            builtin,
            "a name of 1 to 1024 bytes with no '=' and no NUL",
            &format!("{name:?}"),
        ));
    }
    Ok(name.to_string())
}

/// An environment variable value: a string with no NUL, at most 32767 bytes
/// (the Windows limit per variable).
fn env_value(builtin: &str, value: &Value) -> Result<String> {
    let text = expect_string(builtin, value)?;
    if text.contains('\0') || text.len() > 32_767 {
        return Err(crate::safety::bad_arg(
            builtin,
            "a value of at most 32767 bytes with no NUL",
            "a value that is too long or has NUL",
        ));
    }
    Ok(text.to_string())
}

/// Refuse, in agent mode, any change to a variable that steers a child program
/// or the destination of data (see `safety::env_name_steers_children`).
///
/// The approval gate and its mode switch are read from the process
/// environment on every call: `IRONSHELL_MODE`/`IRONSHELL_AGENT` decide whether
/// `approve()` is refused, `IRONSHELL_APPROVE`/`IRONSHELL_APPROVE_ALL` decide whether a
/// gated call (including `apply`) is approved, and `IRONSHELL_POLICY`,
/// `IRONSHELL_WORKSPACE` and the `IRONSHELL_MAX_*` budgets decide the rest. An agent
/// that could set or unset those through `set_env`/`env_set`/`env_unset` (all
/// classified WriteLocal, so allowed in agent mode) could approve its own plan
/// or switch the gate off. Fail closed: the agent may not touch them. Human
/// mode is unchanged.
fn refuse_gate_env(builtin: &str, name: &str) -> Result<()> {
    if crate::safety::env_change_refused(name) {
        return Err(crate::safety::policy_deny(
            builtin,
            format!(
                "{builtin}: an agent may not change {name}: it steers the approval gate, \
                 a child program, its loader or configuration, or where data is sent"
            ),
            "variables that steer child programs and network destinations (PATH, GIT_*, \
             IRONGATE_*, *_PROXY, provider keys and endpoints, ...) are set by whoever \
             launches the agent, not by the agent",
        ));
    }
    Ok(())
}

/// sleep(seconds) - Sleep for specified duration
/// Args:
///   - seconds: Number - Duration to sleep
/// Returns: Null
///
/// Example:
///   sleep(2)     # Sleep for 2 seconds
fn bi_sleep(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err("sleep requires duration argument"));
    }

    let seconds = match &args[0] {
        Value::Int(n) => *n as f64,
        Value::Float(f) => *f,
        _ => return Err(crate::safety::arg_err("sleep requires numeric duration")),
    };

    let duration = Duration::try_from_secs_f64(seconds).map_err(|_| {
        crate::safety::arg_err("sleep: duration must be finite, non-negative and representable")
    })?;
    // A sleep may not outlast the evaluation deadline. Sleeping only what is
    // left and then failing tells the caller the time was cut short, rather
    // than returning Null for a wait that did not happen in full.
    if let Some(left) = crate::safety::remaining_deadline() {
        if left < duration {
            let message = if left.is_zero() {
                format!("sleep of {seconds} s refused: the evaluation deadline has already expired")
            } else {
                std::thread::sleep(left);
                format!("sleep of {seconds} s cut short by the evaluation deadline after {left:?}")
            };
            return Err(crate::safety::budget_exceeded(
                "sleep",
                message,
                "ask for a shorter sleep, or allow a longer evaluation time limit",
            ));
        }
    }
    std::thread::sleep(duration);
    Ok(Value::Null)
}

/// time() - Get current Unix timestamp
/// Returns: Int - Current Unix timestamp in seconds
///
/// Example:
///   time()     # Returns 1699401234
fn bi_time(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // `now` and `time` are one clock under two names, declared identically
    // in the ontology; one implementation keeps them from drifting apart.
    bi_now(args, input)
}

/// json_parse(json_string?) - Parse JSON string into value
/// Args:
///   - json_string: String (optional if piped)
/// Returns: Any - Parsed JSON value
///
/// Example:
///   json_parse("{\"a\":1}")     # Returns {a: 1}
fn bi_json_parse(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let json_str = if args.is_empty() {
        let input_val =
            input.ok_or_else(|| crate::safety::arg_err("json_parse requires JSON string"))?;
        expect_string("json_parse", &input_val)?.to_string()
    } else {
        expect_string("json_parse", &args[0])?.to_string()
    };
    let json_str = without_bom(json_str);

    let json_val: serde_json::Value = serde_json::from_str(&json_str).map_err(|e| {
        let (detail, hint) = json_failure(&e, &json_str);
        crate::safety::value_not_representable(
            "json_parse",
            format!("json_parse: the text is not JSON: {detail}"),
            &hint,
        )
    })?;

    if let Some(refusal) = wide_integer_refusal("json_parse", &json_str) {
        return Err(refusal);
    }
    Ok(json_to_value(with_integer_negative_zeros(
        json_val, &json_str,
    )))
}

/// json_stringify(value?) - Convert value to JSON string
/// Args:
///   - value: Any (optional if piped)
/// Returns: String - JSON representation
///
/// Example:
///   {a: 1} | json_stringify()     # Returns "{\"a\":1}"
fn bi_json_stringify(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Piped, the value is the input and an optional indent the first argument;
    // called directly, the value is the first argument and the indent the second.
    let (val, rest) = match input {
        Some(value) => (value, args.as_slice()),
        None => match args.split_first() {
            Some((value, rest)) => (value.clone(), rest),
            None => return Err(crate::safety::arg_err("json_stringify requires value")),
        },
    };

    let json_val = value_to_json_strict("json_stringify", &val, "value")?;
    let json_str = match rest.first() {
        Some(Value::Int(indent)) => json_indented("json_stringify", &json_val, *indent)?,
        _ => serde_json::to_string(&json_val).context("Failed to stringify to JSON")?,
    };

    Ok(Value::Str(json_str))
}

/// `json` as text with each nesting level indented by `indent` spaces. An indent
/// of 0 is compact JSON. An indent outside 0 to 8 is a bad argument.
fn json_indented(builtin: &str, json: &serde_json::Value, indent: i64) -> Result<String> {
    if !(0..=8).contains(&indent) {
        return Err(crate::safety::bad_arg_in(
            builtin,
            format!("{builtin}: indent must be 0 to 8 spaces, got {indent}"),
            "pass an indent from 0 to 8, or leave it out for compact JSON",
        ));
    }
    if indent == 0 {
        return Ok(serde_json::to_string(json)?);
    }
    let unit = vec![b' '; indent as usize];
    Ok(String::from_utf8(serialize_with_unit(json, &unit)?)?)
}

/// `json` as bytes, each nesting level indented by `unit`.
fn serialize_with_unit(json: &serde_json::Value, unit: &[u8]) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    let formatter = serde_json::ser::PrettyFormatter::with_indent(unit);
    let mut serializer = serde_json::Serializer::with_formatter(&mut buf, formatter);
    serde::Serialize::serialize(json, &mut serializer)?;
    Ok(buf)
}

/// json_set(path, key_path, value): set one key of a JSON file and write the
/// file back in place.
///
/// The file keeps its key order and its indentation: a tab, two or four spaces,
/// or none for compact JSON, read from the text. `key_path` is dot-separated:
/// "version", "a.b.c", "items.0.name". A missing object key is created; an
/// array index must already exist. A path that would create a key inside a
/// value that is not an object is refused. The write is guarded and atomic, as
/// file_write's is.
fn bi_json_set(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            "json_set",
            "no pipeline input: json_set(path, key_path, value)",
            "a piped value",
        ));
    }
    let (Some(Value::Str(path)), Some(Value::Str(key_path)), Some(value)) =
        (args.first(), args.get(1), args.get(2))
    else {
        return Err(crate::safety::arg_err(
            "json_set requires a file path, a key path and a value",
        ));
    };
    let segments: Vec<&str> = key_path.split('.').collect();
    if segments.iter().any(|segment| segment.is_empty()) {
        return Err(crate::safety::bad_arg_in(
            "json_set",
            format!("json_set: key path '{key_path}' has an empty key"),
            "name keys separated by dots, such as version or a.b.c or items.0.name",
        ));
    }

    let path = crate::safety::resolve_path_str(path);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "json_set",
        effect: crate::safety::Effect::WriteLocal,
        what: "write",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({ "key": key_path }),
        reversible: true,
        fs_paths: true,
    })?;

    let text = std::fs::read_to_string(&path).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            crate::safety::not_found("json_set", "file", &path)
        } else {
            crate::safety::fs_error("json_set", &path, &e)
        }
    })?;
    // serde_json's Map keeps insertion order here, so a set key stays where it was.
    let mut json: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
        crate::safety::bad_value(
            format!("json_set: {path} is not valid JSON: {e}"),
            "json_set edits well-formed JSON only; fix the file's syntax first",
        )
    })?;
    if let Err(reason) = set_json_path(&mut json, &segments, value_to_json(value.clone())) {
        return Err(crate::safety::bad_arg_in(
            "json_set",
            format!("json_set: cannot set '{key_path}' in {path}: {reason}"),
            "only object keys are created, and an array index must already exist; the path must lead through objects and arrays",
        ));
    }

    // Written as the file was indented, with its line endings and its final newline.
    let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
    let mut bytes = match json_indent_unit(&text) {
        Some(unit) => serialize_with_unit(&json, &unit)?,
        None => serde_json::to_vec(&json)?,
    };
    if newline != "\n" {
        bytes = String::from_utf8(bytes)?
            .replace('\n', newline)
            .into_bytes();
    }
    if text.ends_with('\n') {
        bytes.extend_from_slice(newline.as_bytes());
    }

    crate::tx::snapshot(&path); // record pre-write state if a transaction is active
    write_file_atomically("json_set", &path, &bytes)?;

    let mut result = BTreeMap::new();
    result.insert("path".to_string(), Value::Str(path));
    result.insert("key".to_string(), Value::Str(key_path.clone()));
    result.insert("success".to_string(), Value::Bool(true));
    Ok(Value::Record(result))
}

/// Set the value at `segments` inside `node`. An object gets a missing key; an
/// array's index must already exist; any other value refuses, and the reason
/// names the segment.
fn set_json_path(
    node: &mut serde_json::Value,
    segments: &[&str],
    value: serde_json::Value,
) -> std::result::Result<(), String> {
    let Some((segment, rest)) = segments.split_first() else {
        *node = value;
        return Ok(());
    };
    match node {
        serde_json::Value::Object(map) => {
            // A missing key that the next segment indexes would be created as an
            // object, and the index would then become a key of it: `tags.0` made
            // {"tags": {"0": ...}}. An index needs an array that already exists.
            if !map.contains_key(*segment)
                && rest
                    .first()
                    .is_some_and(|next| next.parse::<usize>().is_ok())
            {
                return Err(format!(
                    "'{segment}' is missing; an array index needs an existing array"
                ));
            }
            let child = map
                .entry(segment.to_string())
                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
            set_json_path(child, rest, value)
        }
        serde_json::Value::Array(items) => {
            let index = segment
                .parse::<usize>()
                .ok()
                .filter(|index| *index < items.len())
                .ok_or_else(|| format!("'{segment}' is not an index of this array"))?;
            set_json_path(&mut items[index], rest, value)
        }
        other => {
            let kind = match other {
                serde_json::Value::Null => "null",
                serde_json::Value::Bool(_) => "boolean",
                serde_json::Value::Number(_) => "number",
                _ => "string",
            };
            Err(format!(
                "'{segment}' would be created inside a {kind} value, which is not an object"
            ))
        }
    }
}

/// The indentation a JSON text uses: a tab, or the spaces of its least-indented
/// line. None when no line is indented, which is compact JSON.
fn json_indent_unit(text: &str) -> Option<Vec<u8>> {
    let mut spaces: Option<usize> = None;
    for line in text.lines() {
        if line.starts_with('\t') {
            return Some(b"\t".to_vec());
        }
        let indent = line.len() - line.trim_start_matches(' ').len();
        if indent > 0 {
            spaces = Some(spaces.map_or(indent, |least| least.min(indent)));
        }
    }
    spaces.map(|n| vec![b' '; n])
}

// ==================== Syntax Knowledge Base Functions ====================

use crate::syntax_kb::{AgenticBinary, SyntaxCategory, SyntaxEntry, SyntaxKB};
use std::sync::{Mutex, OnceLock};

// Global syntax knowledge base
static SYNTAX_KB: OnceLock<Mutex<SyntaxKB>> = OnceLock::new();

// Why ~/.ironshell/syntax_kb.json did not load, when the file exists but cannot
// be read or parsed. None when storage is live. Set by the first
// get_syntax_kb(); the knowledge base then runs in memory and saves nothing.
static SYNTAX_KB_LOAD_ERROR: OnceLock<Option<String>> = OnceLock::new();

/// The reason the syntax knowledge base is not persisted, or None when its
/// storage loaded. Forces the load first, so the answer is never stale.
fn syntax_kb_load_error() -> Option<&'static str> {
    let _ = get_syntax_kb();
    SYNTAX_KB_LOAD_ERROR.get().and_then(|e| e.as_deref())
}

fn get_syntax_kb() -> &'static Mutex<SyntaxKB> {
    SYNTAX_KB.get_or_init(|| {
        // Try to load from ~/.ironshell/syntax_kb.json
        let home = std::env::var("HOME")
            .or_else(|_| std::env::var("USERPROFILE"))
            .unwrap_or_else(|_| ".".to_string());
        let storage_path = std::path::PathBuf::from(home)
            .join(".ironshell")
            .join("syntax_kb.json");

        // Create directory if it doesn't exist
        if let Some(parent) = storage_path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }

        let (kb, load_error) = match SyntaxKB::with_storage(storage_path.clone()) {
            Ok(kb) => (kb, None),
            Err(e) => (
                SyntaxKB::new(),
                Some(format!(
                    "the syntax knowledge base file {} did not load ({e})",
                    storage_path.display()
                )),
            ),
        };
        let _ = SYNTAX_KB_LOAD_ERROR.set(load_error);
        Mutex::new(kb)
    })
}

/// syntax_get(id) - Get syntax entry by ID
/// Args:
///   - id: String - Syntax ID
/// Returns: Record - Syntax entry details
///
/// Example:
///   syntax_get("ab")  # Returns AgenticBinary protocol details
fn bi_syntax_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let id_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("syntax_get requires syntax ID"))?;
    let id = expect_string("syntax_get", &id_val)?;

    let kb = get_syntax_kb().lock().unwrap();
    let entry = kb
        .get(id)
        .ok_or_else(|| crate::safety::not_found("syntax_get", "syntax", id))?;

    // Convert to Value::Record
    let mut fields = std::collections::BTreeMap::new();
    fields.insert("id".to_string(), Value::Str(entry.id.clone()));
    fields.insert("name".to_string(), Value::Str(entry.name.clone()));
    fields.insert(
        "category".to_string(),
        Value::Str(format!("{:?}", entry.category)),
    );
    fields.insert(
        "specification".to_string(),
        Value::Str(entry.specification.clone()),
    );
    fields.insert(
        "examples".to_string(),
        Value::Array(
            entry
                .examples
                .iter()
                .map(|s| Value::Str(s.clone()))
                .collect(),
        ),
    );

    if let Some(enc) = &entry.binary_encoding {
        let mut enc_fields = std::collections::BTreeMap::new();
        enc_fields.insert("name".to_string(), Value::Str(enc.name.clone()));
        enc_fields.insert("bit_layout".to_string(), Value::Str(enc.bit_layout.clone()));
        fields.insert("binary_encoding".to_string(), Value::Record(enc_fields));
    }

    Ok(Value::Record(fields))
}

/// syntax_list(category?) - List all syntax entries or by category
/// Args:
///   - category: String (optional) - Category to filter by
/// Returns: Array - List of syntax IDs
///
/// Example:
///   syntax_list()           # Returns all syntax IDs
///   syntax_list("protocol") # Returns protocol syntax IDs
fn bi_syntax_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let kb = get_syntax_kb().lock().unwrap();

    let ids = if let Some(cat_val) = input.or_else(|| args.first().cloned()) {
        let category_str = expect_string("syntax_list", &cat_val)?;
        let category = match category_str.to_lowercase().as_str() {
            "protocol" => SyntaxCategory::Protocol,
            "language" => SyntaxCategory::Language,
            "encoding" => SyntaxCategory::Encoding,
            "command" => SyntaxCategory::Command,
            "query" => SyntaxCategory::Query,
            other => SyntaxCategory::Custom(other.to_string()),
        };

        kb.list_by_category(&category)
            .iter()
            .map(|e| Value::Str(e.id.clone()))
            .collect()
    } else {
        kb.list_all_ids()
            .iter()
            .map(|id| Value::Str(id.clone()))
            .collect()
    };

    Ok(Value::Array(ids))
}

/// syntax_search(query) - Search syntax entries by keyword
/// Args:
///   - query: String - Search query
/// Returns: Array - Matching syntax IDs
///
/// Example:
///   syntax_search("binary")  # Finds entries with "binary" in name/spec
fn bi_syntax_search(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let query_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("syntax_search requires query string"))?;
    let query = expect_string("syntax_search", &query_val)?;

    let kb = get_syntax_kb().lock().unwrap();
    let results: Vec<Value> = kb
        .search(query)
        .iter()
        .map(|e| Value::Str(e.id.clone()))
        .collect();

    Ok(Value::Array(results))
}

/// syntax_add(entry_record) - Add a new syntax entry
/// Args:
///   - entry_record: Record - Syntax entry with id, name, category, specification
/// Returns: Bool - Success status
///
/// Example:
///   syntax_add({id: "mysyntax", name: "My Syntax", category: "custom", specification: "..."})
fn bi_syntax_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "syntax_add";
    // The entry comes either piped or as the argument, never both: the piped
    // form used to win and drop the argument without a word.
    let entry_val = match (input, args.as_slice()) {
        (Some(piped), []) => piped,
        (None, [direct]) => direct.clone(),
        (Some(_), [_, ..]) => {
            return Err(crate::safety::arg_err(
                "syntax_add takes its entry piped or as its argument, not both",
            ))
        }
        (None, []) => return Err(crate::safety::arg_err("syntax_add requires entry record")),
        (None, _) => return Err(crate::safety::arg_err("syntax_add takes one entry record")),
    };

    let record = match entry_val {
        Value::Record(r) => r,
        other => {
            return Err(crate::safety::bad_arg(
                B,
                "entry: Record",
                other.type_name(),
            ))
        }
    };
    // A misspelt field (`exmples`) used to be dropped, and the entry saved
    // without it.
    if let Some(unknown) = record.keys().find(|k| {
        !matches!(
            k.as_str(),
            "id" | "name" | "category" | "specification" | "examples"
        )
    }) {
        return Err(crate::safety::bad_arg(
            B,
            "a Record with only the fields id, name, category, specification, examples",
            &format!("the field {unknown:?}"),
        ));
    }

    // A present field of the wrong type is refused; an absent one falls to its
    // default or to the required-field message below.
    let text_field = |key: &str| -> Result<Option<String>> {
        match record.get(key) {
            None => Ok(None),
            Some(Value::Str(s)) => Ok(Some(s.clone())),
            Some(other) => Err(crate::safety::bad_arg(
                B,
                &format!("{key}: String"),
                other.type_name(),
            )),
        }
    };
    let id = text_field("id")?
        .ok_or_else(|| crate::safety::arg_err("syntax_add requires 'id' field"))?;
    let well_formed_id = !id.is_empty()
        && id.len() <= 128
        && id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'));
    if !well_formed_id {
        return Err(crate::safety::bad_arg(
            B,
            "id: 1 to 128 letters, digits, '_', '-' or '.'",
            &format!("{id:?}"),
        ));
    }
    let name = text_field("name")?
        .ok_or_else(|| crate::safety::arg_err("syntax_add requires 'name' field"))?;
    if name.trim().is_empty() {
        return Err(crate::safety::bad_arg(
            B,
            "name: a non-blank String",
            "a blank name",
        ));
    }
    let category_str = text_field("category")?.unwrap_or_else(|| "custom".to_string());
    let category = match category_str.to_lowercase().as_str() {
        "protocol" => SyntaxCategory::Protocol,
        "language" => SyntaxCategory::Language,
        "encoding" => SyntaxCategory::Encoding,
        "command" => SyntaxCategory::Command,
        "query" => SyntaxCategory::Query,
        "" => {
            return Err(crate::safety::bad_arg(
                B,
                "category: a nonblank String",
                "an empty category",
            ))
        }
        other => SyntaxCategory::Custom(other.to_string()),
    };
    let specification = text_field("specification")?
        .ok_or_else(|| crate::safety::arg_err("syntax_add requires 'specification' field"))?;

    let examples: Vec<String> = match record.get("examples") {
        None => Vec::new(),
        Some(Value::Array(arr)) => arr
            .iter()
            .map(|v| match v {
                Value::Str(s) => Ok(s.clone()),
                other => Err(crate::safety::bad_arg(
                    B,
                    "examples: Array of String",
                    other.type_name(),
                )),
            })
            .collect::<Result<_>>()?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                B,
                "examples: Array of String",
                other.type_name(),
            ))
        }
    };

    let entry = SyntaxEntry {
        id: id.clone(),
        name,
        category,
        specification,
        examples,
        binary_encoding: None,
        metadata: std::collections::HashMap::new(),
    };

    if let Some(why) = syntax_kb_load_error() {
        return Err(crate::safety::bad_state_with_hint(
            B,
            &format!("{why}; the entry was not saved and the file was left untouched"),
            "repair or move the syntax knowledge base file so it loads, then retry; the shell does not overwrite it",
        ));
    }
    let mut kb = get_syntax_kb().lock().map_err(|_| {
        crate::safety::bad_state(
            B,
            "the syntax knowledge base is poisoned by an earlier failure",
            "syntax_list",
        )
    })?;
    // add_entry replaces an entry with the same id and lists the id twice in
    // its category, so an existing id is refused rather than overwritten.
    if kb.get(&id).is_some() {
        return Err(crate::safety::bad_arg(
            B,
            "an id not yet in the syntax knowledge base",
            &format!("the existing id {id:?}"),
        ));
    }
    kb.add_entry(entry).map_err(|e| {
        crate::safety::fs_error(B, "syntax_kb.json", &std::io::Error::other(e.to_string()))
    })?;

    Ok(Value::Bool(true))
}

/// syntax_categories() - List all available syntax categories
/// Returns: Array - List of category names
///
/// Example:
///   syntax_categories()  # Returns ["protocol", "language", ...]
fn bi_syntax_categories(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let kb = get_syntax_kb().lock().unwrap();
    let categories: Vec<Value> = kb
        .list_categories()
        .iter()
        .map(|c| Value::Str(c.clone()))
        .collect();

    Ok(Value::Array(categories))
}

/// ab_encode(msg_type, opcode, payload) - Encode message using AgenticBinary protocol
/// Args:
///   - msg_type: String or Int - Message type (Command/Query/Response/Event or 0-3)
///   - opcode: String or Int - Opcode name or number (0-15)
///   - payload: String - Payload data
/// Returns: Array - Encoded bytes
///
/// Example:
///   ab_encode("Query", "DATA", "hello")  # Encodes AgenticBinary message
///   ab_encode(1, 4, "hello")             # Same using numeric codes
fn bi_ab_encode(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.len() < 3 {
        return Err(crate::safety::arg_err(
            "ab_encode requires 3 arguments: msg_type, opcode, payload",
        ));
    }

    // Parse message type
    let msg_type = match &args[0] {
        Value::Int(i) if (0..=3).contains(i) => *i as u8,
        Value::Str(s) => match s.to_lowercase().as_str() {
            "command" | "cmd" => 0,
            "query" => 1,
            "response" | "resp" => 2,
            "event" => 3,
            _ => return Err(crate::safety::arg_err(format!("Invalid message type: {s}"))),
        },
        _ => return Err(crate::safety::arg_err("msg_type must be String or Int")),
    };

    // Parse opcode
    let opcode = match &args[1] {
        Value::Int(i) if (0..=15).contains(i) => *i as u8,
        Value::Str(s) => match s.to_uppercase().as_str() {
            "PING" => 0x0,
            "ACK" => 0x1,
            "QUERY" => 0x2,
            "EXEC" => 0x3,
            "DATA" => 0x4,
            "ERROR" => 0x5,
            "SYNC" => 0x6,
            "AUTH" => 0x7,
            "DELEGATE" => 0x8,
            "COLLABORATE" => 0x9,
            "LEARN" => 0xA,
            "REASON" => 0xB,
            "PLAN" => 0xC,
            "OBSERVE" => 0xD,
            "REFLECT" => 0xE,
            "EXTEND" => 0xF,
            _ => return Err(crate::safety::arg_err(format!("Invalid opcode: {s}"))),
        },
        _ => return Err(crate::safety::arg_err("opcode must be String or Int")),
    };

    // Get payload
    let payload = expect_string("ab_encode", &args[2])?;

    // Encode using AgenticBinary (version 0)
    let encoded = AgenticBinary::encode(0, msg_type, opcode, payload.as_bytes())?;

    // Convert to Value::Array of Int values
    let result: Vec<Value> = encoded.iter().map(|&b| Value::Int(b as i64)).collect();

    Ok(Value::Array(result))
}

/// ab_decode(bytes) - Decode AgenticBinary message
/// Args:
///   - bytes: Array - Byte array to decode
/// Returns: Record - Decoded message with version, msg_type, opcode, payload
///
/// Example:
///   ab_decode([20, 5, 104, 101, 108, 108, 111])  # Decodes to record
fn bi_ab_decode(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let bytes_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("ab_decode requires byte array"))?;

    let bytes_arr = expect_array("ab_decode", &bytes_val)?;
    let bytes: Vec<u8> = bytes_arr
        .iter()
        .map(|v| match v {
            Value::Int(i) if (0..=255).contains(i) => Ok(*i as u8),
            _ => Err(crate::safety::arg_err(
                "Byte array must contain integers in 0..255",
            )),
        })
        .collect::<Result<Vec<u8>>>()?;

    let (version, msg_type, opcode, payload) = AgenticBinary::decode(&bytes)
        .map_err(|error| crate::safety::arg_err(format!("ab_decode: {error}")))?;

    let mut result = std::collections::BTreeMap::new();
    result.insert("version".to_string(), Value::Int(version as i64));
    result.insert(
        "msg_type".to_string(),
        Value::Str(AgenticBinary::msg_type_name(msg_type).to_string()),
    );
    result.insert("msg_type_code".to_string(), Value::Int(msg_type as i64));
    result.insert(
        "opcode".to_string(),
        Value::Str(AgenticBinary::opcode_name(opcode).to_string()),
    );
    result.insert("opcode_code".to_string(), Value::Int(opcode as i64));
    result.insert(
        "payload".to_string(),
        Value::Str(String::from_utf8_lossy(&payload).to_string()),
    );
    result.insert(
        "payload_bytes".to_string(),
        Value::Array(payload.iter().map(|&b| Value::Int(b as i64)).collect()),
    );

    Ok(Value::Record(result))
}

// --------------- Neural Network Builtins ---------------

/// nn_create(name, layer_sizes, [hidden_activation], [output_activation])
/// Creates a feedforward neural network
/// Args:
///   - name: String - Network name/identifier
///   - layer_sizes: Array[Int] - Sizes of each layer [input, hidden..., output]
///   - hidden_activation: String (optional) - "relu", "sigmoid", "tanh", "swish" (default: "relu")
///   - output_activation: String (optional) - activation for output layer (default: "tanh")
/// Returns: Record - Network representation
///
/// Example:
///   nn_create("policy", [8, 16, 8, 4])  # 8 inputs, 2 hidden layers, 4 outputs
fn bi_nn_create(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err(
            "nn_create requires at least name and layer_sizes",
        ));
    }

    let name = expect_string("nn_create", &args[0])?;
    let layer_sizes_val = args
        .get(1)
        .ok_or_else(|| crate::safety::arg_err("nn_create requires layer_sizes array"))?;
    let layer_sizes_arr = expect_array("nn_create", layer_sizes_val)?;

    let layer_sizes: Vec<usize> = layer_sizes_arr
        .iter()
        .map(|v| {
            let n = match v {
                Value::Int(n) => *n,
                other => {
                    return Err(crate::safety::bad_arg(
                        "nn_create",
                        "layer size: Int",
                        other.type_name(),
                    ))
                }
            };
            usize::try_from(n).ok().filter(|&n| n > 0).ok_or_else(|| {
                crate::safety::arg_err("nn_create: layer sizes must be positive integers")
            })
        })
        .collect::<Result<Vec<_>>>()?;

    if layer_sizes.len() < 2 {
        return Err(crate::safety::arg_err(
            "nn_create requires at least 2 layers (input and output)",
        ));
    }

    let mut count = 0usize;
    for sizes in layer_sizes.windows(2) {
        count = checked_nn_parameter_count(count, sizes[0], sizes[1])?;
    }
    let parse_activation = |value: &Value| {
        let name = expect_string("nn_create", value)?;
        Activation::from_str(name).ok_or_else(|| {
            crate::safety::bad_arg(
                "nn_create",
                "relu, sigmoid, tanh, softmax, linear, swish or leaky_relu",
                name,
            )
        })
    };
    let hidden_activation = args
        .get(2)
        .map(parse_activation)
        .transpose()?
        .unwrap_or(Activation::ReLU);
    let output_activation = args
        .get(3)
        .map(parse_activation)
        .transpose()?
        .unwrap_or(Activation::Tanh);

    let network =
        NeuralNetwork::feedforward(name, &layer_sizes, hidden_activation, output_activation);
    nn_to_value(&network)
}

/// nn_forward(network, input)
/// Forward pass through the network
/// Args:
///   - network: Record - Network from nn_create
///   - input: Array[Float] - Input values
/// Returns: Array[Float] - Output values
fn bi_nn_forward(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let has_input = input.is_some();
    let network_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("nn_forward requires network"))?;

    let network = value_to_nn(&network_val)?;

    let input_val = args
        .get(if has_input { 0 } else { 1 })
        .ok_or_else(|| crate::safety::arg_err("nn_forward requires input array"))?;
    let input_arr = expect_array("nn_forward", input_val)?;

    let input_vec: Vec<f64> = input_arr
        .iter()
        .map(|v| finite_nn_number("nn_forward", v))
        .collect::<Result<Vec<_>>>()?;
    if input_vec.len() != network.layers[0].input_size {
        return Err(crate::safety::arg_err(
            "nn_forward: input length must equal the network input size",
        ));
    }
    let output = network.forward(&input_vec);
    if output.iter().any(|n| !n.is_finite()) {
        return Err(crate::safety::bad_state_with_hint(
            "nn_forward",
            "non-finite output",
            "the computation exceeded the numeric range",
        ));
    }
    Ok(Value::Array(output.into_iter().map(Value::Float).collect()))
}

/// nn_mutate(network, rate, strength)
/// Mutate network parameters
/// Args:
///   - network: Record - Network to mutate
///   - rate: Float - Mutation probability (0.0-1.0)
///   - strength: Float - Mutation magnitude
/// Returns: Record - Mutated network
fn bi_nn_mutate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let has_input = input.is_some();
    let network_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("nn_mutate requires network"))?;

    let network = value_to_nn(&network_val)?;

    let idx = if has_input { 0 } else { 1 };
    let rate = args
        .get(idx)
        .map(|v| finite_nn_number("nn_mutate", v))
        .transpose()?
        .unwrap_or(0.1);
    let strength = args
        .get(idx + 1)
        .map(|v| finite_nn_number("nn_mutate", v))
        .transpose()?
        .unwrap_or(0.3);

    if !(0.0..=1.0).contains(&rate) || strength < 0.0 {
        return Err(crate::safety::arg_err(
            "nn_mutate: rate must be in 0..=1 and strength non-negative",
        ));
    }
    let mutated = network.mutate(rate, strength);
    validate_nn(&mutated)?;
    nn_to_value(&mutated)
}

/// nn_crossover(network1, network2)
/// Crossover two networks
/// Args:
///   - network1: Record - First parent network
///   - network2: Record - Second parent network
/// Returns: Record - Child network
fn bi_nn_crossover(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::safety::arg_err("nn_crossover requires two networks"));
    }

    let net1 = value_to_nn(&args[0])?;
    let net2 = value_to_nn(&args[1])?;
    if net1.layers.len() != net2.layers.len()
        || net1
            .layers
            .iter()
            .zip(&net2.layers)
            .any(|(a, b)| a.input_size != b.input_size || a.output_size != b.output_size)
    {
        return Err(crate::safety::arg_err(
            "nn_crossover: parent layer dimensions must match",
        ));
    }
    let child = NeuralNetwork::crossover(&net1, &net2);
    nn_to_value(&child)
}

/// nn_params(network)
/// Get network parameters as flat array
/// Args:
///   - network: Record - Network
/// Returns: Array[Float] - All weights and biases
fn bi_nn_params(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let network_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("nn_params requires network"))?;

    let network = value_to_nn(&network_val)?;
    let params = network.get_params();
    Ok(Value::Array(params.into_iter().map(Value::Float).collect()))
}

/// nn_set_params(network, params)
/// Set network parameters from flat array
/// Args:
///   - network: Record - Network
///   - params: Array[Float] - New parameters
/// Returns: Record - Updated network
fn bi_nn_set_params(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let has_input = input.is_some();
    let network_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("nn_set_params requires network"))?;

    let mut network = value_to_nn(&network_val)?;

    let idx = if has_input { 0 } else { 1 };
    let params_val = args
        .get(idx)
        .ok_or_else(|| crate::safety::arg_err("nn_set_params requires params array"))?;
    let params_arr = expect_array("nn_set_params", params_val)?;

    let params: Vec<f64> = params_arr
        .iter()
        .map(|v| finite_nn_number("nn_set_params", v))
        .collect::<Result<Vec<_>>>()?;
    if params.len() != network.param_count() {
        return Err(crate::safety::arg_err(
            "nn_set_params: parameter length must equal the network parameter count",
        ));
    }
    network.set_params(&params);
    nn_to_value(&network)
}

/// nn_layers(network)
/// Get layer information
/// Args:
///   - network: Record - Network
/// Returns: Array[Record] - Layer specifications
fn bi_nn_layers(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let network_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("nn_layers requires network"))?;

    let network = value_to_nn(&network_val)?;

    let layers: Vec<Value> = network
        .layers
        .iter()
        .map(|layer| {
            let mut rec = BTreeMap::new();
            rec.insert(
                "input_size".to_string(),
                Value::Int(layer.input_size as i64),
            );
            rec.insert(
                "output_size".to_string(),
                Value::Int(layer.output_size as i64),
            );
            rec.insert(
                "activation".to_string(),
                Value::Str(format!("{:?}", layer.activation)),
            );
            rec.insert(
                "param_count".to_string(),
                Value::Int(layer.param_count() as i64),
            );
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(layers))
}

/// nn_info(network)
/// Get network summary information
/// Args:
///   - network: Record - Network
/// Returns: Record - Network info including total params, layer count, etc.
fn bi_nn_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let network_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("nn_info requires network"))?;

    let network = value_to_nn(&network_val)?;

    let mut info = BTreeMap::new();
    info.insert("name".to_string(), Value::Str(network.name.clone()));
    info.insert(
        "layer_count".to_string(),
        Value::Int(network.layers.len() as i64),
    );
    info.insert(
        "param_count".to_string(),
        Value::Int(network.param_count() as i64),
    );

    if let Some(first) = network.layers.first() {
        info.insert(
            "input_size".to_string(),
            Value::Int(first.input_size as i64),
        );
    }
    if let Some(last) = network.layers.last() {
        info.insert(
            "output_size".to_string(),
            Value::Int(last.output_size as i64),
        );
    }

    Ok(Value::Record(info))
}

/// consensus_net(name, agent_count, input_size, hidden_size, output_size)
/// Create a consensus network for distributed decision making
/// Args:
///   - name: String - Network name
///   - agent_count: Int - Number of agents
///   - input_size: Int - Input dimension
///   - hidden_size: Int - Hidden layer size
///   - output_size: Int - Output dimension (decision size)
/// Returns: Record - Consensus network
fn bi_consensus_net(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.len() < 5 {
        return Err(crate::safety::arg_err(
            "consensus_net requires name, agent_count, input_size, hidden_size, output_size",
        ));
    }

    let name = expect_string("consensus_net", &args[0])?;
    let size = |value: &Value| -> Result<usize> {
        let n = expect_int("consensus_net", value)?;
        usize::try_from(n).ok().filter(|n| *n > 0).ok_or_else(|| {
            crate::safety::arg_err("consensus_net sizes must be positive representable integers")
        })
    };
    let agent_count = size(&args[1])?;
    let input_size = size(&args[2])?;
    let hidden_size = size(&args[3])?;
    let output_size = size(&args[4])?;
    if agent_count > 1024 {
        return Err(crate::safety::budget_exceeded(
            "consensus_net",
            "supports at most 1024 agents".into(),
            "use fewer agents",
        ));
    }
    let twice_input = input_size.checked_mul(2);
    let twice_hidden = hidden_size.checked_mul(2);
    let decision_input = hidden_size.checked_add(input_size);
    let decision_hidden = hidden_size.checked_add(output_size).map(|n| n / 2);
    let dimensions = twice_input
        .zip(twice_hidden)
        .zip(decision_input.zip(decision_hidden))
        .ok_or_else(|| crate::safety::arg_err("consensus_net dimension arithmetic overflow"))?;
    let ((twice_input, twice_hidden), (decision_input, decision_hidden)) = dimensions;
    let mut total = 0;
    for (input, output) in [
        (input_size, twice_input),
        (twice_input, hidden_size),
        (twice_hidden, twice_hidden),
        (twice_hidden, hidden_size),
        (decision_input, decision_hidden),
        (decision_hidden, output_size),
    ] {
        total = checked_nn_parameter_count(total, input, output)?;
    }
    for _ in 0..agent_count {
        total = checked_nn_parameter_count(total, input_size, input_size)?;
        total = checked_nn_parameter_count(total, input_size, hidden_size)?;
    }

    let consensus = ConsensusNetwork::new(name, agent_count, input_size, hidden_size, output_size);
    consensus_net_to_value(&consensus)
}

/// consensus_vote(network, agent_inputs)
/// Run consensus voting across all agents
/// Args:
///   - network: Record - Consensus network
///   - agent_inputs: Array[Array[Float]] - Each agent's input
/// Returns: Record - {decisions: Array[Array], consensus: Array[Float], confidence: Float}
fn bi_consensus_vote(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let has_input = input.is_some();
    let network_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("consensus_vote requires network"))?;

    let mut network = value_to_consensus_net(&network_val)?;

    let idx = if has_input { 0 } else { 1 };
    let inputs_val = args
        .get(idx)
        .ok_or_else(|| crate::safety::arg_err("consensus_vote requires agent_inputs"))?;
    let inputs_arr = expect_array("consensus_vote", inputs_val)?;

    let agent_inputs: Vec<Vec<f64>> = inputs_arr
        .iter()
        .map(|v| {
            let arr = expect_array("consensus_vote", v)?;
            arr.iter()
                .map(|v| finite_nn_number("consensus_vote", v))
                .collect()
        })
        .collect::<Result<Vec<_>>>()?;

    if agent_inputs.len() != network.agent_networks.len()
        || agent_inputs
            .iter()
            .any(|row| row.len() != network.state_dim)
    {
        return Err(crate::safety::arg_err(
            "consensus_vote requires exactly one state_dim input row per agent",
        ));
    }
    let (decisions, consensus) = network.consensus(&agent_inputs);

    if decisions
        .iter()
        .flatten()
        .chain(consensus.iter())
        .any(|n| !n.is_finite())
    {
        return Err(crate::safety::bad_state_with_hint(
            "consensus_vote",
            "non-finite output",
            "the computation exceeded the numeric range",
        ));
    }
    // Confidence is the reciprocal of one plus the mean squared disagreement.
    let decision_dim = decisions.first().map(|d| d.len()).unwrap_or(0);
    let mean: Vec<f64> = (0..decision_dim)
        .map(|i| {
            decisions
                .iter()
                .map(|d| d.get(i).copied().unwrap_or(0.0))
                .sum::<f64>()
                / decisions.len().max(1) as f64
        })
        .collect();
    let variance: f64 = decisions
        .iter()
        .map(|d: &Vec<f64>| {
            d.iter()
                .zip(&mean)
                .map(|(a, b)| (a - b).powi(2))
                .sum::<f64>()
        })
        .sum::<f64>()
        / decisions.len().max(1) as f64;
    let confidence = 1.0 / (1.0 + variance);

    let mut result = BTreeMap::new();
    result.insert(
        "decisions".to_string(),
        Value::Array(
            decisions
                .into_iter()
                .map(|d: Vec<f64>| Value::Array(d.into_iter().map(Value::Float).collect()))
                .collect(),
        ),
    );
    result.insert(
        "consensus".to_string(),
        Value::Array(consensus.into_iter().map(Value::Float).collect()),
    );
    result.insert("confidence".to_string(), Value::Float(confidence));

    Ok(Value::Record(result))
}

/// activation(name)
/// Get activation function by name
/// Args:
///   - name: String - "relu", "sigmoid", "tanh", "softmax", "linear", "swish", "leaky_relu"
/// Returns: Record - Activation function info
fn bi_activation(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = args
        .first()
        .and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.as_str())
            } else {
                None
            }
        })
        .ok_or_else(|| crate::safety::arg_err("activation requires name string"))?;

    let activation = Activation::from_str(name).ok_or_else(|| {
        crate::safety::bad_arg(
            "activation",
            "one of: relu, sigmoid, tanh, softmax, linear, swish, leaky_relu",
            name,
        )
    })?;

    let mut info = BTreeMap::new();
    info.insert("name".to_string(), Value::Str(format!("{:?}", activation)));
    info.insert(
        "description".to_string(),
        Value::Str(
            match activation {
                Activation::ReLU => "Rectified Linear Unit: max(0, x)",
                Activation::Sigmoid => "Sigmoid: 1/(1+e^-x), outputs 0-1",
                Activation::Tanh => "Hyperbolic tangent: outputs -1 to 1",
                Activation::Softmax => "Softmax: probability distribution",
                Activation::Linear => "Linear: f(x) = x",
                Activation::LeakyReLU(_) => "Leaky ReLU: x if x>0, else 0.01*x",
                Activation::Swish => "Swish: x * sigmoid(x)",
            }
            .to_string(),
        ),
    );

    Ok(Value::Record(info))
}

// --------------- Evolution Builtins ---------------

/// population(size, genome_type, [config])
/// Create a population for evolution
/// Args:
///   - size: Int - Population size
///   - genome_type: String - "nn" for neural network, "vec" for float vector
///   - config: Record (optional) - Evolution configuration
/// Returns: Record - Population state
fn bi_population(args: Vec<Value>, _input: Option<Value>, _env: &mut Env) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "population requires size and genome_type",
        ));
    }

    let size_value = expect_int("population", &args[0])?;
    let size = usize::try_from(size_value)
        .ok()
        .filter(|n| *n > 0)
        .ok_or_else(|| {
            crate::safety::arg_err("population size must be a positive representable Int")
        })?;
    let genome_type = expect_string("population", &args[1])?;
    let config = parse_evolution_options("population", args.get(2), Some(size))?;

    // Create population based on genome type
    match genome_type {
        "nn" => {
            let pop: Population<NeuralNetwork> = Population::new(config.clone());
            population_to_value(&pop, "nn")
        }
        "vec" | "vector" => {
            let pop: Population<Vec<f64>> = Population::new(config.clone());
            population_to_value(&pop, "vec")
        }
        _ => Err(crate::safety::bad_arg(
            "population",
            "genome_type: nn, vec or vector",
            genome_type,
        )),
    }
}

/// evolve(population, fitness_fn, generations)
/// Run evolution for multiple generations
/// Args:
///   - population: Record - Population from population()
///   - fitness_fn: Lambda - fn(genome) => Float
///   - generations: Int - Number of generations
/// Returns: Record - Updated population with stats
fn bi_evolve(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    evolution_operation("evolve", args, input, env, true, false)
}

/// Run one generation, evaluating uncached parents before reproduction.
fn bi_evolve_step(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    evolution_operation("evolve_step", args, input, env, false, false)
}

/// Evaluate uncached individuals and retain their scores for subsequent calls.
fn bi_fitness(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    evolution_operation("fitness", args, input, env, false, true)
}

fn evolution_operation(
    name: &str,
    args: Vec<Value>,
    input: Option<Value>,
    env: &mut Env,
    multiple: bool,
    evaluate_only: bool,
) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err(format!("{name} requires population")))?;
    let idx = usize::from(!piped);
    let lambda = need_lambda(
        args.get(idx)
            .ok_or_else(|| crate::safety::arg_err(format!("{name} requires fitness function")))?,
        name,
    )?
    .clone();
    if lambda.params.len() != 1 {
        return Err(crate::safety::arg_err(format!(
            "{name}: fitness function must take exactly one genome parameter"
        )));
    }
    let generations = if evaluate_only {
        None
    } else if multiple {
        let count = match args.get(idx + 1) {
            None => 10,
            Some(Value::Int(n)) => usize::try_from(*n)
                .map_err(|_| crate::safety::arg_err("evolve: generations must be non-negative"))?,
            Some(other) => {
                return Err(crate::safety::bad_arg(
                    name,
                    "generations: Int",
                    other.type_name(),
                ))
            }
        };
        Some(count)
    } else {
        Some(1)
    };
    match get_population_genome_type(&value)?.as_str() {
        "nn" => {
            let mut population = value_to_population_nn(&value)?;
            run_population_operation(
                name,
                &mut population,
                &lambda,
                env,
                generations,
                nn_to_value,
                validate_nn,
            )?;
            population_to_value(&population, "nn")
        }
        "vec" => {
            let mut population = value_to_population_vec(&value)?;
            run_population_operation(
                name,
                &mut population,
                &lambda,
                env,
                generations,
                |genome| {
                    Ok(Value::Array(
                        genome.iter().copied().map(Value::Float).collect(),
                    ))
                },
                |genome| validate_vector_genome(genome),
            )?;
            population_to_value(&population, "vec")
        }
        other => Err(crate::safety::bad_arg(
            name,
            "population genome_type: nn or vec",
            other,
        )),
    }
}

fn check_population_work<G: crate::evolution::Evolvable>(
    name: &str,
    pop: &Population<G>,
    generations: Option<usize>,
) -> Result<()> {
    let count = generations.unwrap_or(1);
    let parameters: usize = pop
        .individuals
        .iter()
        .map(|individual| individual.genome.param_count())
        .sum();
    if count > MAX_EVOLUTION_GENERATIONS
        || pop
            .individuals
            .len()
            .checked_mul(count)
            .is_none_or(|n| n > 100_000)
        || parameters.checked_mul(count).is_none_or(|n| n > 10_000_000)
        || pop
            .stats
            .fitness_history
            .len()
            .checked_add(count)
            .is_none_or(|n| n > MAX_EVOLUTION_GENERATIONS)
    {
        return Err(crate::safety::budget_exceeded(
            name,
            "evolution work or history budget exceeded".into(),
            "use fewer generations or a smaller population",
        ));
    }
    let final_generation = pop.generation.checked_add(generations.unwrap_or(0));
    let final_id = pop
        .next_id
        .checked_add(pop.individuals.len() * generations.unwrap_or(0));
    if final_generation.is_none_or(|n| i64::try_from(n).is_err())
        || final_id.is_none_or(|n| i64::try_from(n).is_err())
    {
        return Err(crate::safety::arg_err(
            "evolution generation or individual ID overflow",
        ));
    }
    Ok(())
}

fn run_population_operation<G: crate::evolution::Evolvable>(
    name: &str,
    pop: &mut Population<G>,
    lambda: &Lambda,
    env: &mut Env,
    generations: Option<usize>,
    encode: impl Fn(&G) -> Result<Value>,
    validate: impl Fn(&G) -> Result<()>,
) -> Result<()> {
    check_population_work(name, pop, generations)?;
    let count = generations.unwrap_or(1);
    for _ in 0..count {
        // Populate the cache fallibly before entering the infallible engine.
        // A failed callback never becomes a zero score or triggers another call.
        for individual in &mut pop.individuals {
            if individual.fitness.is_none() {
                let result = call_lambda(lambda, &[encode(&individual.genome)?], env)?;
                individual.fitness = Some(FitnessResult::new(finite_nn_number(name, &result)?));
            }
        }
        if generations.is_some() {
            pop.evolve(|_| unreachable!("all parent fitness values were evaluated"));
        } else {
            pop.evaluate(|_| unreachable!("all fitness values were evaluated"));
            pop.stats.generation = pop.generation;
        }
        if [
            pop.stats.best_fitness,
            pop.stats.worst_fitness,
            pop.stats.avg_fitness,
            pop.stats.diversity,
        ]
        .iter()
        .any(|n| !n.is_finite())
        {
            return Err(crate::safety::bad_state_with_hint(
                name,
                "non-finite statistics",
                "fitness arithmetic exceeded the numeric range",
            ));
        }
        for individual in &pop.individuals {
            validate(&individual.genome).map_err(|_| {
                crate::safety::bad_state_with_hint(
                    name,
                    "invalid resulting genome",
                    "mutation exceeded the numeric range",
                )
            })?;
        }
    }
    Ok(())
}

/// best_individual(population)
/// Get the best individual from population
fn bi_best_individual(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let pop_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("best_individual requires population"))?;

    let genome_type = get_population_genome_type(&pop_val)?;

    match genome_type.as_str() {
        "nn" => {
            let pop = value_to_population_nn(&pop_val)?;
            if pop
                .individuals
                .iter()
                .any(|individual| individual.fitness.is_none())
            {
                return Err(crate::safety::bad_state_with_hint(
                    "best_individual",
                    "population is not fully evaluated",
                    "call fitness before ranking individuals",
                ));
            }
            let best = pop
                .individuals
                .iter()
                .max_by(|a, b| {
                    a.score()
                        .partial_cmp(&b.score())
                        .unwrap_or(std::cmp::Ordering::Equal)
                })
                .ok_or_else(|| crate::safety::arg_err("Empty population"))?;

            let mut result = BTreeMap::new();
            result.insert("genome".to_string(), nn_to_value(&best.genome)?);
            result.insert("fitness".to_string(), Value::Float(best.score()));
            result.insert("generation".to_string(), Value::Int(best.generation as i64));
            result.insert("id".to_string(), Value::Int(best.id as i64));
            Ok(Value::Record(result))
        }
        "vec" => {
            let pop = value_to_population_vec(&pop_val)?;
            if pop
                .individuals
                .iter()
                .any(|individual| individual.fitness.is_none())
            {
                return Err(crate::safety::bad_state_with_hint(
                    "best_individual",
                    "population is not fully evaluated",
                    "call fitness before ranking individuals",
                ));
            }
            let best = pop
                .individuals
                .iter()
                .max_by(|a, b| {
                    a.score()
                        .partial_cmp(&b.score())
                        .unwrap_or(std::cmp::Ordering::Equal)
                })
                .ok_or_else(|| crate::safety::arg_err("Empty population"))?;

            let mut result = BTreeMap::new();
            result.insert(
                "genome".to_string(),
                Value::Array(best.genome.iter().map(|&f| Value::Float(f)).collect()),
            );
            result.insert("fitness".to_string(), Value::Float(best.score()));
            result.insert("generation".to_string(), Value::Int(best.generation as i64));
            result.insert("id".to_string(), Value::Int(best.id as i64));
            Ok(Value::Record(result))
        }
        _ => Err(crate::safety::bad_arg(
            "best_individual",
            "population genome_type: nn or vec",
            &genome_type,
        )),
    }
}

/// evolution_stats(population)
/// Get evolution statistics
fn bi_evolution_stats(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let pop_val = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("evolution_stats requires population"))?;

    if let Value::Record(rec) = &pop_val {
        if let Some(Value::Record(stats)) = rec.get("stats") {
            return Ok(Value::Record(stats.clone()));
        }
    }

    Err(crate::safety::arg_err(
        "Could not extract stats from population",
    ))
}

/// selection_strategy(name, [param])
/// Create selection strategy
/// Args:
///   - name: String - "tournament", "roulette", "rank", "truncation", "elite"
///   - param: Int/Float (optional) - Strategy parameter
fn bi_selection_strategy(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = args
        .first()
        .and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.as_str())
            } else {
                None
            }
        })
        .ok_or_else(|| crate::safety::arg_err("selection_strategy requires name"))?;

    let strategy = match name.to_lowercase().as_str() {
        "tournament" => {
            let size = args
                .get(1)
                .map(|v| match v {
                    Value::Int(n) => Ok(*n),
                    other => Err(crate::safety::bad_arg(
                        "selection_strategy",
                        "parameter: Int",
                        other.type_name(),
                    )),
                })
                .transpose()?
                .unwrap_or(3);
            let size = usize::try_from(size)
                .ok()
                .filter(|&n| n > 0)
                .ok_or_else(|| {
                    crate::safety::arg_err("selection_strategy: tournament size must be positive")
                })?;
            SelectionStrategy::Tournament(size)
        }
        "roulette" | "rank" if args.len() > 1 => {
            return Err(crate::safety::arg_err(
                "selection_strategy: roulette and rank take no parameter",
            ))
        }
        "roulette" => SelectionStrategy::Roulette,
        "rank" => SelectionStrategy::Rank,
        "truncation" => {
            let ratio = args
                .get(1)
                .map(|v| finite_nn_number("selection_strategy", v))
                .transpose()?
                .unwrap_or(0.5);
            if !(0.0..=1.0).contains(&ratio) {
                return Err(crate::safety::arg_err(
                    "selection_strategy: truncation ratio must be in 0..=1",
                ));
            }
            SelectionStrategy::Truncation(ratio)
        }
        "elite" => {
            let n = args
                .get(1)
                .map(|v| match v {
                    Value::Int(n) => Ok(*n),
                    other => Err(crate::safety::bad_arg(
                        "selection_strategy",
                        "parameter: Int",
                        other.type_name(),
                    )),
                })
                .transpose()?
                .unwrap_or(5);
            let n = usize::try_from(n).ok().filter(|&n| n > 0).ok_or_else(|| {
                crate::safety::arg_err("selection_strategy: elite count must be positive")
            })?;
            SelectionStrategy::Elite(n)
        }
        _ => {
            return Err(crate::safety::bad_arg(
                "selection_strategy",
                "one of: tournament, roulette, rank, truncation, elite",
                name,
            ))
        }
    };

    let mut result = BTreeMap::new();
    result.insert(
        "type".to_string(),
        Value::Str("selection_strategy".to_string()),
    );
    result.insert("name".to_string(), Value::Str(format!("{:?}", strategy)));
    Ok(Value::Record(result))
}

/// crossover_strategy(name, [param])
/// Create crossover strategy
fn bi_crossover_strategy(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = args
        .first()
        .and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.as_str())
            } else {
                None
            }
        })
        .ok_or_else(|| crate::safety::arg_err("crossover_strategy requires name"))?;

    let strategy = match name.to_lowercase().as_str() {
        "single_point" | "singlepoint" | "two_point" | "twopoint" if args.len() > 1 => {
            return Err(crate::safety::arg_err(
                "crossover_strategy: point crossover takes no parameter",
            ))
        }
        "single_point" | "singlepoint" => CrossoverStrategy::SinglePoint,
        "two_point" | "twopoint" => CrossoverStrategy::TwoPoint,
        "uniform" => {
            let prob = args
                .get(1)
                .map(|v| finite_nn_number("crossover_strategy", v))
                .transpose()?
                .unwrap_or(0.5);
            if !(0.0..=1.0).contains(&prob) {
                return Err(crate::safety::arg_err(
                    "crossover_strategy: probability must be in 0..=1",
                ));
            }
            CrossoverStrategy::Uniform(prob)
        }
        "blend" => {
            let alpha = args
                .get(1)
                .map(|v| finite_nn_number("crossover_strategy", v))
                .transpose()?
                .unwrap_or(0.5);
            if alpha < 0.0 {
                return Err(crate::safety::arg_err(
                    "crossover_strategy: alpha must be non-negative",
                ));
            }
            CrossoverStrategy::Blend(alpha)
        }
        "sbx" => {
            let eta = args
                .get(1)
                .map(|v| finite_nn_number("crossover_strategy", v))
                .transpose()?
                .unwrap_or(20.0);
            if eta <= 0.0 {
                return Err(crate::safety::arg_err(
                    "crossover_strategy: eta must be positive",
                ));
            }
            CrossoverStrategy::SBX(eta)
        }
        _ => {
            return Err(crate::safety::bad_arg(
                "crossover_strategy",
                "one of: single_point, two_point, uniform, blend, sbx",
                name,
            ))
        }
    };

    let mut result = BTreeMap::new();
    result.insert(
        "type".to_string(),
        Value::Str("crossover_strategy".to_string()),
    );
    result.insert("name".to_string(), Value::Str(format!("{:?}", strategy)));
    Ok(Value::Record(result))
}

const MAX_EVOLUTION_POPULATION: usize = 10_000;
const MAX_EVOLUTION_GENERATIONS: usize = 10_000;

fn parse_evolution_options(
    builtin: &str,
    options: Option<&Value>,
    size: Option<usize>,
) -> Result<EvolutionConfig> {
    let opts = match options {
        None => None,
        Some(Value::Record(opts)) => Some(opts),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "options: Record",
                other.type_name(),
            ))
        }
    };
    if let Some(opts) = opts {
        for (key, value) in opts {
            match key.as_str() {
                "population_size" | "generations" | "mutation_rate" | "mutation_strength"
                | "crossover_rate" | "elitism" => {}
                "type" if matches!(value, Value::Str(tag) if tag == "evolution_config") => {}
                _ => {
                    return Err(crate::safety::arg_err(format!(
                        "{builtin}: unknown option or invalid configuration marker {key}"
                    )))
                }
            }
        }
    }
    let get = |key: &str| opts.and_then(|opts| opts.get(key));
    let integer = |key: &str, default: usize, positive: bool| -> Result<usize> {
        let Some(value) = get(key) else {
            return Ok(default);
        };
        let n = match value {
            Value::Int(n) => *n,
            other => {
                return Err(crate::safety::bad_arg(
                    builtin,
                    &format!("{key}: Int"),
                    other.type_name(),
                ))
            }
        };
        usize::try_from(n)
            .ok()
            .filter(|n| !positive || *n > 0)
            .ok_or_else(|| {
                crate::safety::arg_err(format!(
                    "{builtin}: {key} must be a {}representable Int",
                    if positive {
                        "positive "
                    } else {
                        "non-negative "
                    }
                ))
            })
    };
    let mut config = EvolutionConfig::default();
    config.population_size = integer(
        "population_size",
        size.unwrap_or(config.population_size),
        true,
    )?;
    if size.is_some_and(|size| size != config.population_size) {
        return Err(crate::safety::arg_err(
            "population: configuration population_size must match the size argument",
        ));
    }
    config.generations = integer("generations", config.generations, false)?;
    if config.population_size > MAX_EVOLUTION_POPULATION
        || config.generations > MAX_EVOLUTION_GENERATIONS
    {
        return Err(crate::safety::budget_exceeded(
            builtin,
            "population_size and generations are limited to 10000".into(),
            "use a smaller population or fewer generations",
        ));
    }
    config.elitism = integer("elitism", config.elitism.min(config.population_size), false)?;
    if config.elitism > config.population_size {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: elitism cannot exceed population_size"
        )));
    }
    let number = |key: &str, default: f64| -> Result<f64> {
        get(key)
            .map(|value| finite_nn_number(builtin, value))
            .transpose()
            .map(|value| value.unwrap_or(default))
    };
    config.mutation_rate = number("mutation_rate", config.mutation_rate)?;
    config.mutation_strength = number("mutation_strength", config.mutation_strength)?;
    config.crossover_rate = number("crossover_rate", config.crossover_rate)?;
    if !(0.0..=1.0).contains(&config.mutation_rate)
        || !(0.0..=1.0).contains(&config.crossover_rate)
        || config.mutation_strength < 0.0
    {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: rates must be in 0..=1 and mutation_strength non-negative"
        )));
    }
    Ok(config)
}

/// evolution_config([options])
/// Create evolution configuration
fn bi_evolution_config(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let config = parse_evolution_options("evolution_config", args.first(), None)?;

    let mut result = BTreeMap::new();
    result.insert(
        "type".to_string(),
        Value::Str("evolution_config".to_string()),
    );
    result.insert(
        "population_size".to_string(),
        Value::Int(config.population_size as i64),
    );
    result.insert(
        "generations".to_string(),
        Value::Int(config.generations as i64),
    );
    result.insert(
        "mutation_rate".to_string(),
        Value::Float(config.mutation_rate),
    );
    result.insert(
        "mutation_strength".to_string(),
        Value::Float(config.mutation_strength),
    );
    result.insert(
        "crossover_rate".to_string(),
        Value::Float(config.crossover_rate),
    );
    result.insert("elitism".to_string(), Value::Int(config.elitism as i64));
    Ok(Value::Record(result))
}

/// Decoded population variants retained during batch preflight.
enum EvolutionPopulation {
    Neural(Population<NeuralNetwork>),
    Vector(Population<Vec<f64>>),
}

/// Evolve populations independently after validating the complete batch.
fn bi_coevolve(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("coevolve requires populations array"))?;
    let values = expect_array("coevolve", &value)?;
    let idx = usize::from(!piped);
    let lambda = need_lambda(
        args.get(idx)
            .ok_or_else(|| crate::safety::arg_err("coevolve requires fitness function"))?,
        "coevolve",
    )?
    .clone();
    if lambda.params.len() != 1 {
        return Err(crate::safety::arg_err(
            "coevolve: fitness function must take exactly one genome parameter",
        ));
    }
    let generations = match args.get(idx + 1) {
        None => 10,
        Some(Value::Int(n)) => usize::try_from(*n)
            .map_err(|_| crate::safety::arg_err("coevolve: generations must be non-negative"))?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "coevolve",
                "generations: Int",
                other.type_name(),
            ))
        }
    };
    let budget = || {
        crate::safety::budget_exceeded(
            "coevolve",
            "combined population, encoding, history or work budget exceeded".into(),
            "use fewer or smaller populations and fewer generations",
        )
    };
    if values.len() > MAX_EVOLUTION_POPULATION || generations > MAX_EVOLUTION_GENERATIONS {
        return Err(budget());
    }
    let mut bytes = 0usize;
    for value in values {
        if let Value::Record(record) = value {
            for key in ["_individuals", "_config"] {
                if let Some(Value::Str(data)) = record.get(key) {
                    bytes = bytes
                        .checked_add(data.len())
                        .filter(|n| *n <= 64 * 1024 * 1024)
                        .ok_or_else(&budget)?;
                }
            }
        }
    }
    // Decode and preflight the complete batch before invoking any callback.
    let mut populations = Vec::with_capacity(values.len());
    let mut individuals = 0usize;
    let mut parameters = 0usize;
    let mut history = 0usize;
    for value in values {
        let (population, size, params, entries) = match get_population_genome_type(value)?.as_str()
        {
            "nn" => {
                let pop = value_to_population_nn(value)?;
                check_population_work("coevolve", &pop, Some(generations))?;
                let params = pop
                    .individuals
                    .iter()
                    .map(|individual| individual.genome.param_count())
                    .sum::<usize>();
                let size = pop.individuals.len();
                let entries = pop.stats.fitness_history.len();
                (EvolutionPopulation::Neural(pop), size, params, entries)
            }
            "vec" => {
                let pop = value_to_population_vec(value)?;
                check_population_work("coevolve", &pop, Some(generations))?;
                let params = pop
                    .individuals
                    .iter()
                    .map(|individual| individual.genome.len())
                    .sum::<usize>();
                let size = pop.individuals.len();
                let entries = pop.stats.fitness_history.len();
                (EvolutionPopulation::Vector(pop), size, params, entries)
            }
            other => {
                return Err(crate::safety::bad_arg(
                    "coevolve",
                    "population genome_type: nn or vec",
                    other,
                ))
            }
        };
        individuals = individuals
            .checked_add(size)
            .filter(|n| *n <= MAX_EVOLUTION_POPULATION)
            .ok_or_else(&budget)?;
        parameters = parameters
            .checked_add(params)
            .filter(|n| *n <= MAX_NN_PARAMETERS)
            .ok_or_else(&budget)?;
        history = history
            .checked_add(entries)
            .filter(|n| *n <= MAX_EVOLUTION_GENERATIONS)
            .ok_or_else(&budget)?;
        populations.push(population);
    }
    if individuals
        .checked_mul(generations)
        .is_none_or(|n| n > 100_000)
        || parameters
            .checked_mul(generations)
            .is_none_or(|n| n > 10_000_000)
        || populations
            .len()
            .checked_mul(generations)
            .and_then(|n| history.checked_add(n))
            .is_none_or(|n| n > MAX_EVOLUTION_GENERATIONS)
    {
        return Err(budget());
    }
    let mut results = Vec::with_capacity(populations.len());
    for population in populations {
        match population {
            EvolutionPopulation::Neural(mut pop) => {
                run_population_operation(
                    "coevolve",
                    &mut pop,
                    &lambda,
                    env,
                    Some(generations),
                    nn_to_value,
                    validate_nn,
                )?;
                results.push(population_to_value(&pop, "nn")?);
            }
            EvolutionPopulation::Vector(mut pop) => {
                run_population_operation(
                    "coevolve",
                    &mut pop,
                    &lambda,
                    env,
                    Some(generations),
                    |genome| {
                        Ok(Value::Array(
                            genome.iter().copied().map(Value::Float).collect(),
                        ))
                    },
                    |genome| validate_vector_genome(genome),
                )?;
                results.push(population_to_value(&pop, "vec")?);
            }
        }
    }
    Ok(Value::Array(results))
}

// --------------- Neural/Evolution Helpers ---------------

const MAX_NN_PARAMETERS: usize = 1_000_000;

fn finite_nn_number(builtin: &str, value: &Value) -> Result<f64> {
    let number = match value {
        Value::Int(n) => *n as f64,
        Value::Float(n) => *n,
        other => {
            return Err(crate::safety::bad_arg(
                builtin,
                "finite Number",
                other.type_name(),
            ))
        }
    };
    if !number.is_finite() {
        return Err(crate::safety::arg_err(&format!(
            "{builtin}: number must be finite"
        )));
    }
    Ok(number)
}

fn checked_nn_parameter_count(total: usize, input: usize, output: usize) -> Result<usize> {
    total
        .checked_add(
            input
                .checked_mul(output)
                .and_then(|n| n.checked_add(output))
                .ok_or_else(|| {
                    crate::safety::arg_err("neural network: parameter count overflow")
                })?,
        )
        .filter(|&n| n <= MAX_NN_PARAMETERS)
        .ok_or_else(|| {
            budget_unnamed(
                "neural network: exceeds 1000000 parameters",
                "reduce the number of layers or their sizes; the limit is 1000000 parameters",
            )
        })
}

fn validate_nn(network: &NeuralNetwork) -> Result<()> {
    if network.layers.is_empty() {
        return Err(crate::safety::arg_err(
            "neural network: at least one dense layer is required",
        ));
    }
    let mut total = 0;
    let mut previous_output = None;
    for layer in &network.layers {
        total = checked_nn_parameter_count(total, layer.input_size, layer.output_size)?;
        if layer.input_size == 0
            || layer.output_size == 0
            || previous_output.is_some_and(|n| n != layer.input_size)
            || layer.weights.len() != layer.output_size
            || layer.biases.len() != layer.output_size
            || layer
                .weights
                .iter()
                .any(|row| row.len() != layer.input_size || row.iter().any(|n| !n.is_finite()))
            || layer.biases.iter().any(|n| !n.is_finite())
            || matches!(layer.activation, Activation::LeakyReLU(alpha) if !alpha.is_finite())
        {
            return Err(crate::safety::arg_err(
                "neural network: inconsistent layer dimensions or non-finite parameters",
            ));
        }
        previous_output = Some(layer.output_size);
    }
    Ok(())
}

fn value_to_f64(v: &Value) -> Result<f64> {
    match v {
        Value::Float(f) => Ok(*f),
        Value::Int(i) => Ok(*i as f64),
        _ => Err(crate::safety::arg_err(format!(
            "Expected numeric value, got {:?}",
            v
        ))),
    }
}

fn nn_to_value(network: &NeuralNetwork) -> Result<Value> {
    let json = serde_json::to_string(network).context("Failed to serialize network")?;

    let mut rec = BTreeMap::new();
    rec.insert("type".to_string(), Value::Str("neural_network".to_string()));
    rec.insert("name".to_string(), Value::Str(network.name.clone()));
    rec.insert(
        "layer_count".to_string(),
        Value::Int(network.layers.len() as i64),
    );
    rec.insert(
        "param_count".to_string(),
        Value::Int(network.param_count() as i64),
    );
    rec.insert("_data".to_string(), Value::Str(json));
    Ok(Value::Record(rec))
}

fn value_to_nn(v: &Value) -> Result<NeuralNetwork> {
    if let Value::Record(rec) = v {
        if let Some(Value::Str(data)) = rec.get("_data") {
            if data.len() > 64 * 1024 * 1024 {
                return Err(budget_unnamed(
                    "neural network: encoded data exceeds 64 MiB",
                    "the encoded network is larger than 64 MiB and cannot be decoded",
                ));
            }
            let network = serde_json::from_str(data).map_err(|e| {
                crate::safety::arg_err(&format!("neural network: invalid encoded data: {e}"))
            })?;
            validate_nn(&network)?;
            return Ok(network);
        }
    }
    Err(crate::safety::arg_err("Invalid neural network value"))
}

fn consensus_net_to_value(network: &ConsensusNetwork) -> Result<Value> {
    let json = serde_json::to_string(network).context("Failed to serialize consensus network")?;

    let mut rec = BTreeMap::new();
    rec.insert(
        "type".to_string(),
        Value::Str("consensus_network".to_string()),
    );
    rec.insert("name".to_string(), Value::Str(network.name.clone()));
    rec.insert(
        "agent_count".to_string(),
        Value::Int(network.agent_networks.len() as i64),
    );
    rec.insert("_data".to_string(), Value::Str(json));
    Ok(Value::Record(rec))
}

fn value_to_consensus_net(v: &Value) -> Result<ConsensusNetwork> {
    if let Value::Record(rec) = v {
        if let Some(Value::Str(data)) = rec.get("_data") {
            if data.len() > 64 * 1024 * 1024 {
                return Err(crate::safety::budget_exceeded(
                    "consensus_vote",
                    "consensus network encoding exceeds 64 MiB".into(),
                    "use a smaller network",
                ));
            }
            let network: ConsensusNetwork = serde_json::from_str(data).map_err(|e| {
                crate::safety::bad_arg(
                    "consensus_vote",
                    "valid encoded consensus network",
                    &e.to_string(),
                )
            })?;
            validate_consensus_net(&network)?;
            return Ok(network);
        }
    }
    Err(crate::safety::arg_err("Invalid consensus network value"))
}

fn validate_consensus_net(network: &ConsensusNetwork) -> Result<()> {
    if network.state_dim == 0 || network.message_dim == 0 || network.agent_networks.is_empty() {
        return Err(crate::safety::arg_err(
            "consensus network dimensions and agent count must be positive",
        ));
    }
    if network.agent_networks.len() > 1024 || network.num_rounds > 16 {
        return Err(crate::safety::budget_exceeded(
            "consensus_vote",
            "consensus network exceeds 1024 agents or 16 rounds".into(),
            "use fewer agents or rounds",
        ));
    }
    let mut total = 0;
    for nn in [
        &network.local_encoder,
        &network.message_processor,
        &network.decision_network,
    ]
    .into_iter()
    .chain(network.agent_networks.iter())
    {
        validate_nn(nn)?;
        for layer in &nn.layers {
            total = checked_nn_parameter_count(total, layer.input_size, layer.output_size)?;
        }
    }
    let dimensions_match = |nn: &NeuralNetwork, input: Option<usize>, output: usize| {
        input == Some(nn.layers[0].input_size) && nn.layers.last().unwrap().output_size == output
    };
    if !dimensions_match(
        &network.local_encoder,
        Some(network.state_dim),
        network.message_dim,
    ) || !dimensions_match(
        &network.message_processor,
        network.message_dim.checked_mul(2),
        network.message_dim,
    ) || Some(network.decision_network.layers[0].input_size)
        != network.message_dim.checked_add(network.state_dim)
        || network
            .agent_networks
            .iter()
            .any(|nn| !dimensions_match(nn, Some(network.state_dim), network.message_dim))
    {
        return Err(crate::safety::arg_err(
            "consensus network component dimensions do not match",
        ));
    }
    Ok(())
}

fn get_population_genome_type(v: &Value) -> Result<String> {
    if let Value::Record(rec) = v {
        if let Some(Value::Str(gt)) = rec.get("genome_type") {
            return Ok(gt.clone());
        }
    }
    Err(crate::safety::arg_err(
        "Could not determine genome type from population",
    ))
}

fn population_to_value<G: crate::evolution::Evolvable + serde::Serialize>(
    pop: &Population<G>,
    genome_type: &str,
) -> Result<Value> {
    let json = serde_json::to_string(&pop.individuals).context("Failed to serialize population")?;
    let config_json = serde_json::to_string(&pop.config).context("Failed to serialize config")?;

    let mut stats = BTreeMap::new();
    stats.insert(
        "generation".to_string(),
        Value::Int(pop.stats.generation as i64),
    );
    stats.insert(
        "best_fitness".to_string(),
        Value::Float(pop.stats.best_fitness),
    );
    stats.insert(
        "avg_fitness".to_string(),
        Value::Float(pop.stats.avg_fitness),
    );
    stats.insert(
        "worst_fitness".to_string(),
        Value::Float(pop.stats.worst_fitness),
    );
    stats.insert("diversity".to_string(), Value::Float(pop.stats.diversity));
    stats.insert(
        "history".to_string(),
        Value::Array(
            pop.stats
                .fitness_history
                .iter()
                .map(|&f| Value::Float(f))
                .collect(),
        ),
    );

    let mut rec = BTreeMap::new();
    rec.insert("type".to_string(), Value::Str("population".to_string()));
    rec.insert(
        "genome_type".to_string(),
        Value::Str(genome_type.to_string()),
    );
    rec.insert("size".to_string(), Value::Int(pop.individuals.len() as i64));
    rec.insert("generation".to_string(), Value::Int(pop.generation as i64));
    rec.insert("next_id".to_string(), Value::Int(pop.next_id as i64));
    rec.insert("stats".to_string(), Value::Record(stats));
    rec.insert("_individuals".to_string(), Value::Str(json));
    rec.insert("_config".to_string(), Value::Str(config_json));
    Ok(Value::Record(rec))
}

fn validate_vector_genome(genome: &[f64]) -> Result<()> {
    if genome.is_empty() || genome.iter().any(|n| !n.is_finite()) {
        return Err(crate::safety::arg_err(
            "population vectors must be nonempty and finite",
        ));
    }
    Ok(())
}

fn value_to_population_nn(value: &Value) -> Result<Population<NeuralNetwork>> {
    let pop = decode_population(value, validate_nn)?;
    let dimensions: Vec<_> = pop.individuals[0]
        .genome
        .layers
        .iter()
        .map(|layer| (layer.input_size, layer.output_size))
        .collect();
    if pop.individuals.iter().any(|individual| {
        individual
            .genome
            .layers
            .iter()
            .map(|layer| (layer.input_size, layer.output_size))
            .collect::<Vec<_>>()
            != dimensions
    }) {
        return Err(crate::safety::arg_err(
            "population networks must have matching layer dimensions",
        ));
    }
    Ok(pop)
}

fn value_to_population_vec(value: &Value) -> Result<Population<Vec<f64>>> {
    let pop = decode_population(value, |genome: &Vec<f64>| validate_vector_genome(genome))?;
    let width = pop.individuals[0].genome.len();
    if pop
        .individuals
        .iter()
        .any(|individual| individual.genome.len() != width)
    {
        return Err(crate::safety::arg_err(
            "population vectors must have equal lengths",
        ));
    }
    Ok(pop)
}

fn decode_population<G: crate::evolution::Evolvable + serde::de::DeserializeOwned>(
    value: &Value,
    validate: impl Fn(&G) -> Result<()>,
) -> Result<Population<G>> {
    let Value::Record(record) = value else {
        return Err(crate::safety::arg_err("population must be a Record"));
    };
    let text = |key: &str| -> Result<&str> {
        match record.get(key) {
            Some(Value::Str(text)) => Ok(text),
            _ => Err(crate::safety::arg_err(format!(
                "population requires encoded {key}: String"
            ))),
        }
    };
    let data = text("_individuals")?;
    let config_data = text("_config")?;
    if data.len().saturating_add(config_data.len()) > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "evo",
            "encoded population exceeds 64 MiB".into(),
            "use a smaller population",
        ));
    }
    let individuals: Vec<crate::evolution::Individual<G>> = serde_json::from_str(data)
        .map_err(|e| crate::safety::bad_arg("evo", "valid encoded individuals", &e.to_string()))?;
    let config: EvolutionConfig = serde_json::from_str(config_data).map_err(|e| {
        crate::safety::bad_arg("evo", "valid encoded configuration", &e.to_string())
    })?;
    if individuals.is_empty() || individuals.len() != config.population_size {
        return Err(crate::safety::arg_err(
            "population must be nonempty and match configured population_size",
        ));
    }
    let bounded_int = |n: usize| {
        i64::try_from(n)
            .map(Value::Int)
            .map_err(|_| crate::safety::arg_err("population count exceeds Int range"))
    };
    let options = Value::Record(BTreeMap::from([
        (
            "population_size".into(),
            bounded_int(config.population_size)?,
        ),
        ("generations".into(), bounded_int(config.generations)?),
        ("elitism".into(), bounded_int(config.elitism)?),
        ("mutation_rate".into(), Value::Float(config.mutation_rate)),
        (
            "mutation_strength".into(),
            Value::Float(config.mutation_strength),
        ),
        ("crossover_rate".into(), Value::Float(config.crossover_rate)),
    ]));
    parse_evolution_options("evo", Some(&options), None)?;
    if config.selection != SelectionStrategy::Tournament(3)
        || config.crossover != CrossoverStrategy::Uniform(0.5)
        || config.seed.is_some()
    {
        return Err(crate::safety::arg_err(
            "population uses unsupported selection, crossover or seed settings",
        ));
    }
    let nonnegative = |value: Option<&Value>| -> Result<usize> {
        match value {
            Some(Value::Int(n)) => usize::try_from(*n).map_err(|_| {
                crate::safety::arg_err("population counters must be non-negative Int values")
            }),
            _ => Err(crate::safety::arg_err(
                "population counters must be Int values",
            )),
        }
    };
    let generation = nonnegative(record.get("generation"))?;
    let mut ids = std::collections::HashSet::new();
    let mut parameters = 0usize;
    let mut next_id = 0usize;
    for individual in &individuals {
        validate(&individual.genome)?;
        parameters = parameters
            .checked_add(individual.genome.param_count())
            .filter(|n| *n <= MAX_NN_PARAMETERS)
            .ok_or_else(|| {
                crate::safety::budget_exceeded(
                    "evo",
                    "population exceeds one million genome parameters".into(),
                    "use a smaller population",
                )
            })?;
        if individual.generation > generation
            || i64::try_from(individual.id).is_err()
            || !ids.insert(individual.id)
        {
            return Err(crate::safety::arg_err(
                "population individual counters or IDs are invalid",
            ));
        }
        next_id = next_id.max(
            individual
                .id
                .checked_add(1)
                .ok_or_else(|| crate::safety::arg_err("population individual ID overflow"))?,
        );
        if individual.fitness.as_ref().is_some_and(|fitness| {
            !fitness.score.is_finite() || fitness.metrics.values().any(|n| !n.is_finite())
        }) {
            return Err(crate::safety::arg_err(
                "population fitness values must be finite",
            ));
        }
    }
    if let Some(value) = record.get("next_id") {
        let supplied = nonnegative(Some(value))?;
        if supplied < next_id {
            return Err(crate::safety::arg_err(
                "population next_id would reuse an individual ID",
            ));
        }
        next_id = supplied;
    }
    bounded_int(next_id)?;
    let Some(Value::Record(stats)) = record.get("stats") else {
        return Err(crate::safety::arg_err("population requires stats: Record"));
    };
    let stats_generation = nonnegative(stats.get("generation"))?;
    if stats_generation > generation {
        return Err(crate::safety::arg_err(
            "population stats generation exceeds population generation",
        ));
    }
    let Some(Value::Array(history)) = stats.get("history") else {
        return Err(crate::safety::arg_err(
            "population stats requires history: Array",
        ));
    };
    if history.len() > MAX_EVOLUTION_GENERATIONS {
        return Err(crate::safety::budget_exceeded(
            "evo",
            "population history exceeds 10000 entries".into(),
            "use a shorter history",
        ));
    }
    let history = history
        .iter()
        .map(|value| finite_nn_number("evo", value))
        .collect::<Result<Vec<_>>>()?;
    let number = |key: &str| -> Result<f64> {
        match stats.get(key) {
            Some(Value::Float(n)) => Ok(*n),
            Some(Value::Int(n)) => Ok(*n as f64),
            _ => Err(crate::safety::arg_err(format!(
                "population stats requires numeric {key}"
            ))),
        }
    };
    let best = number("best_fitness")?;
    let worst = number("worst_fitness")?;
    let avg = number("avg_fitness")?;
    let diversity = number("diversity")?;
    let initial = history.is_empty()
        && individuals
            .iter()
            .all(|individual| individual.fitness.is_none())
        && best == f64::NEG_INFINITY
        && worst == f64::INFINITY;
    if (!initial && (!best.is_finite() || !worst.is_finite()))
        || !avg.is_finite()
        || !diversity.is_finite()
        || diversity < 0.0
    {
        return Err(crate::safety::arg_err(
            "population statistics must be finite except unevaluated initial extrema",
        ));
    }
    Ok(Population {
        individuals,
        config,
        generation,
        next_id,
        stats: crate::evolution::EvolutionStats {
            generation: stats_generation,
            best_fitness: best,
            worst_fitness: worst,
            avg_fitness: avg,
            diversity,
            fitness_history: history,
        },
    })
}

// ==================== Reinforcement Learning Builtins ====================

/// Create a Q-learning agent
/// Usage: rl_agent(name, state_size, action_size, [config])
const MAX_RL_CELLS: usize = 1_000_000;

fn rl_positive_size(name: &str, value: &Value) -> Result<usize> {
    match value {
        Value::Int(n) => usize::try_from(*n).ok().filter(|n| *n > 0).ok_or_else(|| {
            crate::safety::arg_err(format!("{name}: size must be a positive representable Int"))
        }),
        other => Err(crate::safety::bad_arg(
            name,
            "positive Int",
            other.type_name(),
        )),
    }
}

fn validate_q_agent(agent: &QLearningAgent) -> Result<()> {
    if agent.state_size == 0 || agent.action_size == 0 {
        return Err(crate::safety::arg_err(
            "Q-learning dimensions must be positive",
        ));
    }
    if agent.action_size > 10000
        || agent
            .state_size
            .checked_mul(agent.action_size)
            .is_none_or(|n| n > MAX_RL_CELLS)
        || agent.q_table.len() > MAX_RL_CELLS
    {
        return Err(crate::safety::budget_exceeded(
            "rl",
            "Q-learning exceeds 10000 actions or one million state-action cells".into(),
            "use a smaller state/action space",
        ));
    }
    if [
        agent.learning_rate,
        agent.discount,
        agent.epsilon,
        agent.epsilon_decay,
        agent.epsilon_min,
    ]
    .iter()
    .any(|n| !n.is_finite() || !(0.0..=1.0).contains(n))
        || i64::try_from(agent.steps).is_err()
    {
        return Err(crate::safety::arg_err(
            "Q-learning rates must be finite probabilities and steps must fit Int",
        ));
    }
    if agent.q_table.iter().any(|(&(state, action), q)| {
        state >= agent.state_size || action >= agent.action_size || !q.is_finite()
    }) {
        return Err(crate::safety::arg_err(
            "Q-learning table indices must be in range and values finite",
        ));
    }
    Ok(())
}

fn validate_sarsa_agent(agent: &SarsaAgent) -> Result<()> {
    if agent.state_size == 0 || agent.action_size == 0 {
        return Err(crate::safety::arg_err("SARSA dimensions must be positive"));
    }
    if agent.action_size > 10000
        || agent
            .state_size
            .checked_mul(agent.action_size)
            .is_none_or(|n| n > MAX_RL_CELLS)
        || agent.q_table.len() > MAX_RL_CELLS
    {
        return Err(crate::safety::budget_exceeded(
            "rl",
            "SARSA exceeds 10000 actions or one million state-action cells".into(),
            "use a smaller state/action space",
        ));
    }
    if [agent.learning_rate, agent.discount, agent.epsilon]
        .iter()
        .any(|n| !n.is_finite() || !(0.0..=1.0).contains(n))
        || i64::try_from(agent.steps).is_err()
    {
        return Err(crate::safety::arg_err(
            "SARSA rates must be finite probabilities and steps must fit Int",
        ));
    }
    if agent.q_table.iter().any(|(&(state, action), q)| {
        state >= agent.state_size || action >= agent.action_size || !q.is_finite()
    }) {
        return Err(crate::safety::arg_err(
            "SARSA table indices must be in range and values finite",
        ));
    }
    Ok(())
}

fn rl_index(name: &str, value: &Value, limit: usize) -> Result<usize> {
    match value {
        Value::Int(n) => usize::try_from(*n)
            .ok()
            .filter(|n| *n < limit)
            .ok_or_else(|| crate::safety::arg_err(format!("{name}: index must be in 0..{limit}"))),
        other => Err(crate::safety::bad_arg(
            name,
            "index: Int",
            other.type_name(),
        )),
    }
}

fn bi_rl_agent(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = expect_string(
        "rl_agent",
        args.first()
            .ok_or_else(|| crate::safety::arg_err("rl_agent requires name"))?,
    )?;
    let states = rl_positive_size(
        "rl_agent",
        args.get(1)
            .ok_or_else(|| crate::safety::arg_err("rl_agent requires state_size"))?,
    )?;
    let actions = rl_positive_size(
        "rl_agent",
        args.get(2)
            .ok_or_else(|| crate::safety::arg_err("rl_agent requires action_size"))?,
    )?;
    let mut agent = QLearningAgent::new(name, states, actions, 0.1, 0.99, 0.1);
    if let Some(value) = args.get(3) {
        let Value::Record(options) = value else {
            return Err(crate::safety::bad_arg(
                "rl_agent",
                "config: Record",
                value.type_name(),
            ));
        };
        for (key, value) in options {
            let number = finite_nn_number("rl_agent", value)?;
            match key.as_str() {
                "learning_rate" => agent.learning_rate = number,
                "discount" => agent.discount = number,
                "epsilon" => agent.epsilon = number,
                _ => {
                    return Err(crate::safety::arg_err(format!(
                        "rl_agent: unknown option {key}"
                    )))
                }
            }
        }
    }
    validate_q_agent(&agent)?;
    q_agent_to_value(&agent)
}

fn bi_rl_action(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("rl_action requires agent"))?;
    let agent = value_to_q_agent(&value)?;
    let idx = usize::from(!piped);
    let state = rl_index(
        "rl_action state",
        args.get(idx)
            .ok_or_else(|| crate::safety::arg_err("rl_action requires state"))?,
        agent.state_size,
    )?;
    Ok(Value::Int(agent.select_action(state) as i64))
}

fn bi_rl_update(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("rl_update requires agent"))?;
    let mut agent = value_to_q_agent(&value)?;
    let idx = usize::from(!piped);
    let arg = |offset| {
        args.get(idx + offset).ok_or_else(|| {
            crate::safety::arg_err("rl_update requires state, action, reward, next_state, done")
        })
    };
    let state = rl_index("rl_update state", arg(0)?, agent.state_size)?;
    let action = rl_index("rl_update action", arg(1)?, agent.action_size)?;
    let reward = finite_nn_number("rl_update reward", arg(2)?)?;
    let next_state = rl_index("rl_update next_state", arg(3)?, agent.state_size)?;
    let Value::Bool(done) = arg(4)? else {
        return Err(crate::safety::arg_err("rl_update done must be Bool"));
    };
    if agent
        .steps
        .checked_add(1)
        .is_none_or(|n| i64::try_from(n).is_err())
    {
        return Err(crate::safety::arg_err("rl_update step counter overflow"));
    }
    agent.update(state, action, reward, next_state, *done);
    validate_q_agent(&agent).map_err(|_| {
        crate::safety::bad_state_with_hint(
            "rl_update",
            "non-finite Q-learning result",
            "the update exceeded the numeric range",
        )
    })?;
    q_agent_to_value(&agent)
}

/// Create a SARSA agent with fixed default rates.
fn bi_rl_sarsa_agent(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = expect_string(
        "rl_sarsa_agent",
        args.first()
            .ok_or_else(|| crate::safety::arg_err("rl_sarsa_agent requires name"))?,
    )?;
    let states = rl_positive_size(
        "rl_sarsa_agent",
        args.get(1)
            .ok_or_else(|| crate::safety::arg_err("rl_sarsa_agent requires state_size"))?,
    )?;
    let actions = rl_positive_size(
        "rl_sarsa_agent",
        args.get(2)
            .ok_or_else(|| crate::safety::arg_err("rl_sarsa_agent requires action_size"))?,
    )?;
    sarsa_agent_to_value(&SarsaAgent::new(&name, states, actions, 0.1, 0.99, 0.1))
}

/// Update a validated SARSA agent copy using the supplied next action.
fn bi_rl_sarsa_update(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("rl_sarsa_update requires agent"))?;
    let mut agent = value_to_sarsa_agent(&value)?;
    let idx = usize::from(!piped);
    let arg = |offset| {
        args.get(idx + offset).ok_or_else(|| {
            crate::safety::arg_err(
                "rl_sarsa_update requires state, action, reward, next_state, next_action, done",
            )
        })
    };
    let state = rl_index("rl_sarsa_update state", arg(0)?, agent.state_size)?;
    let action = rl_index("rl_sarsa_update action", arg(1)?, agent.action_size)?;
    let reward = finite_nn_number("rl_sarsa_update reward", arg(2)?)?;
    let next_state = rl_index("rl_sarsa_update next_state", arg(3)?, agent.state_size)?;
    let next_action = rl_index("rl_sarsa_update next_action", arg(4)?, agent.action_size)?;
    let Value::Bool(done) = arg(5)? else {
        return Err(crate::safety::arg_err("rl_sarsa_update done must be Bool"));
    };
    if agent
        .steps
        .checked_add(1)
        .is_none_or(|n| i64::try_from(n).is_err())
    {
        return Err(crate::safety::arg_err(
            "rl_sarsa_update step counter overflow",
        ));
    }
    agent.update(state, action, reward, next_state, next_action, *done);
    validate_sarsa_agent(&agent).map_err(|_| {
        crate::safety::bad_state_with_hint(
            "rl_sarsa_update",
            "non-finite SARSA result",
            "the update exceeded the numeric range",
        )
    })?;
    sarsa_agent_to_value(&agent)
}

fn pg_dimensions(state_dim: usize, action_size: usize) -> Result<usize> {
    if state_dim == 0 || action_size == 0 {
        return Err(crate::safety::arg_err(
            "policy-gradient dimensions must be positive",
        ));
    }
    state_dim
        .checked_mul(action_size)
        .filter(|n| *n <= MAX_RL_CELLS && action_size <= 10000)
        .ok_or_else(|| {
            crate::safety::budget_exceeded(
                "rl_pg",
                "policy exceeds 10000 actions or one million weights".into(),
                "use a smaller policy",
            )
        })
}

fn pg_history_budget(state_dim: usize, steps: usize) -> Result<()> {
    if steps > 10000
        || state_dim
            .checked_mul(steps)
            .is_none_or(|n| n > MAX_RL_CELLS)
    {
        return Err(crate::safety::budget_exceeded(
            "rl_pg",
            "episode exceeds 10000 steps or one million stored state values".into(),
            "finish a shorter episode",
        ));
    }
    Ok(())
}

fn validate_pg_agent(agent: &PolicyGradientAgent) -> Result<()> {
    pg_dimensions(agent.state_dim, agent.action_size)?;
    pg_history_budget(agent.state_dim, agent.episode_states.len())?;
    if agent.weights.len() != agent.action_size
        || agent
            .weights
            .iter()
            .any(|row| row.len() != agent.state_dim || row.iter().any(|v| !v.is_finite()))
    {
        return Err(crate::safety::arg_err(
            "policy weights must match dimensions and be finite",
        ));
    }
    if [agent.learning_rate, agent.discount]
        .iter()
        .any(|v| !v.is_finite() || !(0.0..=1.0).contains(v))
        || i64::try_from(agent.episodes).is_err()
    {
        return Err(crate::safety::arg_err(
            "policy rates must be finite probabilities and episodes must fit Int",
        ));
    }
    if agent.episode_actions.len() != agent.episode_states.len()
        || agent.episode_rewards.len() != agent.episode_states.len()
        || agent
            .episode_states
            .iter()
            .any(|row| row.len() != agent.state_dim || row.iter().any(|v| !v.is_finite()))
        || agent
            .episode_actions
            .iter()
            .any(|a| *a >= agent.action_size)
        || agent.episode_rewards.iter().any(|v| !v.is_finite())
    {
        return Err(crate::safety::arg_err("episode states, actions and rewards must have equal lengths, valid shapes/indices and finite values"));
    }
    Ok(())
}

/// Create a linear softmax policy with fixed default rates.
fn bi_rl_pg_agent(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = expect_string(
        "rl_pg_agent",
        args.first()
            .ok_or_else(|| crate::safety::arg_err("rl_pg_agent requires name"))?,
    )?;
    let state_dim = rl_positive_size(
        "rl_pg_agent",
        args.get(1)
            .ok_or_else(|| crate::safety::arg_err("rl_pg_agent requires state_dim"))?,
    )?;
    let action_size = rl_positive_size(
        "rl_pg_agent",
        args.get(2)
            .ok_or_else(|| crate::safety::arg_err("rl_pg_agent requires action_size"))?,
    )?;
    pg_dimensions(state_dim, action_size)?;
    pg_agent_to_value(&PolicyGradientAgent::new(
        &name,
        state_dim,
        action_size,
        0.01,
        0.99,
    ))
}

/// Append a validated step without updating policy weights.
fn bi_rl_pg_step(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("rl_pg_step requires agent"))?;
    let mut agent = value_to_pg_agent(&value)?;
    let idx = usize::from(!piped);
    let arg = |offset| {
        args.get(idx + offset)
            .ok_or_else(|| crate::safety::arg_err("rl_pg_step requires state, action, reward"))
    };
    let Value::Array(values) = arg(0)? else {
        return Err(crate::safety::arg_err("rl_pg_step state must be Array"));
    };
    if values.len() != agent.state_dim {
        return Err(crate::safety::arg_err(
            "rl_pg_step state must match state_dim",
        ));
    }
    pg_history_budget(agent.state_dim, agent.episode_states.len() + 1)?;
    let state = values
        .iter()
        .map(|v| finite_nn_number("rl_pg_step state", v))
        .collect::<Result<Vec<_>>>()?;
    let action = rl_index("rl_pg_step action", arg(1)?, agent.action_size)?;
    let reward = finite_nn_number("rl_pg_step reward", arg(2)?)?;
    agent.record_step(state, action, reward);
    pg_agent_to_value(&agent)
}

/// Finish a nonempty episode using REINFORCE, preserving empty episodes.
fn bi_rl_pg_episode_end(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("rl_pg_episode_end requires agent"))?;
    let mut agent = value_to_pg_agent(&value)?;
    if !agent.episode_states.is_empty() {
        if agent
            .episodes
            .checked_add(1)
            .is_none_or(|n| i64::try_from(n).is_err())
        {
            return Err(crate::safety::arg_err(
                "rl_pg_episode_end episode counter overflow",
            ));
        }
        let weights = pg_dimensions(agent.state_dim, agent.action_size)?;
        if weights
            .checked_mul(agent.episode_states.len())
            .is_none_or(|n| n > 10_000_000)
        {
            return Err(crate::safety::budget_exceeded(
                "rl_pg_episode_end",
                "episode exceeds ten million weight-step pairs".into(),
                "use a smaller policy or shorter episode",
            ));
        }
        agent.end_episode();
        validate_pg_agent(&agent).map_err(|_| {
            crate::safety::bad_state_with_hint(
                "rl_pg_episode_end",
                "non-finite policy-gradient result",
                "the update exceeded the numeric range",
            )
        })?;
    }
    pg_agent_to_value(&agent)
}

fn ac_dimensions(state_dim: usize, actions: usize) -> Result<()> {
    pg_dimensions(state_dim, actions)?;
    if actions
        .checked_add(1)
        .and_then(|n| n.checked_mul(state_dim))
        .is_none_or(|n| n > MAX_RL_CELLS)
    {
        return Err(crate::safety::budget_exceeded(
            "rl_ac",
            "actor and critic exceed one million weights".into(),
            "use a smaller agent",
        ));
    }
    Ok(())
}
fn validate_ac_agent(agent: &ActorCriticAgent) -> Result<()> {
    ac_dimensions(agent.state_dim, agent.action_size)?;
    if agent.actor_weights.len() != agent.action_size
        || agent
            .actor_weights
            .iter()
            .any(|row| row.len() != agent.state_dim || row.iter().any(|n| !n.is_finite()))
        || agent.critic_weights.len() != agent.state_dim
        || agent.critic_weights.iter().any(|n| !n.is_finite())
    {
        return Err(crate::safety::arg_err(
            "actor/critic weights must match dimensions and be finite",
        ));
    }
    if [agent.actor_lr, agent.critic_lr, agent.discount]
        .iter()
        .any(|n| !n.is_finite() || !(0.0..=1.0).contains(n))
        || i64::try_from(agent.steps).is_err()
    {
        return Err(crate::safety::arg_err(
            "actor/critic rates must be finite probabilities and steps must fit Int",
        ));
    }
    Ok(())
}
fn ac_state(value: &Value, width: usize) -> Result<Vec<f64>> {
    let Value::Array(values) = value else {
        return Err(crate::safety::arg_err("actor/critic state must be Array"));
    };
    if values.len() != width {
        return Err(crate::safety::arg_err(
            "actor/critic state must match state_dim",
        ));
    }
    values
        .iter()
        .map(|v| finite_nn_number("rl_ac_update state", v))
        .collect()
}
/// Create a bounded linear actor and critic with fixed rates.
fn bi_rl_ac_agent(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = expect_string(
        "rl_ac_agent",
        args.first()
            .ok_or_else(|| crate::safety::arg_err("rl_ac_agent requires name"))?,
    )?;
    let states = rl_positive_size(
        "rl_ac_agent",
        args.get(1)
            .ok_or_else(|| crate::safety::arg_err("rl_ac_agent requires state_dim"))?,
    )?;
    let actions = rl_positive_size(
        "rl_ac_agent",
        args.get(2)
            .ok_or_else(|| crate::safety::arg_err("rl_ac_agent requires action_size"))?,
    )?;
    ac_dimensions(states, actions)?;
    ac_agent_to_value(&ActorCriticAgent::new(
        &name, states, actions, 0.01, 0.01, 0.99,
    ))
}
/// Update a validated copy of an actor-critic agent.
fn bi_rl_ac_update(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("rl_ac_update requires agent"))?;
    let mut agent = value_to_ac_agent(&value)?;
    let idx = usize::from(!piped);
    let arg = |offset| {
        args.get(idx + offset).ok_or_else(|| {
            crate::safety::arg_err("rl_ac_update requires state, action, reward, next_state, done")
        })
    };
    let state = ac_state(arg(0)?, agent.state_dim)?;
    let action = rl_index("rl_ac_update action", arg(1)?, agent.action_size)?;
    let reward = finite_nn_number("rl_ac_update reward", arg(2)?)?;
    let next = ac_state(arg(3)?, agent.state_dim)?;
    let Value::Bool(done) = arg(4)? else {
        return Err(crate::safety::arg_err("rl_ac_update done must be Bool"));
    };
    if agent
        .steps
        .checked_add(1)
        .is_none_or(|n| i64::try_from(n).is_err())
    {
        return Err(crate::safety::arg_err("rl_ac_update step counter overflow"));
    }
    agent.update(&state, action, reward, &next, *done);
    validate_ac_agent(&agent).map_err(|_| {
        crate::safety::bad_state_with_hint(
            "rl_ac_update",
            "non-finite actor-critic result",
            "the update exceeded the numeric range",
        )
    })?;
    ac_agent_to_value(&agent)
}

fn validate_dqn_agent(agent: &DQNAgent) -> Result<()> {
    if agent.state_dim == 0 || agent.action_size == 0 {
        return Err(crate::safety::arg_err("DQN dimensions must be positive"));
    }
    if agent.action_size > 10000
        || agent.network.layers.len() > 127
        || agent.target_network.layers.len() > 127
    {
        return Err(crate::safety::budget_exceeded(
            "rl_dqn",
            "DQN exceeds 10000 actions or 127 dense layers".into(),
            "use a smaller network",
        ));
    }
    let mut total = 0;
    for net in [&agent.network, &agent.target_network] {
        validate_nn(net)?;
        if net
            .layers
            .first()
            .is_none_or(|l| l.input_size != agent.state_dim)
            || net
                .layers
                .last()
                .is_none_or(|l| l.output_size != agent.action_size)
        {
            return Err(crate::safety::arg_err(
                "DQN network endpoints must match state/action dimensions",
            ));
        }
        for layer in &net.layers {
            total = checked_nn_parameter_count(total, layer.input_size, layer.output_size)?;
        }
    }
    if agent.network.layers.len() != agent.target_network.layers.len()
        || agent
            .network
            .layers
            .iter()
            .zip(&agent.target_network.layers)
            .any(|(a, b)| (a.input_size, a.output_size) != (b.input_size, b.output_size))
    {
        return Err(crate::safety::arg_err(
            "DQN policy and target architectures must match",
        ));
    }
    if [
        agent.learning_rate,
        agent.discount,
        agent.epsilon,
        agent.epsilon_decay,
        agent.epsilon_min,
    ]
    .iter()
    .any(|n| !n.is_finite() || !(0.0..=1.0).contains(n))
        || i64::try_from(agent.steps).is_err()
        || agent.batch_size == 0
        || agent.batch_size > 10000
        || agent.target_update_freq == 0
    {
        return Err(crate::safety::arg_err("DQN requires finite probability rates, a representable step count, batch size in 1..=10000 and positive target frequency"));
    }
    let replay = &agent.replay_buffer;
    if replay.capacity == 0
        || replay.buffer.len() > replay.capacity
        || replay.position >= replay.capacity
        || (replay.buffer.len() < replay.capacity && replay.position != replay.buffer.len())
    {
        return Err(crate::safety::arg_err(
            "DQN replay capacity, length and circular position are inconsistent",
        ));
    }
    if replay.capacity > 10000
        || replay
            .buffer
            .len()
            .checked_mul(agent.state_dim)
            .and_then(|n| n.checked_mul(2))
            .is_none_or(|n| n > MAX_RL_CELLS)
    {
        return Err(crate::safety::budget_exceeded(
            "rl_dqn",
            "replay exceeds 10000 capacity or one million state values".into(),
            "use a smaller replay buffer",
        ));
    }
    if replay.buffer.iter().any(|exp| {
        exp.state.len() != agent.state_dim
            || exp.next_state.len() != agent.state_dim
            || exp
                .state
                .iter()
                .chain(&exp.next_state)
                .any(|n| !n.is_finite())
            || exp.action >= agent.action_size
            || !exp.reward.is_finite()
    }) {
        return Err(crate::safety::arg_err(
            "DQN experiences require exact finite state widths, valid actions and finite rewards",
        ));
    }
    Ok(())
}

/// Create bounded policy and target networks with fixed DQN defaults.
fn bi_rl_dqn_agent(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = expect_string(
        "rl_dqn_agent",
        args.first()
            .ok_or_else(|| crate::safety::arg_err("rl_dqn_agent requires name"))?,
    )?;
    let states = rl_positive_size(
        "rl_dqn_agent",
        args.get(1)
            .ok_or_else(|| crate::safety::arg_err("rl_dqn_agent requires state_dim"))?,
    )?;
    let actions = rl_positive_size(
        "rl_dqn_agent",
        args.get(2)
            .ok_or_else(|| crate::safety::arg_err("rl_dqn_agent requires action_size"))?,
    )?;
    if actions > 10000 {
        return Err(crate::safety::budget_exceeded(
            "rl_dqn_agent",
            "DQN exceeds 10000 actions".into(),
            "use fewer actions",
        ));
    }
    let hidden = match args.get(3) {
        None => vec![64, 64],
        Some(Value::Array(values)) if values.len() <= 126 => values
            .iter()
            .map(|v| rl_positive_size("rl_dqn_agent hidden size", v))
            .collect::<Result<Vec<_>>>()?,
        Some(Value::Array(_)) => {
            return Err(crate::safety::budget_exceeded(
                "rl_dqn_agent",
                "DQN exceeds 126 hidden layers".into(),
                "use fewer layers",
            ))
        }
        Some(_) => return Err(crate::safety::arg_err("DQN hidden_sizes must be Array")),
    };
    let sizes: Vec<_> = std::iter::once(states)
        .chain(hidden.iter().copied())
        .chain(std::iter::once(actions))
        .collect();
    let mut total = 0;
    for _ in 0..2 {
        for pair in sizes.windows(2) {
            total = checked_nn_parameter_count(total, pair[0], pair[1])?;
        }
    }
    dqn_agent_to_value(&DQNAgent::new(
        &name, states, actions, &hidden, 0.001, 0.99, 1.0, 10000,
    ))
}

/// Record experience; refuse the unimplemented training path before mutation.
fn bi_rl_dqn_step(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("rl_dqn_step requires agent"))?;
    let mut agent = value_to_dqn_agent(&value)?;
    let idx = usize::from(!piped);
    let arg = |offset| {
        args.get(idx + offset).ok_or_else(|| {
            crate::safety::arg_err("rl_dqn_step requires state, action, reward, next_state, done")
        })
    };
    let state = ac_state(arg(0)?, agent.state_dim)?;
    let action = rl_index("rl_dqn_step action", arg(1)?, agent.action_size)?;
    let reward = finite_nn_number("rl_dqn_step reward", arg(2)?)?;
    let next = ac_state(arg(3)?, agent.state_dim)?;
    let Value::Bool(done) = arg(4)? else {
        return Err(crate::safety::arg_err("rl_dqn_step done must be Bool"));
    };
    if agent
        .steps
        .checked_add(1)
        .is_none_or(|n| i64::try_from(n).is_err())
    {
        return Err(crate::safety::arg_err("rl_dqn_step counter overflow"));
    }
    let next_len = (agent.replay_buffer.len() + 1).min(agent.replay_buffer.capacity);
    if next_len
        .checked_mul(agent.state_dim)
        .and_then(|n| n.checked_mul(2))
        .is_none_or(|n| n > MAX_RL_CELLS)
    {
        return Err(crate::safety::budget_exceeded(
            "rl_dqn_step",
            "replay exceeds one million state values".into(),
            "use a smaller buffer or state",
        ));
    }
    if next_len >= agent.batch_size
        && (agent.network.param_count() + agent.target_network.param_count())
            .checked_mul(agent.batch_size)
            .and_then(|work| work.checked_mul(4))
            .is_none_or(|work| work > 20_000_000)
    {
        return Err(crate::safety::budget_exceeded(
            "rl_dqn_step",
            "training exceeds twenty million estimated dense operations".into(),
            "use a smaller network or batch size",
        ));
    }
    agent
        .step(state, action, reward, next, *done)
        .map_err(|reason| {
            crate::safety::bad_state_with_hint(
                "rl_dqn_step",
                reason,
                "finite training arithmetic; use smaller values or learning rate",
            )
        })?;
    dqn_agent_to_value(&agent)
}

/// Create an empty bounded replay buffer.
fn bi_rl_replay_buffer(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let capacity = match args.first() {
        None => 10000,
        Some(value) => rl_positive_size("rl_replay_buffer", value)?,
    };
    if capacity > 10000 {
        return Err(crate::safety::budget_exceeded(
            "rl_replay_buffer",
            "replay capacity exceeds 10000".into(),
            "use a smaller capacity",
        ));
    }
    replay_buffer_to_value(&ReplayBuffer::new(capacity))
}

fn grid_dimensions(width: usize, height: usize) -> Result<usize> {
    if width == 0 || height == 0 {
        return Err(crate::safety::arg_err(
            "gridworld dimensions must be positive",
        ));
    }
    width
        .checked_mul(height)
        .filter(|n| *n <= MAX_RL_CELLS)
        .ok_or_else(|| {
            crate::safety::budget_exceeded(
                "rl_gridworld",
                "gridworld exceeds one million cells".into(),
                "use smaller dimensions",
            )
        })
}

fn validate_gridworld(env: &GridWorld) -> Result<()> {
    grid_dimensions(env.width, env.height)?;
    if env.agent_pos.0 >= env.width
        || env.agent_pos.1 >= env.height
        || env.goal_pos.0 >= env.width
        || env.goal_pos.1 >= env.height
        || env
            .obstacles
            .iter()
            .any(|&(x, y)| x >= env.width || y >= env.height)
    {
        return Err(crate::safety::arg_err(
            "gridworld positions must be within dimensions",
        ));
    }
    if env.obstacles.len() > 10000 {
        return Err(crate::safety::budget_exceeded(
            "rl_gridworld",
            "gridworld exceeds 10000 obstacle entries".into(),
            "use fewer obstacles",
        ));
    }
    Ok(())
}

/// Create a positive bounded gridworld.
fn bi_rl_gridworld(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let width = match args.first() {
        None => 5,
        Some(value) => rl_positive_size("rl_gridworld width", value)?,
    };
    let height = match args.get(1) {
        None => width,
        Some(value) => rl_positive_size("rl_gridworld height", value)?,
    };
    grid_dimensions(width, height)?;
    gridworld_to_value(&GridWorld::new(width, height))
}

/// Move a validated gridworld copy by one clamped cardinal step.
fn bi_rl_env_step(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let piped = input.is_some();
    let value = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("rl_env_step requires environment"))?;
    let mut env = value_to_gridworld(&value)?;
    let action = rl_index(
        "rl_env_step action",
        args.get(usize::from(!piped))
            .ok_or_else(|| crate::safety::arg_err("rl_env_step requires action"))?,
        4,
    )?;
    let (state, reward, done) = env.step(action);
    Ok(Value::Record(BTreeMap::from([
        ("state".into(), Value::Int(state as i64)),
        ("reward".into(), Value::Float(reward)),
        ("done".into(), Value::Bool(done)),
        ("env".into(), gridworld_to_value(&env)?),
    ])))
}

// ==================== RL Helper Functions ====================

fn q_agent_to_value(agent: &QLearningAgent) -> Result<Value> {
    validate_q_agent(agent)?;
    let mut rows: Vec<_> = agent
        .q_table
        .iter()
        .map(|(&(state, action), &q)| (state, action, q))
        .collect();
    rows.sort_by_key(|&(state, action, _)| (state, action));
    let json = serde_json::json!({
        "name": agent.name, "state_size": agent.state_size, "action_size": agent.action_size,
        "learning_rate": agent.learning_rate, "discount": agent.discount, "epsilon": agent.epsilon,
        "epsilon_decay": agent.epsilon_decay, "epsilon_min": agent.epsilon_min, "steps": agent.steps,
        "q_table": rows,
    }).to_string();

    let mut rec = BTreeMap::new();
    rec.insert(
        "type".to_string(),
        Value::Str("q_learning_agent".to_string()),
    );
    rec.insert("name".to_string(), Value::Str(agent.name.clone()));
    rec.insert(
        "state_size".to_string(),
        Value::Int(agent.state_size as i64),
    );
    rec.insert(
        "action_size".to_string(),
        Value::Int(agent.action_size as i64),
    );
    rec.insert("epsilon".to_string(), Value::Float(agent.epsilon));
    rec.insert("steps".to_string(), Value::Int(agent.steps as i64));
    rec.insert("_data".to_string(), Value::Str(json));

    Ok(Value::Record(rec))
}

fn value_to_q_agent(value: &Value) -> Result<QLearningAgent> {
    let Value::Record(record) = value else {
        return Err(crate::safety::arg_err("Q-learning agent must be a Record"));
    };
    let Some(Value::Str(data)) = record.get("_data") else {
        return Err(crate::safety::arg_err(
            "Q-learning agent requires _data: String",
        ));
    };
    if data.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "rl",
            "Q-learning encoding exceeds 64 MiB".into(),
            "use a smaller agent",
        ));
    }
    let mut wire: serde_json::Value = serde_json::from_str(data).map_err(|e| {
        crate::safety::bad_arg("rl", "valid encoded Q-learning agent", &e.to_string())
    })?;
    let rows = match wire.get_mut("q_table") {
        Some(value @ serde_json::Value::Array(_)) => {
            std::mem::replace(value, serde_json::json!({}))
        }
        Some(serde_json::Value::Object(table)) if table.is_empty() => serde_json::json!([]),
        _ => {
            return Err(crate::safety::arg_err(
                "Q-learning q_table must contain row triples or a legacy empty object",
            ))
        }
    };
    let mut agent: QLearningAgent = serde_json::from_value(wire).map_err(|e| {
        crate::safety::bad_arg("rl", "valid encoded Q-learning agent", &e.to_string())
    })?;
    validate_q_agent(&agent)?;
    let rows = rows.as_array().expect("row representation was checked");
    if rows.len() > MAX_RL_CELLS {
        return Err(crate::safety::budget_exceeded(
            "rl",
            "Q-learning table exceeds one million entries".into(),
            "use a smaller agent",
        ));
    }
    for row in rows {
        let Some(row) = row.as_array().filter(|row| row.len() == 3) else {
            return Err(crate::safety::arg_err(
                "Q-learning rows must be [state, action, finite value]",
            ));
        };
        let index = |value: &serde_json::Value, limit| {
            value
                .as_u64()
                .and_then(|n| usize::try_from(n).ok())
                .filter(|n| *n < limit)
                .ok_or_else(|| {
                    crate::safety::arg_err("Q-learning row indices must be in-range integers")
                })
        };
        let state = index(&row[0], agent.state_size)?;
        let action = index(&row[1], agent.action_size)?;
        let q = row[2].as_f64().filter(|n| n.is_finite()).ok_or_else(|| {
            crate::safety::arg_err("Q-learning row values must be finite numbers")
        })?;
        if agent.q_table.insert((state, action), q).is_some() {
            return Err(crate::safety::arg_err(
                "Q-learning rows contain duplicate state-action pairs",
            ));
        }
    }
    Ok(agent)
}

fn sarsa_agent_to_value(agent: &SarsaAgent) -> Result<Value> {
    validate_sarsa_agent(agent)?;
    let mut rows: Vec<_> = agent
        .q_table
        .iter()
        .map(|(&(state, action), &q)| (state, action, q))
        .collect();
    rows.sort_by_key(|&(state, action, _)| (state, action));
    let json = serde_json::json!({
        "name": agent.name, "state_size": agent.state_size, "action_size": agent.action_size,
        "learning_rate": agent.learning_rate, "discount": agent.discount, "epsilon": agent.epsilon,
        "steps": agent.steps,
        "q_table": rows,
    })
    .to_string();

    let mut rec = BTreeMap::new();
    rec.insert("type".to_string(), Value::Str("sarsa_agent".to_string()));
    rec.insert("name".to_string(), Value::Str(agent.name.clone()));
    rec.insert(
        "state_size".to_string(),
        Value::Int(agent.state_size as i64),
    );
    rec.insert(
        "action_size".to_string(),
        Value::Int(agent.action_size as i64),
    );
    rec.insert("epsilon".to_string(), Value::Float(agent.epsilon));
    rec.insert("steps".to_string(), Value::Int(agent.steps as i64));
    rec.insert("_data".to_string(), Value::Str(json));

    Ok(Value::Record(rec))
}

fn value_to_sarsa_agent(value: &Value) -> Result<SarsaAgent> {
    let Value::Record(record) = value else {
        return Err(crate::safety::arg_err("SARSA agent must be a Record"));
    };
    let Some(Value::Str(data)) = record.get("_data") else {
        return Err(crate::safety::arg_err("SARSA agent requires _data: String"));
    };
    if data.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "rl",
            "SARSA encoding exceeds 64 MiB".into(),
            "use a smaller agent",
        ));
    }
    let mut wire: serde_json::Value = serde_json::from_str(data)
        .map_err(|e| crate::safety::bad_arg("rl", "valid encoded SARSA agent", &e.to_string()))?;
    let rows = match wire.get_mut("q_table") {
        Some(value @ serde_json::Value::Array(_)) => {
            std::mem::replace(value, serde_json::json!({}))
        }
        Some(serde_json::Value::Object(table)) if table.is_empty() => serde_json::json!([]),
        _ => {
            return Err(crate::safety::arg_err(
                "SARSA q_table must contain row triples or a legacy empty object",
            ))
        }
    };
    let mut agent: SarsaAgent = serde_json::from_value(wire)
        .map_err(|e| crate::safety::bad_arg("rl", "valid encoded SARSA agent", &e.to_string()))?;
    validate_sarsa_agent(&agent)?;
    let rows = rows.as_array().expect("row representation was checked");
    if rows.len() > MAX_RL_CELLS {
        return Err(crate::safety::budget_exceeded(
            "rl",
            "SARSA table exceeds one million entries".into(),
            "use a smaller agent",
        ));
    }
    for row in rows {
        let Some(row) = row.as_array().filter(|row| row.len() == 3) else {
            return Err(crate::safety::arg_err(
                "SARSA rows must be [state, action, finite value]",
            ));
        };
        let index = |value: &serde_json::Value, limit| {
            value
                .as_u64()
                .and_then(|n| usize::try_from(n).ok())
                .filter(|n| *n < limit)
                .ok_or_else(|| {
                    crate::safety::arg_err("SARSA row indices must be in-range integers")
                })
        };
        let state = index(&row[0], agent.state_size)?;
        let action = index(&row[1], agent.action_size)?;
        let q = row[2]
            .as_f64()
            .filter(|n| n.is_finite())
            .ok_or_else(|| crate::safety::arg_err("SARSA row values must be finite numbers"))?;
        if agent.q_table.insert((state, action), q).is_some() {
            return Err(crate::safety::arg_err(
                "SARSA rows contain duplicate state-action pairs",
            ));
        }
    }
    Ok(agent)
}

fn pg_agent_to_value(agent: &PolicyGradientAgent) -> Result<Value> {
    validate_pg_agent(agent)?;
    let json = serde_json::to_string(agent).context("Failed to serialize PG agent")?;
    if json.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "rl_pg",
            "policy encoding exceeds 64 MiB".into(),
            "use a smaller agent",
        ));
    }

    let mut rec = BTreeMap::new();
    rec.insert(
        "type".to_string(),
        Value::Str("policy_gradient_agent".to_string()),
    );
    rec.insert("name".to_string(), Value::Str(agent.name.clone()));
    rec.insert("state_dim".to_string(), Value::Int(agent.state_dim as i64));
    rec.insert(
        "action_size".to_string(),
        Value::Int(agent.action_size as i64),
    );
    rec.insert("episodes".to_string(), Value::Int(agent.episodes as i64));
    rec.insert("_data".to_string(), Value::Str(json));

    Ok(Value::Record(rec))
}

fn value_to_pg_agent(value: &Value) -> Result<PolicyGradientAgent> {
    let Value::Record(record) = value else {
        return Err(crate::safety::arg_err(
            "policy-gradient agent must be Record",
        ));
    };
    let Some(Value::Str(data)) = record.get("_data") else {
        return Err(crate::safety::arg_err(
            "policy-gradient agent requires _data: String",
        ));
    };
    if data.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "rl_pg",
            "policy encoding exceeds 64 MiB".into(),
            "use a smaller agent",
        ));
    }
    let agent: PolicyGradientAgent = serde_json::from_str(data).map_err(|e| {
        crate::safety::bad_arg(
            "rl_pg",
            "valid encoded policy-gradient agent",
            &e.to_string(),
        )
    })?;
    validate_pg_agent(&agent)?;
    Ok(agent)
}

fn ac_agent_to_value(agent: &ActorCriticAgent) -> Result<Value> {
    validate_ac_agent(agent)?;
    let json = serde_json::to_string(agent).context("Failed to serialize AC agent")?;
    if json.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "rl_ac",
            "actor-critic encoding exceeds 64 MiB".into(),
            "use a smaller agent",
        ));
    }

    let mut rec = BTreeMap::new();
    rec.insert(
        "type".to_string(),
        Value::Str("actor_critic_agent".to_string()),
    );
    rec.insert("name".to_string(), Value::Str(agent.name.clone()));
    rec.insert("state_dim".to_string(), Value::Int(agent.state_dim as i64));
    rec.insert(
        "action_size".to_string(),
        Value::Int(agent.action_size as i64),
    );
    rec.insert("steps".to_string(), Value::Int(agent.steps as i64));
    rec.insert("_data".to_string(), Value::Str(json));

    Ok(Value::Record(rec))
}

fn value_to_ac_agent(value: &Value) -> Result<ActorCriticAgent> {
    let Value::Record(record) = value else {
        return Err(crate::safety::arg_err("actor-critic agent must be Record"));
    };
    let Some(Value::Str(data)) = record.get("_data") else {
        return Err(crate::safety::arg_err(
            "actor-critic agent requires _data: String",
        ));
    };
    if data.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "rl_ac",
            "actor-critic encoding exceeds 64 MiB".into(),
            "use a smaller agent",
        ));
    }
    let agent: ActorCriticAgent = serde_json::from_str(data).map_err(|e| {
        crate::safety::bad_arg("rl_ac", "valid encoded actor-critic agent", &e.to_string())
    })?;
    validate_ac_agent(&agent)?;
    Ok(agent)
}

fn dqn_agent_to_value(agent: &DQNAgent) -> Result<Value> {
    validate_dqn_agent(agent)?;
    let json = serde_json::to_string(agent).context("Failed to serialize DQN agent")?;
    if json.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "rl_dqn",
            "DQN encoding exceeds 64 MiB".into(),
            "use a smaller agent",
        ));
    }

    let mut rec = BTreeMap::new();
    rec.insert("type".to_string(), Value::Str("dqn_agent".to_string()));
    rec.insert("name".to_string(), Value::Str(agent.name.clone()));
    rec.insert("state_dim".to_string(), Value::Int(agent.state_dim as i64));
    rec.insert(
        "action_size".to_string(),
        Value::Int(agent.action_size as i64),
    );
    rec.insert("epsilon".to_string(), Value::Float(agent.epsilon));
    rec.insert("steps".to_string(), Value::Int(agent.steps as i64));
    rec.insert(
        "buffer_size".to_string(),
        Value::Int(agent.replay_buffer.len() as i64),
    );
    rec.insert("_data".to_string(), Value::Str(json));

    Ok(Value::Record(rec))
}

fn value_to_dqn_agent(value: &Value) -> Result<DQNAgent> {
    let Value::Record(record) = value else {
        return Err(crate::safety::arg_err("DQN agent must be Record"));
    };
    let Some(Value::Str(data)) = record.get("_data") else {
        return Err(crate::safety::arg_err("DQN agent requires _data: String"));
    };
    if data.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "rl_dqn",
            "DQN encoding exceeds 64 MiB".into(),
            "use a smaller agent",
        ));
    }
    let agent: DQNAgent = serde_json::from_str(data)
        .map_err(|e| crate::safety::bad_arg("rl_dqn", "valid encoded DQN agent", &e.to_string()))?;
    validate_dqn_agent(&agent)?;
    Ok(agent)
}

fn replay_buffer_to_value(buffer: &ReplayBuffer) -> Result<Value> {
    let json = serde_json::to_string(buffer).context("Failed to serialize replay buffer")?;

    let mut rec = BTreeMap::new();
    rec.insert("type".to_string(), Value::Str("replay_buffer".to_string()));
    rec.insert("capacity".to_string(), Value::Int(buffer.capacity as i64));
    rec.insert("size".to_string(), Value::Int(buffer.len() as i64));
    rec.insert("_data".to_string(), Value::Str(json));

    Ok(Value::Record(rec))
}

fn gridworld_to_value(env: &GridWorld) -> Result<Value> {
    validate_gridworld(env)?;
    let mut rec = BTreeMap::new();
    rec.insert("type".to_string(), Value::Str("gridworld".to_string()));
    rec.insert("width".to_string(), Value::Int(env.width as i64));
    rec.insert("height".to_string(), Value::Int(env.height as i64));
    rec.insert("agent_x".to_string(), Value::Int(env.agent_pos.0 as i64));
    rec.insert("agent_y".to_string(), Value::Int(env.agent_pos.1 as i64));
    rec.insert("goal_x".to_string(), Value::Int(env.goal_pos.0 as i64));
    rec.insert("goal_y".to_string(), Value::Int(env.goal_pos.1 as i64));
    rec.insert(
        "obstacles".to_string(),
        Value::Array(
            env.obstacles
                .iter()
                .map(|&(x, y)| Value::Array(vec![Value::Int(x as i64), Value::Int(y as i64)]))
                .collect(),
        ),
    );
    rec.insert(
        "state_size".to_string(),
        Value::Int(env.state_size() as i64),
    );
    rec.insert(
        "action_size".to_string(),
        Value::Int(env.action_size() as i64),
    );

    Ok(Value::Record(rec))
}

fn value_to_gridworld(value: &Value) -> Result<GridWorld> {
    let Value::Record(record) = value else {
        return Err(crate::safety::arg_err(
            "gridworld environment must be Record",
        ));
    };
    if let Some(value) = record.get("type") {
        if !matches!(value, Value::Str(kind) if kind == "gridworld") {
            return Err(crate::safety::arg_err("gridworld type must be gridworld"));
        }
    }
    let width = rl_positive_size(
        "gridworld width",
        record
            .get("width")
            .ok_or_else(|| crate::safety::arg_err("gridworld requires width"))?,
    )?;
    let height = rl_positive_size(
        "gridworld height",
        record
            .get("height")
            .ok_or_else(|| crate::safety::arg_err("gridworld requires height"))?,
    )?;
    let cells = grid_dimensions(width, height)?;
    let position = |key: &str, default, limit| -> Result<usize> {
        match record.get(key) {
            None => Ok(default),
            Some(value) => rl_index(key, value, limit),
        }
    };
    let mut env = GridWorld::new(width, height);
    env.agent_pos = (
        position("agent_x", 0, width)?,
        position("agent_y", 0, height)?,
    );
    env.goal_pos = (
        position("goal_x", width - 1, width)?,
        position("goal_y", height - 1, height)?,
    );
    for (key, expected) in [("state_size", cells as i64), ("action_size", 4)] {
        if let Some(value) = record.get(key) {
            if !matches!(value, Value::Int(n) if *n == expected) {
                return Err(crate::safety::arg_err(format!(
                    "gridworld {key} must match dimensions"
                )));
            }
        }
    }
    if let Some(value) = record.get("obstacles") {
        let Value::Array(rows) = value else {
            return Err(crate::safety::arg_err(
                "gridworld obstacles must be Array of [x,y] pairs",
            ));
        };
        if rows.len() > 10000 {
            return Err(crate::safety::budget_exceeded(
                "rl_gridworld",
                "gridworld exceeds 10000 obstacle entries".into(),
                "use fewer obstacles",
            ));
        }
        for row in rows {
            let Value::Array(pair) = row else {
                return Err(crate::safety::arg_err(
                    "gridworld obstacles must be [x,y] pairs",
                ));
            };
            if pair.len() != 2 {
                return Err(crate::safety::arg_err(
                    "gridworld obstacles must be [x,y] pairs",
                ));
            }
            env.obstacles.push((
                rl_index("obstacle x", &pair[0], width)?,
                rl_index("obstacle y", &pair[1], height)?,
            ));
        }
    }
    validate_gridworld(&env)?;
    Ok(env)
}

// ===========================================================================
// OS Tools Builtins
// ===========================================================================

/// List all available tools or filter by category/OS
/// Usage: tools() | tools("network") | tools("linux")
fn bi_tools(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db = OSToolsDatabase::shared();

    // A filter that is not a string used to be ignored, so `tools(5)` listed
    // the whole catalogue as if no filter had been given.
    if args.len() > 1 {
        return Err(crate::safety::bad_arg(
            "tools",
            "at most one filter argument",
            &format!("{} arguments", args.len()),
        ));
    }
    let filter = match args.first() {
        None | Some(Value::Null) => None,
        Some(Value::Str(s)) => Some(s.to_lowercase()),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "tools",
                "a filter: an OS, a category, or a search string",
                other.type_name(),
            ))
        }
    };

    let tools: Vec<&crate::os_tools::OSTool> = if let Some(ref f) = filter {
        // Check if it's an OS filter
        let os_filter = match f.as_str() {
            "linux" => Some(OperatingSystem::Linux),
            "bsd" | "freebsd" | "openbsd" | "netbsd" => Some(OperatingSystem::BSD),
            "macos" | "mac" | "darwin" => Some(OperatingSystem::MacOS),
            "windows" | "win" => Some(OperatingSystem::Windows),
            "ios" | "iphone" => Some(OperatingSystem::iOS),
            "android" => Some(OperatingSystem::Android),
            _ => None,
        };

        if let Some(os) = os_filter {
            db.get_tools_by_os(&os)
        } else {
            // Check if it's a category filter
            let cat_filter = match f.as_str() {
                "filesystem" | "file" | "files" => Some(ToolCategory::FileSystem),
                "text" | "textprocessing" => Some(ToolCategory::TextProcessing),
                "network" | "net" => Some(ToolCategory::NetworkTools),
                "system" | "systeminfo" | "sysinfo" => Some(ToolCategory::SystemInfo),
                "process" | "processes" => Some(ToolCategory::ProcessManagement),
                "archive" | "archives" | "compression" => Some(ToolCategory::Archives),
                "search" => Some(ToolCategory::SearchTools),
                "monitor" | "monitoring" => Some(ToolCategory::Monitoring),
                "dev" | "development" => Some(ToolCategory::Development),
                "media" => Some(ToolCategory::Media),
                "security" | "sec" => Some(ToolCategory::Security),
                "util" | "utilities" => Some(ToolCategory::Utilities),
                "web" | "webtools" => Some(ToolCategory::WebTools),
                "cyber" | "cybersecurity" | "pentest" => Some(ToolCategory::CyberSecurity),
                "recon" | "reconnaissance" | "osint" => Some(ToolCategory::Reconnaissance),
                "forensics" | "forensic" => Some(ToolCategory::Forensics),
                "crypto" | "cryptography" => Some(ToolCategory::Cryptography),
                _ => None,
            };

            if let Some(cat) = cat_filter {
                db.get_tools_by_category(&cat)
            } else {
                // Fallback to search
                db.search_tools(f)
            }
        }
    } else {
        // Return all tools
        db.tools.values().collect()
    };

    // Sorted, because `db.tools` is a `HashMap` and Rust randomises its
    // iteration order per process: `tools()` returned the same set in a
    // different order on every call. This is the agent-facing tool catalogue,
    // the thing an agent is supposed to fetch once and cache, and it could not
    // be diffed, cached or hashed. Determinism is one of the four axes
    // `docs/TYPED_SHELL_RESPONSE.md` argues on, and E1 measured it only over
    // data queries -- never over the discovery surface itself.
    let mut tools = tools;
    tools.sort_by(|a, b| a.name.cmp(&b.name));

    // Convert to Value::Array of Records
    let tool_values: Vec<Value> = tools
        .iter()
        .map(|t| {
            let mut rec = BTreeMap::new();
            rec.insert("name".to_string(), Value::Str(t.name.clone()));
            rec.insert("description".to_string(), Value::Str(t.description.clone()));
            rec.insert("command".to_string(), Value::Str(t.command.clone()));
            rec.insert(
                "category".to_string(),
                Value::Str(format!("{:?}", t.category)),
            );
            rec.insert(
                "safety".to_string(),
                Value::Str(format!("{:?}", t.safety_level)),
            );
            rec.insert("requires_admin".to_string(), Value::Bool(t.requires_admin));
            rec.insert(
                "supported_os".to_string(),
                Value::Array(
                    t.supported_os
                        .iter()
                        .map(|os| Value::Str(format!("{:?}", os)))
                        .collect(),
                ),
            );
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(tool_values))
}

/// Get detailed information about a specific tool
/// Usage: tool_info("curl") | tool_info("nmap")
fn bi_tool_info(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let tool_name = args
        .first()
        .and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.clone())
            } else {
                None
            }
        })
        .ok_or_else(|| crate::safety::arg_err("tool_info requires tool name as argument"))?;

    let db = OSToolsDatabase::shared();
    let tool = db
        .get_tool(&tool_name)
        .ok_or_else(|| crate::safety::not_found("tool_info", "tool", &tool_name.to_string()))?;

    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(tool.name.clone()));
    rec.insert(
        "description".to_string(),
        Value::Str(tool.description.clone()),
    );
    rec.insert("command".to_string(), Value::Str(tool.command.clone()));
    rec.insert(
        "category".to_string(),
        Value::Str(format!("{:?}", tool.category)),
    );
    rec.insert(
        "safety_level".to_string(),
        Value::Str(format!("{:?}", tool.safety_level)),
    );
    rec.insert(
        "requires_admin".to_string(),
        Value::Bool(tool.requires_admin),
    );
    rec.insert(
        "supported_os".to_string(),
        Value::Array(
            tool.supported_os
                .iter()
                .map(|os| Value::Str(format!("{:?}", os)))
                .collect(),
        ),
    );
    rec.insert(
        "common_args".to_string(),
        Value::Array(
            tool.common_args
                .iter()
                .map(|a| Value::Str(a.clone()))
                .collect(),
        ),
    );

    // Add examples
    let examples: Vec<Value> = tool
        .examples
        .iter()
        .map(|ex| {
            let mut ex_rec = BTreeMap::new();
            ex_rec.insert(
                "description".to_string(),
                Value::Str(ex.description.clone()),
            );
            ex_rec.insert("command".to_string(), Value::Str(ex.command.clone()));
            if let Some(ref output) = ex.expected_output {
                ex_rec.insert("expected_output".to_string(), Value::Str(output.clone()));
            }
            Value::Record(ex_rec)
        })
        .collect();
    rec.insert("examples".to_string(), Value::Array(examples));

    // Add parameters if available
    let params: Vec<Value> = tool
        .parameters
        .iter()
        .map(|p| {
            let mut p_rec = BTreeMap::new();
            p_rec.insert("name".to_string(), Value::Str(p.name.clone()));
            p_rec.insert("description".to_string(), Value::Str(p.description.clone()));
            p_rec.insert(
                "type".to_string(),
                Value::Str(format!("{:?}", p.param_type)),
            );
            p_rec.insert("required".to_string(), Value::Bool(p.required));
            if let Some(ref default) = p.default_value {
                p_rec.insert("default".to_string(), Value::Str(default.clone()));
            }
            if !p.enum_values.is_empty() {
                p_rec.insert(
                    "enum_values".to_string(),
                    Value::Array(
                        p.enum_values
                            .iter()
                            .map(|v| Value::Str(v.clone()))
                            .collect(),
                    ),
                );
            }
            Value::Record(p_rec)
        })
        .collect();
    rec.insert("parameters".to_string(), Value::Array(params));

    Ok(Value::Record(rec))
}

/// Get OpenAI-compatible function calling schemas for tools
/// Usage: tool_schema("curl") | tool_schema() for all | tool_schema("network") for category
fn bi_tool_schema(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db = OSToolsDatabase::shared();

    let filter = match args.first() {
        None => None,
        Some(Value::Str(s)) => Some(s.clone()),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "tool_schema",
                "filter: String",
                other.type_name(),
            ));
        }
    };

    let schemas = if let Some(ref name) = filter {
        // Check if it's a specific tool
        if let Some(tool) = db.get_tool(name) {
            vec![tool.to_openai_function_schema()]
        } else {
            // Check if it's a category
            let cat = match name.to_lowercase().as_str() {
                "network" | "net" => Some(ToolCategory::NetworkTools),
                "web" | "webtools" => Some(ToolCategory::WebTools),
                "cyber" | "cybersecurity" => Some(ToolCategory::CyberSecurity),
                "filesystem" | "file" => Some(ToolCategory::FileSystem),
                "security" | "sec" => Some(ToolCategory::Security),
                "forensics" => Some(ToolCategory::Forensics),
                "crypto" | "cryptography" => Some(ToolCategory::Cryptography),
                _ => None,
            };

            if let Some(c) = cat {
                db.get_category_schemas(&c)
            } else {
                // Search and return schemas for matching tools
                db.search_tools(name)
                    .iter()
                    .map(|t| t.to_openai_function_schema())
                    .collect()
            }
        }
    } else {
        // Return all schemas
        db.to_openai_function_schemas()
    };

    // Convert serde_json::Value to our Value
    let schema_values: Vec<Value> = schemas.into_iter().map(json_to_value).collect();

    Ok(Value::Array(schema_values))
}

/// Execute a tool with given arguments
/// Usage: tool_exec("ls", ["-la"]) | tool_exec("curl", ["-s", "https://example.com"])
fn bi_tool_exec(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err(
            "tool_exec requires: tool_name, [args], [allow_dangerous]",
        ));
    }

    let tool_name = if let Value::Str(s) = &args[0] {
        s.clone()
    } else {
        return Err(crate::safety::arg_err(
            "tool_exec: first argument must be tool name string",
        ));
    };

    if args.len() > 3 {
        return Err(crate::safety::bad_arg(
            "tool_exec",
            "at most 3 arguments: tool_name, [args], [allow_dangerous]",
            &format!("{} arguments", args.len()),
        ));
    }

    // Every argument is passed to the program as given, so a value that is not
    // a string used to be dropped from the argv (changing what ran) or the
    // whole list was discarded. Refuse those instead.
    let tool_args: Vec<String> = match args.get(1) {
        None | Some(Value::Null) => vec![],
        Some(Value::Str(s)) => vec![s.clone()],
        Some(Value::Array(arr)) => {
            let mut out = Vec::with_capacity(arr.len());
            for (i, v) in arr.iter().enumerate() {
                match v {
                    Value::Str(s) if !s.contains('\0') => out.push(s.clone()),
                    other => {
                        return Err(crate::safety::bad_arg(
                            "tool_exec",
                            &format!("args[{i}]: a string without NUL"),
                            other.type_name(),
                        ))
                    }
                }
            }
            out
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "tool_exec",
                "args: an Array<String> or a single String",
                other.type_name(),
            ))
        }
    };

    let allow_dangerous = match args.get(2) {
        None | Some(Value::Null) => false,
        Some(Value::Bool(b)) => *b,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "tool_exec",
                "allow_dangerous: a boolean",
                other.type_name(),
            ))
        }
    };

    let db = OSToolsDatabase::shared();
    let tool = db
        .get_tool(&tool_name)
        .ok_or_else(|| crate::safety::not_found("tool_exec", "tool", &tool_name))?;
    if !allow_dangerous
        && matches!(
            tool.safety_level,
            crate::os_tools::SafetyLevel::Dangerous | crate::os_tools::SafetyLevel::Critical
        )
    {
        return Err(crate::safety::policy_deny(
            "tool_exec",
            format!("tool '{tool_name}' is {:?}", tool.safety_level),
            "pass allow_dangerous=true, which needs the same approval as any gated exec",
        ));
    }

    crate::safety::guard_exec(
        "tool_exec",
        format!("{} {}", tool_name, tool_args.join(" ")),
    )?;

    // A refusal before the run is a policy denial. Everything else is already
    // coded: a missing program (E_TOOL_MISSING), a run past its deadline
    // (E_BUDGET_EXCEEDED, the child killed) or a failure to start.
    let result = execute_tool_safe(&db, &tool_name, &tool_args, allow_dangerous).map_err(|e| {
        if e.is::<crate::os_tools::ToolRefusal>() {
            let message = e.to_string();
            crate::safety::policy_deny(
                "tool_exec",
                message,
                "see the tool's safety and OS requirements",
            )
        } else {
            e
        }
    })?;

    // Convert result to Value::Record
    let mut rec = BTreeMap::new();
    rec.insert("success".to_string(), Value::Bool(result.success));
    rec.insert("stdout".to_string(), Value::Str(result.stdout));
    rec.insert(
        "stdout_truncated".to_string(),
        Value::Bool(result.stdout_truncated),
    );
    rec.insert("stderr".to_string(), Value::Str(result.stderr));
    rec.insert(
        "stderr_truncated".to_string(),
        Value::Bool(result.stderr_truncated),
    );
    rec.insert(
        "exit_code".to_string(),
        result
            .exit_code
            .map(|c| Value::Int(c as i64))
            .unwrap_or(Value::Null),
    );
    rec.insert("tool_name".to_string(), Value::Str(result.tool_name));
    rec.insert(
        "command_executed".to_string(),
        Value::Str(result.command_executed),
    );
    rec.insert(
        "execution_time_ms".to_string(),
        Value::Int(result.execution_time_ms as i64),
    );

    Ok(Value::Record(rec))
}

/// Search for tools by keyword or description
/// Usage: tool_search("network") | tool_search("file copy")
fn bi_tool_search(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let query = args
        .first()
        .and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.clone())
            } else {
                None
            }
        })
        .ok_or_else(|| crate::safety::arg_err("tool_search requires a search query"))?;

    let db = OSToolsDatabase::shared();

    // Use get_recommended_tools for smart search
    let tools = db.get_recommended_tools(&query);

    // If no recommendations, fall back to regular search
    let tools = if tools.is_empty() {
        db.search_tools(&query)
    } else {
        tools
    };

    let tool_values: Vec<Value> = tools
        .iter()
        .map(|t| {
            let mut rec = BTreeMap::new();
            rec.insert("name".to_string(), Value::Str(t.name.clone()));
            rec.insert("description".to_string(), Value::Str(t.description.clone()));
            rec.insert("command".to_string(), Value::Str(t.command.clone()));
            rec.insert(
                "category".to_string(),
                Value::Str(format!("{:?}", t.category)),
            );
            rec.insert(
                "safety".to_string(),
                Value::Str(format!("{:?}", t.safety_level)),
            );
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(tool_values))
}

// ===========================================================================
// Recursive Language Model (RLM) Builtins
// ===========================================================================

/// Run a recursive agent that can spawn subagents
/// Usage: rlm_agent("goal", ["tool1", "tool2"])
///        rlm_agent("goal", ["tools"], {max_depth: 3, max_agents: 20})
fn bi_rlm_agent(args: Vec<Value>, _input: Option<Value>, env: &mut Env) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err(
            "rlm_agent requires: goal, [tools], [config]",
        ));
    }

    let goal = if let Value::Str(s) = &args[0] {
        s.clone()
    } else {
        return Err(crate::safety::arg_err(
            "rlm_agent: first argument must be goal string",
        ));
    };

    if args.len() > 4 {
        return Err(crate::safety::bad_arg(
            "rlm_agent",
            "at most 4 arguments: goal, [tools], [config], [model_uri]",
            &format!("{} arguments", args.len()),
        ));
    }

    let tool_names = match args.get(1) {
        None => rlm_default_tools(),
        Some(v) => rlm_tool_list("rlm_agent", v)?,
    };

    let config = match args.get(2) {
        None => RlmConfig::default(),
        Some(v) => parse_rlm_config(v)?,
    };

    let model_uri = match args.get(3) {
        None | Some(Value::Null) => None,
        Some(Value::Str(s)) if !s.is_empty() => Some(s.clone()),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "rlm_agent",
                "model_uri: a non-empty string",
                other.type_name(),
            ))
        }
    };

    let tool_refs: Vec<&str> = tool_names.iter().map(|s| s.as_str()).collect();

    let (result, stats) = if let Some(uri) = model_uri {
        run_recursive_with_model(&goal, &tool_refs, &uri, config, false, env)?
    } else {
        run_recursive(&goal, &tool_refs, config, false, env)?
    };
    record_rlm_run(&stats);

    // Return result with stats
    let mut rec = BTreeMap::new();
    rec.insert("output".to_string(), Value::Str(result));
    rec.insert(
        "total_agents".to_string(),
        Value::Int(stats.total_spawned as i64),
    );
    rec.insert(
        "active_agents".to_string(),
        Value::Int(stats.currently_active as i64),
    );
    rec.insert(
        "messages_sent".to_string(),
        Value::Int(stats.messages_sent as i64),
    );
    rec.insert(
        "elapsed_ms".to_string(),
        Value::Int(stats.elapsed_ms as i64),
    );

    Ok(Value::Record(rec))
}

/// Create an RLM configuration
/// Usage: rlm_config({max_depth: 5, max_agents: 50, timeout: 60})
fn bi_rlm_config(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let config = if args.is_empty() {
        RlmConfig::default()
    } else {
        parse_rlm_config(&args[0])?
    };

    let mut rec = BTreeMap::new();
    rec.insert("max_depth".to_string(), Value::Int(config.max_depth as i64));
    rec.insert(
        "max_agents".to_string(),
        Value::Int(config.max_agents as i64),
    );
    rec.insert(
        "agent_timeout_secs".to_string(),
        Value::Int(config.agent_timeout_secs as i64),
    );
    rec.insert(
        "max_concurrent_children".to_string(),
        Value::Int(config.max_concurrent_children as i64),
    );
    rec.insert(
        "trace_enabled".to_string(),
        Value::Bool(config.trace_enabled),
    );
    if let Some(uri) = config.subagent_model_uri {
        rec.insert("subagent_model_uri".to_string(), Value::Str(uri));
    }

    Ok(Value::Record(rec))
}

/// Get RLM statistics from the last run
/// Usage: rlm_stats()
/// The last recursive-agent run's statistics, and how many runs there were.
static LAST_RLM_RUN: std::sync::Mutex<Option<(u64, crate::rlm::HierarchyStats)>> =
    std::sync::Mutex::new(None);

fn record_rlm_run(stats: &crate::rlm::HierarchyStats) {
    let mut last = LAST_RLM_RUN.lock().unwrap_or_else(|e| e.into_inner());
    let runs = last.as_ref().map_or(0, |(n, _)| *n) + 1;
    *last = Some((runs, stats.clone()));
}

fn bi_rlm_stats(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Given the record an rlm run returned, report it.
    match input.or_else(|| args.first().cloned()) {
        Some(Value::Record(rec)) => return Ok(Value::Record(rec)),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "rlm_stats",
                "nothing, or the record an rlm run returned",
                other.type_name(),
            ))
        }
        None => {}
    }
    // With no argument this returned constants -- max_depth 5, max_agents 50,
    // zero spawned -- presented as "statistics from the last run", whether or
    // not anything had run. Nothing recorded runs. rlm_agent and rlm_spawn
    // now do, and this reports the last one; before any run, `runs` is 0 and
    // there is no last run to describe.
    let last = LAST_RLM_RUN
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .clone();
    let mut rec = BTreeMap::new();
    rec.insert(
        "runs".to_string(),
        Value::Int(last.as_ref().map_or(0, |(n, _)| *n as i64)),
    );
    let last = last.map(|(_, st)| {
        let mut r = BTreeMap::new();
        r.insert(
            "total_spawned".to_string(),
            Value::Int(st.total_spawned as i64),
        );
        r.insert(
            "currently_active".to_string(),
            Value::Int(st.currently_active as i64),
        );
        r.insert(
            "messages_sent".to_string(),
            Value::Int(st.messages_sent as i64),
        );
        r.insert("elapsed_ms".to_string(), Value::Int(st.elapsed_ms as i64));
        r.insert("max_depth".to_string(), Value::Int(st.max_depth as i64));
        r.insert("max_agents".to_string(), Value::Int(st.max_agents as i64));
        Value::Record(r)
    });
    rec.insert("last_run".to_string(), last.unwrap_or(Value::Null));
    Ok(Value::Record(rec))
}

/// Spawn a subagent (used in agent context)
/// Usage: rlm_spawn("name", "goal", ["tools"])
fn bi_rlm_spawn(args: Vec<Value>, _input: Option<Value>, env: &mut Env) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "rlm_spawn requires: name, goal, [tools]",
        ));
    }

    let name = if let Value::Str(s) = &args[0] {
        s.clone()
    } else {
        return Err(crate::safety::arg_err("rlm_spawn: name must be a string"));
    };

    let goal = if let Value::Str(s) = &args[1] {
        s.clone()
    } else {
        return Err(crate::safety::arg_err("rlm_spawn: goal must be a string"));
    };

    if args.len() > 3 {
        return Err(crate::safety::bad_arg(
            "rlm_spawn",
            "at most 3 arguments: name, goal, [tools]",
            &format!("{} arguments", args.len()),
        ));
    }
    let tool_names = match args.get(2) {
        None => vec!["ls".to_string(), "cat".to_string()],
        Some(v) => rlm_tool_list("rlm_spawn", v)?,
    };

    // Run a single-depth recursive agent for the spawn. Every bound here is a
    // literal, not a caller choice: one level, five agents, thirty seconds.
    let config = RlmConfig {
        max_depth: 1, // Single level only
        max_agents: 5,
        agent_timeout_secs: 30,
        ..Default::default()
    };

    // Spawning an autonomous sub-agent is an execution decision in its own right:
    // the individual tool calls it makes are guarded at their own chokepoints,
    // but *whether to start it at all* is the one point a policy can weigh.
    crate::safety::guard_exec("rlm_spawn", format!("spawn agent '{name}': {goal}"))?;
    let tool_refs: Vec<&str> = tool_names.iter().map(|s| s.as_str()).collect();
    let (result, stats) = run_recursive(&goal, &tool_refs, config, false, env)?;
    record_rlm_run(&stats);

    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(name));
    rec.insert("goal".to_string(), Value::Str(goal));
    // `run_sync` answers a run that hit its step cap with an Ok string that
    // begins "(incomplete)", not with an error. That is not a success, however
    // many agents it spawned.
    let complete = !result.starts_with("(incomplete)");
    rec.insert("output".to_string(), Value::Str(result));
    rec.insert("complete".to_string(), Value::Bool(complete));
    rec.insert(
        "success".to_string(),
        Value::Bool(stats.total_spawned > 0 && complete),
    );
    rec.insert(
        "agents_used".to_string(),
        Value::Int(stats.total_spawned as i64),
    );
    rec.insert(
        "elapsed_ms".to_string(),
        Value::Int(stats.elapsed_ms as i64),
    );

    Ok(Value::Record(rec))
}

/// Hard ceilings on the recursion budgets a caller may choose. A request above
/// one is refused with `E_BUDGET_EXCEEDED`, not clamped: a silently smaller
/// run than the one asked for is a result nobody can reason about.
const RLM_MAX_DEPTH_CEILING: i64 = 8;
const RLM_MAX_AGENTS_CEILING: i64 = 200;
const RLM_MAX_CHILDREN_CEILING: i64 = 32;
const RLM_TIMEOUT_CEILING_SECS: i64 = 3600;

/// The tool names a recursive agent gets when the caller names none.
fn rlm_default_tools() -> Vec<String> {
    ["ls", "cat", "grep", "find"]
        .iter()
        .map(|s| s.to_string())
        .collect()
}

/// A caller's tool list: an array of names of builtins that exist. A name that
/// does not is refused rather than dropped, so the agent never runs with fewer
/// tools than it was given.
fn rlm_tool_list(builtin: &str, value: &Value) -> Result<Vec<String>> {
    let arr = match value {
        Value::Null => return Ok(rlm_default_tools()),
        Value::Array(arr) => arr,
        other => {
            return Err(crate::safety::bad_arg(
                builtin,
                "tools: Array<String> of builtin names",
                other.type_name(),
            ))
        }
    };
    let mut out = Vec::with_capacity(arr.len());
    for (i, v) in arr.iter().enumerate() {
        match v {
            Value::Str(s) if crate::builtins::is_dispatched(s) => out.push(s.clone()),
            Value::Str(s) => {
                return Err(crate::safety::not_found(builtin, "builtin", s));
            }
            other => {
                return Err(crate::safety::bad_arg(
                    builtin,
                    &format!("tools[{i}]: a builtin name string"),
                    other.type_name(),
                ))
            }
        }
    }
    Ok(out)
}

/// One integer budget from a config record, between `min` and `ceiling`.
fn rlm_budget(key: &str, v: &Value, min: i64, ceiling: i64) -> Result<i64> {
    match v {
        Value::Int(n) if *n > ceiling => Err(crate::safety::budget_exceeded(
            "rlm_agent",
            format!("{key} = {n} is above the ceiling of {ceiling}"),
            "lower it; the ceiling is fixed so one call cannot fan out without bound",
        )),
        Value::Int(n) if *n >= min => Ok(*n),
        Value::Int(n) => Err(crate::safety::bad_arg(
            "rlm_agent",
            &format!("{key}: an integer from {min} to {ceiling}"),
            &n.to_string(),
        )),
        other => Err(crate::safety::bad_arg(
            "rlm_agent",
            &format!("{key}: an integer from {min} to {ceiling}"),
            other.type_name(),
        )),
    }
}

/// Parse RLM configuration from a Value.
///
/// Every key must be one this reads, and every value must have the right type
/// and lie within its ceiling. A negative count used to wrap to a huge `usize`
/// (an effectively unbounded depth or agent count), and an unknown key or a
/// wrong type used to fall back to the default with no word.
fn parse_rlm_config(value: &Value) -> Result<RlmConfig> {
    const KEYS: &[&str] = &[
        "max_depth",
        "max_agents",
        "timeout",
        "agent_timeout_secs",
        "max_concurrent_children",
        "trace_enabled",
        "trace",
        "model_uri",
        "subagent_model_uri",
    ];
    let rec = match value {
        Value::Record(rec) => rec,
        other => {
            return Err(crate::safety::bad_arg(
                "rlm_agent",
                "config: a Record of recursion budgets",
                other.type_name(),
            ))
        }
    };
    if let Some(k) = rec.keys().find(|k| !KEYS.contains(&k.as_str())) {
        return Err(crate::safety::bad_arg(
            "rlm_agent",
            &format!("config: a known key (one of {})", KEYS.join(", ")),
            &format!("key '{k}'"),
        ));
    }

    let mut config = RlmConfig::default();
    if let Some(v) = rec.get("max_depth") {
        config.max_depth = rlm_budget("max_depth", v, 0, RLM_MAX_DEPTH_CEILING)? as usize;
    }
    if let Some(v) = rec.get("max_agents") {
        config.max_agents = rlm_budget("max_agents", v, 1, RLM_MAX_AGENTS_CEILING)? as usize;
    }
    for key in ["timeout", "agent_timeout_secs"] {
        if let Some(v) = rec.get(key) {
            config.agent_timeout_secs = rlm_budget(key, v, 1, RLM_TIMEOUT_CEILING_SECS)? as u64;
        }
    }
    if let Some(v) = rec.get("max_concurrent_children") {
        config.max_concurrent_children =
            rlm_budget("max_concurrent_children", v, 1, RLM_MAX_CHILDREN_CEILING)? as usize;
    }
    for key in ["trace_enabled", "trace"] {
        match rec.get(key) {
            None => {}
            Some(Value::Bool(b)) => config.trace_enabled = *b,
            Some(other) => {
                return Err(crate::safety::bad_arg(
                    "rlm_agent",
                    &format!("{key}: a boolean"),
                    other.type_name(),
                ))
            }
        }
    }
    for key in ["model_uri", "subagent_model_uri"] {
        match rec.get(key) {
            None => {}
            Some(Value::Str(s)) if !s.is_empty() => config.subagent_model_uri = Some(s.clone()),
            Some(other) => {
                return Err(crate::safety::bad_arg(
                    "rlm_agent",
                    &format!("{key}: a non-empty string"),
                    other.type_name(),
                ))
            }
        }
    }
    Ok(config)
}

// =============== New Aspirational Feature Builtins ===============

/// sh(args) - Execute a shell command directly
/// Usage: sh(["echo", "hello"]) or sh("echo hello")
///
/// SECURITY: Gated behind IRONSHELL_ALLOW_SH=true environment variable.

/// Split a command line into words as a POSIX shell does, without any of the
/// expansions a shell would then perform.
///
/// Whitespace separates words; `'...'` is literal; `"..."` is literal except
/// that `\` escapes `"`, `\`, `$` and a backquote; outside quotes `\` escapes
/// the next character. Adjacent pieces join into one word (`a"b c"d` is
/// `ab cd`), and `''` is an empty argument rather than nothing.
fn split_command_words(s: &str) -> std::result::Result<Vec<String>, String> {
    let mut words = Vec::new();
    let mut cur = String::new();
    let mut in_word = false;
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\'' => {
                in_word = true;
                loop {
                    match chars.next() {
                        Some('\'') => break,
                        Some(ch) => cur.push(ch),
                        None => return Err("an unterminated single quote".into()),
                    }
                }
            }
            '"' => {
                in_word = true;
                loop {
                    match chars.next() {
                        Some('"') => break,
                        Some('\\') => match chars.peek() {
                            Some(&n) if matches!(n, '"' | '\\' | '$' | '`') => {
                                cur.push(n);
                                chars.next();
                            }
                            _ => cur.push('\\'),
                        },
                        Some(ch) => cur.push(ch),
                        None => return Err("an unterminated double quote".into()),
                    }
                }
            }
            '\\' => {
                in_word = true;
                match chars.next() {
                    Some(n) => cur.push(n),
                    None => return Err("a trailing backslash".into()),
                }
            }
            c if c.is_whitespace() => {
                if in_word {
                    words.push(std::mem::take(&mut cur));
                    in_word = false;
                }
            }
            c => {
                in_word = true;
                cur.push(c);
            }
        }
    }
    if in_word {
        words.push(cur);
    }
    Ok(words)
}

#[cfg(test)]
mod split_command_words_tests {
    use super::split_command_words;

    fn split(s: &str) -> Vec<String> {
        split_command_words(s).unwrap()
    }

    #[test]
    fn quoted_arguments_stay_whole() {
        assert_eq!(
            split("git commit -m 'fix bug'"),
            ["git", "commit", "-m", "fix bug"]
        );
        assert_eq!(split(r#"echo "a \"b\" c""#), ["echo", r#"a "b" c"#]);
        assert_eq!(split(r"touch my\ file"), ["touch", "my file"]);
    }

    #[test]
    fn adjacent_quotes_join_and_empty_quotes_are_words() {
        assert_eq!(split(r#"a'b'"c" ''"#), ["abc", ""]);
    }

    #[test]
    fn nothing_is_expanded() {
        assert_eq!(split("echo $HOME '*' *"), ["echo", "$HOME", "*", "*"]);
        assert_eq!(split(r"echo 'a\nb'"), ["echo", r"a\nb"]);
    }

    #[test]
    fn whitespace_only_is_no_words() {
        assert!(split("  \t ").is_empty());
    }

    #[test]
    fn malformed_input_is_refused() {
        assert!(split_command_words("echo 'open").is_err());
        assert!(split_command_words("echo \"open").is_err());
        assert!(split_command_words("echo \\").is_err());
    }
}

fn bi_sh(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("sh", &input)?;
    k8s_max_args("sh", &args, 1)?;

    if args.is_empty() {
        return Err(crate::safety::bad_arg(
            "sh",
            "a command String or an argv Array",
            "nothing",
        ));
    }

    let (program, cmd_args): (String, Vec<String>) = match &args[0] {
        Value::Str(s) => {
            // Split the way a POSIX shell would split WORDS -- quotes and
            // backslashes honoured -- but without running a shell: no
            // globbing, no variables, no pipes. This was `split_whitespace`,
            // which ignored quotes entirely, so
            // `sh("git commit -m 'fix bug'")` passed `'fix` and `bug'` as two
            // arguments: the commit message became `'fix`, and `bug'` was
            // taken as a path. Found while writing a probe whose control call
            // was `bash -c '...'` and never ran.
            let parts = split_command_words(s).map_err(|why| {
                crate::safety::bad_arg(
                    "sh",
                    "a command with balanced quotes, or an array of arguments",
                    &why,
                )
            })?;
            if parts.is_empty() {
                return Err(crate::safety::bad_arg(
                    "sh",
                    "a non-empty command",
                    "an empty string",
                ));
            }
            (parts[0].clone(), parts[1..].to_vec())
        }
        Value::Array(arr) => {
            if arr.is_empty() {
                return Err(crate::safety::bad_arg(
                    "sh",
                    "a non-empty command",
                    "an empty array",
                ));
            }
            let program = match &arr[0] {
                Value::Str(s) => s.clone(),
                other => {
                    return Err(crate::safety::bad_arg(
                        "sh",
                        "a program name String as the first element",
                        other.type_name(),
                    ))
                }
            };
            let args: Result<Vec<String>> = arr[1..]
                .iter()
                .map(|v| match v {
                    Value::Str(s) => Ok(s.clone()),
                    Value::Int(n) => Ok(n.to_string()),
                    Value::Float(f) => Ok(f.to_string()),
                    other => Err(crate::safety::bad_arg(
                        "sh",
                        "arguments that are strings or numbers",
                        other.type_name(),
                    )),
                })
                .collect();
            (program, args?)
        }
        other => {
            return Err(crate::safety::bad_arg(
                "sh",
                "a command String or an argv Array",
                other.type_name(),
            ))
        }
    };

    // Security gate: require explicit opt-in. Checked after the shape, so a
    // malformed call says what is wrong with it whether or not sh is enabled.
    validate_sh_allowed()?;

    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "sh",
        effect: crate::safety::Effect::Exec,
        what: "exec",
        targets: vec![format!("{} {}", program, cmd_args.join(" "))
            .trim()
            .to_string()],
        blast_radius: serde_json::json!({ "program": program, "args": cmd_args }),
        reversible: false,
        fs_paths: false,
    })?;

    // Directly, never through a shell, with stdin closed. This was
    // `Command::output()`: no deadline, so a program that never exits held the
    // session forever, and both streams were kept whole, so one that printed
    // without end grew without bound. A missing program was an uncoded error.
    let argv: Vec<&str> = cmd_args.iter().map(String::as_str).collect();
    let run = tool_run_stderr(
        "sh",
        &program,
        None,
        &argv,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_KEEP_TAIL,
        TOOL_LONG_DEADLINE_SECS,
    )?;

    // A nonzero exit is the program's answer, not a failure of `sh`: the record
    // carries it, as a shell's `$?` does.
    let mut record = BTreeMap::new();
    record.insert("stdout".to_string(), Value::Str(run.stdout));
    record.insert("stderr".to_string(), Value::Str(run.stderr));
    record.insert("success".to_string(), Value::Bool(run.success));
    record.insert(
        "exit_code".to_string(),
        Value::Int(run.code.unwrap_or(-1) as i64),
    );
    record.insert(
        "stdout_truncated".to_string(),
        Value::Bool(run.stdout_truncated),
    );

    Ok(Value::Record(record))
}

// ─────────────────────────────────────────────────────────────────────────
// Output economy (token efficiency): AECON compact rendering + token estimate.
// See docs/AGENTIC_FIRST_DESIGN.md §6.2. The dominant agent output cost is
// homogeneous record arrays (ls, proc.list, docker.ps, db queries); AECON emits
// the field names ONCE as a header, then positional TSV rows — typically a
// large output-token saving over repeating keys per row (as JSON does).
// ─────────────────────────────────────────────────────────────────────────

/// Render one cell value compactly. Strings are emitted raw unless empty or
/// containing the TSV delimiters (tab/newline), in which case they're JSON
/// quoted; nested arrays/records are inlined as JSON to preserve row structure.
fn aecon_atom(v: &Value) -> String {
    match v {
        Value::Str(s) => {
            // A bare cell opening with `{` or `[` is reserved for a composite value
            // (record/array), which renders as JSON below. A *string* that happens to
            // start that way is JSON-quoted so the two can never be confused — the
            // same reservation `""` already provides for the empty string.
            if s.is_empty()
                || s.contains('\t')
                || s.contains('\n')
                || s.starts_with('{')
                || s.starts_with('[')
            {
                serde_json::to_string(s).unwrap_or_else(|_| format!("{:?}", s))
            } else {
                s.clone()
            }
        }
        Value::Uri(u) => u.clone(),
        Value::Int(n) => n.to_string(),
        Value::Float(f) => crate::value::float_text(*f),
        Value::Bool(b) => b.to_string(),
        Value::Null => "null".to_string(),
        other => serde_json::to_string(&other.to_json()).unwrap_or_else(|_| "null".to_string()),
    }
}

/// Longest common character prefix shared by every string in `vals` (empty if
/// they share none). Char-aligned, so the returned `String`'s byte length is a
/// valid UTF-8 slice boundary in each input — used by `@prefix` factoring.
fn longest_common_str_prefix(vals: &[&str]) -> String {
    let mut prefix: Vec<char> = match vals.first() {
        Some(s) => s.chars().collect(),
        None => return String::new(),
    };
    for s in vals.iter().skip(1) {
        let mut n = 0usize;
        for (a, b) in prefix.iter().zip(s.chars()) {
            if *a == b {
                n += 1;
            } else {
                break;
            }
        }
        prefix.truncate(n);
        if prefix.is_empty() {
            break;
        }
    }
    prefix.into_iter().collect()
}

/// Longest common character *suffix* shared by every string in `vals` (empty if
/// they share none). Char-aligned, so subtracting the returned `String`'s byte
/// length from each input's length lands on a valid UTF-8 boundary — used by
/// `@suffix` factoring (shared extensions, domain tails, id suffixes).
fn longest_common_str_suffix(vals: &[&str]) -> String {
    let mut suffix: Vec<char> = match vals.first() {
        Some(s) => s.chars().rev().collect(),
        None => return String::new(),
    };
    for s in vals.iter().skip(1) {
        let mut n = 0usize;
        for (a, b) in suffix.iter().zip(s.chars().rev()) {
            if *a == b {
                n += 1;
            } else {
                break;
            }
        }
        suffix.truncate(n);
        if suffix.is_empty() {
            break;
        }
    }
    suffix.into_iter().rev().collect()
}

/// Depth limit for `@nest` flattening. Deep enough for real API payloads, shallow
/// enough that a pathological or cyclic-looking shape cannot blow the stack.
const AECON_NEST_DEPTH: usize = 4;

/// Flatten a record's nested-record fields into dotted columns, in place.
/// `user: {id, name}` becomes `user.id` / `user.name`, recursively to
/// `AECON_NEST_DEPTH`. Records are the only thing expanded — arrays and scalars stay
/// whole, so a cell is always an atom. Returns the *top-level* keys that were
/// expanded, which the `@nest` line names so decode knows which dotted columns to
/// rebuild (and which merely contain a literal dot).
fn aecon_flatten_into(
    src: &BTreeMap<String, Value>,
    out: &mut BTreeMap<String, Value>,
    prefix: &str,
    depth: usize,
) {
    for (k, v) in src {
        let name = if prefix.is_empty() {
            k.clone()
        } else {
            format!("{prefix}.{k}")
        };
        match v {
            // An empty record carries no columns, so flattening it would erase the
            // field entirely; keep it as an atom so the round-trip holds.
            Value::Record(inner) if depth < AECON_NEST_DEPTH && !inner.is_empty() => {
                aecon_flatten_into(inner, out, &name, depth + 1)
            }
            other => {
                out.insert(name, other.clone());
            }
        }
    }
}

/// Render a Value as AECON (IronShell Compact Object Notation). Tabular values
/// (Table, or a homogeneous Array<Record>) become a `@aecon` header + TSV rows;
/// single records become `{k=v ...}`; scalar arrays become `[a,b,c]`; scalars
/// render as their literal. Deterministic (records are key-sorted BTreeMaps).
fn aecon_render(v: &Value) -> String {
    let (rows, header): (Vec<&BTreeMap<String, Value>>, Option<Vec<String>>) = match v {
        Value::Table(t) => {
            let h = if t.schema.is_empty() {
                None
            } else {
                Some(t.schema.clone())
            };
            (t.rows.iter().collect(), h)
        }
        Value::Array(arr)
            if !arr.is_empty() && arr.iter().all(|e| matches!(e, Value::Record(_))) =>
        {
            let rs = arr
                .iter()
                .filter_map(|e| match e {
                    Value::Record(m) => Some(m),
                    _ => None,
                })
                .collect();
            (rs, None)
        }
        _ => (Vec::new(), None),
    };

    // `@nest`: a record-valued cell would otherwise serialize as whole JSON on every
    // row — keys and all — which is precisely what this format exists to avoid, and
    // none of the column passes below can reach inside it. Expanding it into dotted
    // columns subjects each leaf to `@const`/`@dict`/`@prefix`/`@suffix`/`@same` like
    // any other column. A top-level key is expanded only when no existing column
    // already starts with `<key>.`, so a literal dotted key is never shadowed; the
    // `@nest` line names exactly what was expanded, so decode rebuilds only those.
    let mut nest_keys: Vec<String> = Vec::new();
    let flattened: Option<Vec<BTreeMap<String, Value>>> = if rows.len() >= 2 {
        let top: Vec<&String> = rows[0].keys().collect();
        let expandable: Vec<String> = rows[0]
            .iter()
            .filter(|(k, v)| match v {
                Value::Record(inner) => {
                    !inner.is_empty()
                        && !top.iter().any(|other| other.starts_with(&format!("{k}.")))
                }
                _ => false,
            })
            .map(|(k, _)| k.clone())
            .collect();
        // Every row must agree that the field is a record, or the flattened table is
        // ragged and the homogeneity check below would reject it anyway.
        let consistent = expandable.iter().all(|k| {
            rows.iter()
                .all(|r| matches!(r.get(k), Some(Value::Record(m)) if !m.is_empty()))
        });
        if expandable.is_empty() || !consistent {
            None
        } else {
            nest_keys = expandable;
            Some(
                rows.iter()
                    .map(|r| {
                        let mut out = BTreeMap::new();
                        for (k, v) in r.iter() {
                            if nest_keys.contains(k) {
                                if let Value::Record(inner) = v {
                                    aecon_flatten_into(inner, &mut out, k, 1);
                                    continue;
                                }
                            }
                            out.insert(k.clone(), v.clone());
                        }
                        out
                    })
                    .collect(),
            )
        }
    } else {
        None
    };
    let (rows, header) = match &flattened {
        // Flattening rewrites the column set, so a caller-supplied schema no longer
        // describes it; the expanded keys are the schema.
        Some(f) => (f.iter().collect::<Vec<_>>(), None),
        None => (rows, header),
    };

    if !rows.is_empty() {
        let keys: Vec<String> = header.unwrap_or_else(|| rows[0].keys().cloned().collect());
        let homogeneous = rows
            .iter()
            .all(|r| r.len() == keys.len() && keys.iter().all(|k| r.contains_key(k)));
        if homogeneous {
            // Constant-column factoring: columns whose value is identical across
            // ALL rows are emitted once in a `@const` line rather than repeated
            // per row — a real per-row token saving for the common case of
            // constant status/type/owner fields. (No constants → unchanged.)
            let (mut const_keys, mut var_keys): (Vec<String>, Vec<String>) =
                (Vec::new(), Vec::new());
            if rows.len() >= 2 {
                for k in &keys {
                    let first = rows[0].get(k);
                    if rows.iter().all(|r| r.get(k) == first) {
                        const_keys.push(k.clone());
                    } else {
                        var_keys.push(k.clone());
                    }
                }
            } else {
                var_keys = keys.clone();
            }
            // If every column is constant (identical rows), don't factor it all
            // away — keep them as the header so the row count stays observable.
            if var_keys.is_empty() {
                var_keys = keys.clone();
                const_keys.clear();
            }
            // Per-column encoding choice, decided by exact character cost.
            //
            // Every eligible STRING column has three candidate encodings — raw,
            // `@dict` (each distinct value once, referenced per row by integer
            // index), and `@prefix`/`@suffix` (shared leading and trailing runs
            // emitted once and stripped from every row) — and the cheapest wins.
            //
            // Costing them for real replaces two hand-tuned dictionary heuristics
            // (`d <= rows/2`, `avg_len >= 3`) that mis-fired in both directions:
            // they declined dictionaries that would have paid on long values, and
            // — because `@dict` was tried first and won by default — they took
            // columns that prefix/suffix factoring would have compressed further.
            // Costs are byte counts, so the choice is deterministic and
            // format-stable across builds (no tokenizer, no float).
            //
            // Eligibility is bare-safe strings only (non-empty, no tab/newline).
            // For `@prefix`/`@suffix` that keeps the stripped residue splittable;
            // for `@dict` it is a *correctness* requirement, because the distinct
            // values are emitted tab-separated on the `@dict` line — a value
            // containing a tab would silently corrupt its own dictionary.
            let mut dict_cols: std::collections::BTreeMap<String, Vec<String>> =
                std::collections::BTreeMap::new();
            let mut dict_index: std::collections::HashMap<
                String,
                std::collections::HashMap<String, usize>,
            > = std::collections::HashMap::new();
            let mut prefix_cols: std::collections::BTreeMap<String, String> =
                std::collections::BTreeMap::new();
            let mut suffix_cols: std::collections::BTreeMap<String, String> =
                std::collections::BTreeMap::new();
            for k in &var_keys {
                let mut vals: Vec<&str> = Vec::with_capacity(rows.len());
                let mut all_bare = true;
                for r in &rows {
                    match r.get(k) {
                        Some(Value::Str(s))
                            if !s.is_empty() && !s.contains('\t') && !s.contains('\n') =>
                        {
                            vals.push(s.as_str())
                        }
                        _ => {
                            all_bare = false;
                            break;
                        }
                    }
                }
                if !all_bare {
                    continue;
                }
                // `@same` runs after this choice and elides any cell equal to the
                // one above it, so a candidate must be costed as the later pass will
                // actually leave it — otherwise a dictionary can win on paper and
                // lose in the emitted output. Mirrors that pass's gate exactly,
                // including the shapes it declines.
                let same_eligible = rows.len() >= 4 && var_keys.len() >= 2;
                let after_same = |cells: &[&str]| -> usize {
                    let total: usize = cells.iter().map(|c| c.len()).sum();
                    if !same_eligible {
                        return total;
                    }
                    let elidable: usize = (1..cells.len())
                        .filter(|&i| cells[i] == cells[i - 1])
                        .map(|i| cells[i].len())
                        .sum();
                    if elidable > k.len() + 1 {
                        total - elidable + k.len() + 1
                    } else {
                        total
                    }
                };
                let raw_cost = after_same(&vals);

                // `@dict`: the distinct values once (tab-joined), plus one index
                // per row. Only meaningful when something actually repeats.
                let mut distinct: Vec<&str> = Vec::new();
                let mut first_seen: std::collections::HashMap<&str, usize> =
                    std::collections::HashMap::new();
                for v in &vals {
                    if !first_seen.contains_key(v) {
                        first_seen.insert(v, distinct.len());
                        distinct.push(v);
                    }
                }
                let dict_cost = if distinct.len() < vals.len() {
                    let indices: Vec<String> =
                        vals.iter().map(|v| first_seen[v].to_string()).collect();
                    let idx_refs: Vec<&str> = indices.iter().map(|s| s.as_str()).collect();
                    "\n@dict : ".len()
                        + k.len()
                        + distinct.iter().map(|d| d.len()).sum::<usize>()
                        + distinct.len().saturating_sub(1)
                        + after_same(&idx_refs)
                } else {
                    usize::MAX
                };

                // `@prefix`/`@suffix`: each run is included only if emitting it once
                // beats leaving it on every row. The suffix is searched in the
                // residue the prefix leaves, so the two can never overlap — even on
                // a value they consume entirely. `longest_common_str_prefix` is
                // char-aligned, so slicing at its byte length is a valid boundary.
                let n = vals.len();
                let lcp = longest_common_str_prefix(&vals);
                let p_line = "\n@prefix : ".len() + k.len() + lcp.len();
                let lcp = if !lcp.is_empty() && lcp.len() * n > p_line {
                    lcp
                } else {
                    String::new()
                };
                let residue: Vec<&str> = vals.iter().map(|s| &s[lcp.len()..]).collect();
                let lcs = longest_common_str_suffix(&residue);
                let s_line = "\n@suffix : ".len() + k.len() + lcs.len();
                let lcs = if !lcs.is_empty() && lcs.len() * n > s_line {
                    lcs
                } else {
                    String::new()
                };
                let ps_cost = if lcp.is_empty() && lcs.is_empty() {
                    usize::MAX
                } else {
                    residue.iter().map(|s| s.len() - lcs.len()).sum::<usize>()
                        + if lcp.is_empty() { 0 } else { p_line }
                        + if lcs.is_empty() { 0 } else { s_line }
                };

                // Cheapest wins; comparisons are strict and ordered, so ties fall to
                // the simpler encoding (raw, then prefix/suffix).
                if dict_cost < raw_cost && dict_cost <= ps_cost {
                    let idx: std::collections::HashMap<String, usize> = distinct
                        .iter()
                        .enumerate()
                        .map(|(i, v)| ((*v).to_string(), i))
                        .collect();
                    dict_index.insert(k.clone(), idx);
                    dict_cols.insert(k.clone(), distinct.iter().map(|s| s.to_string()).collect());
                } else if ps_cost < raw_cost {
                    if !lcp.is_empty() {
                        prefix_cols.insert(k.clone(), lcp);
                    }
                    if !lcs.is_empty() {
                        suffix_cols.insert(k.clone(), lcs);
                    }
                }
            }
            // Delta encoding for large-valued, slowly-varying INTEGER columns
            // (timestamps, sequential ids): row 0 carries the absolute value, each
            // later row carries the difference from the previous row; a `@delta:`
            // line names the affected columns. Gated to fire only where it's a real
            // *token* win — the raw values must be multi-token (avg ≥4 decimal
            // digits; small ints are one token regardless) and the deltas must be
            // well under half the raw character count. Deltas use i128 (no
            // overflow); never collides with `@dict` (string-only) as this is
            // integer-only.
            let mut delta_cols: std::collections::BTreeMap<String, Vec<String>> =
                std::collections::BTreeMap::new();
            if rows.len() >= 4 {
                for k in &var_keys {
                    if dict_index.contains_key(k) {
                        continue;
                    }
                    let mut vals: Vec<i64> = Vec::with_capacity(rows.len());
                    let mut all_int = true;
                    for r in &rows {
                        match r.get(k) {
                            Some(Value::Int(n)) => vals.push(*n),
                            _ => {
                                all_int = false;
                                break;
                            }
                        }
                    }
                    if !all_int {
                        continue;
                    }
                    let raw_chars: usize = vals.iter().map(|v| v.to_string().len()).sum();
                    if raw_chars / vals.len() < 4 {
                        continue; // raws aren't multi-token — a delta saves nothing
                    }
                    let mut cells: Vec<String> = Vec::with_capacity(vals.len());
                    cells.push(vals[0].to_string());
                    let mut delta_chars = cells[0].len();
                    for i in 1..vals.len() {
                        let s = ((vals[i] as i128) - (vals[i - 1] as i128)).to_string();
                        delta_chars += s.len();
                        cells.push(s);
                    }
                    if delta_chars * 2 < raw_chars {
                        delta_cols.insert(k.clone(), cells);
                    }
                }
            }
            // Type tags for lossless decode (reliability): emitted only for the
            // columns where the compact form would be misread by inference — a
            // string that looks like a number/bool/null, or an integral float.
            // Dict columns are always strings and delta columns always integers,
            // so they never need a tag; this costs tokens only on real ambiguity.
            let mut type_tags: std::collections::BTreeMap<String, char> =
                std::collections::BTreeMap::new();
            for k in const_keys.iter().chain(var_keys.iter()) {
                if dict_index.contains_key(k)
                    || delta_cols.contains_key(k)
                    || prefix_cols.contains_key(k)
                    || suffix_cols.contains_key(k)
                {
                    continue;
                }
                let vals: Vec<&Value> = if const_keys.contains(k) {
                    vec![rows[0].get(k).unwrap_or(&Value::Null)]
                } else {
                    rows.iter()
                        .map(|r| r.get(k).unwrap_or(&Value::Null))
                        .collect()
                };
                if let Some(tag) = aecon_type_tag(&vals) {
                    type_tags.insert(k.clone(), tag);
                }
            }
            // Render every cell once, so repeat-elision below can be gated on the
            // characters it actually saves rather than on a guess.
            let mut matrix: Vec<Vec<String>> = rows
                .iter()
                .enumerate()
                .map(|(ri, r)| {
                    var_keys
                        .iter()
                        .map(|k| {
                            if let Some(col) = delta_cols.get(k) {
                                return col[ri].clone();
                            }
                            let v = r.get(k).unwrap_or(&Value::Null);
                            if let Value::Str(s) = v {
                                let p = prefix_cols.get(k).map_or(0, |p| p.len());
                                let sfx = suffix_cols.get(k).map_or(0, |x| x.len());
                                if p > 0 || sfx > 0 {
                                    // bare-safe and non-overlapping by construction.
                                    return s[p..s.len() - sfx].to_string();
                                }
                            }
                            match (dict_index.get(k), v) {
                                (Some(idx), Value::Str(s)) => idx
                                    .get(s)
                                    .map(|i| i.to_string())
                                    .unwrap_or_else(|| aecon_atom(v)),
                                _ => aecon_atom(v),
                            }
                        })
                        .collect()
                })
                .collect();

            // Repeat elision (`@same`): in a column that runs in blocks — the shape
            // of any sorted or grouped result — a cell identical to the one above it
            // is emitted as *nothing*. An empty cell is an unambiguous sentinel
            // because a genuinely empty string renders JSON-quoted (`""`). `@const`
            // already covers columns constant across every row; this covers the runs
            // `@const` cannot see. Excluded: `@delta` columns (whose running sum owns
            // the previous-row state), `@prefix`/`@suffix` columns (whose stripped
            // residue may legitimately be empty), and single-column tables — where
            // an all-elided row renders as a bare empty line. The decoder now reads
            // interior blank lines as rows, so that last exclusion is defence in
            // depth rather than the sole guard; it costs nothing, because a
            // single-column run is already `@dict`'s case.
            let mut same_cols: Vec<String> = Vec::new();
            if rows.len() >= 4 && var_keys.len() >= 2 {
                for (ci, k) in var_keys.iter().enumerate() {
                    if delta_cols.contains_key(k)
                        || prefix_cols.contains_key(k)
                        || suffix_cols.contains_key(k)
                    {
                        continue;
                    }
                    let saved: usize = (1..matrix.len())
                        .filter(|&ri| matrix[ri][ci] == matrix[ri - 1][ci])
                        .map(|ri| matrix[ri][ci].len())
                        .sum();
                    // Naming a column costs a tab plus its name; the `\n@same `
                    // marker is charged once, to the set, below.
                    if saved > k.len() + 1 {
                        same_cols.push(k.clone());
                    }
                }
                // The line only pays if the set as a whole beats its own overhead.
                let set_saved: usize = same_cols
                    .iter()
                    .filter_map(|k| var_keys.iter().position(|v| v == k))
                    .map(|ci| {
                        (1..matrix.len())
                            .filter(|&ri| matrix[ri][ci] == matrix[ri - 1][ci])
                            .map(|ri| matrix[ri][ci].len())
                            .sum::<usize>()
                    })
                    .sum();
                let set_cost: usize =
                    "\n@same ".len() + same_cols.iter().map(|k| k.len() + 1).sum::<usize>();
                if set_saved <= set_cost {
                    same_cols.clear();
                }
                // Reverse order: each comparison must see the previous row's
                // *un-elided* cell.
                for ci in same_cols
                    .iter()
                    .filter_map(|k| var_keys.iter().position(|v| v == k))
                    .collect::<Vec<_>>()
                {
                    for ri in (1..matrix.len()).rev() {
                        if matrix[ri][ci] == matrix[ri - 1][ci] {
                            matrix[ri][ci].clear();
                        }
                    }
                }
            }

            // Tight format: a bare tab-separated header line (the column schema),
            // optional `@const` (factored constants), `@dict` (low-cardinality
            // columns), `@prefix`/`@suffix` (shared leading/trailing runs), `@same`
            // (repeat-elided columns), `@delta:` (delta-encoded numeric columns) and
            // `@type` (lossless type tags) metadata lines, then positional
            // tab-separated rows. No `@aecon rows=N cols=` prefix — the header is
            // self-describing and ~7 tokens cheaper per result than the verbose form.
            let mut out = var_keys.join("\t");
            if !nest_keys.is_empty() {
                out.push_str("\n@nest ");
                out.push_str(&nest_keys.join("\t"));
            }
            if !const_keys.is_empty() {
                let consts: Vec<String> = const_keys
                    .iter()
                    .map(|k| {
                        format!(
                            "{}={}",
                            k,
                            aecon_atom(rows[0].get(k).unwrap_or(&Value::Null))
                        )
                    })
                    .collect();
                out.push_str("\n@const ");
                out.push_str(&consts.join("\t"));
            }
            for (col, distinct) in &dict_cols {
                out.push_str(&format!("\n@dict {}: ", col));
                out.push_str(&distinct.join("\t"));
            }
            for (col, prefix) in &prefix_cols {
                out.push_str(&format!("\n@prefix {}: {}", col, prefix));
            }
            for (col, suffix) in &suffix_cols {
                out.push_str(&format!("\n@suffix {}: {}", col, suffix));
            }
            if !same_cols.is_empty() {
                out.push_str("\n@same ");
                out.push_str(&same_cols.join("\t"));
            }
            if !delta_cols.is_empty() {
                out.push_str("\n@delta: ");
                let names: Vec<&str> = delta_cols.keys().map(|s| s.as_str()).collect();
                out.push_str(&names.join("\t"));
            }
            if !type_tags.is_empty() {
                out.push_str("\n@type ");
                let tags: Vec<String> = type_tags
                    .iter()
                    .map(|(k, t)| format!("{}:{}", k, t))
                    .collect();
                out.push_str(&tags.join("\t"));
            }
            for cells in &matrix {
                out.push('\n');
                out.push_str(&cells.join("\t"));
            }
            return out;
        }
    }

    match v {
        Value::Record(m) => {
            let pairs: Vec<String> = m
                .iter()
                .map(|(k, val)| format!("{}={}", k, aecon_item(val)))
                .collect();
            format!("{{{}}}", pairs.join(" "))
        }
        Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(aecon_item).collect();
            format!("[{}]", items.join(","))
        }
        other => aecon_atom(other),
    }
}

/// Render a value that sits inside a `[...]` or `{k=v}` container. A string there
/// is always JSON-quoted, however plain it looks, so the elements `a,b` and `1`
/// cannot read back as `[a,b,1]`. The quoted form is a valid JSON string, so
/// the whole `[...]` is valid JSON when it holds only strings, numbers and
/// booleans. A table cell stays bare: TSV already separates it.
fn aecon_item(v: &Value) -> String {
    match v {
        Value::Str(s) => serde_json::to_string(s).unwrap_or_else(|_| format!("{s:?}")),
        other => aecon_atom(other),
    }
}

/// Whether a bare string would be misread by `aecon_decode_atom` as a non-string
/// (number/bool/null) — i.e. it needs an explicit `s` type tag for lossless decode.
fn aecon_str_is_ambiguous(s: &str) -> bool {
    s == "null"
        || s == "true"
        || s == "false"
        || s.parse::<i64>().is_ok()
        || s.parse::<f64>().is_ok()
}

/// The type tag a column needs for lossless decode, or `None` if inference is
/// already exact. Only two cases are ambiguous in the compact form: an all-string
/// column containing a number/bool/null-looking value (`s`), and an all-float
/// column containing an integral value that renders without a `.` (`f`, which
/// inference would read back as `Int`). Mixed-variant columns return `None`
/// (best-effort — use `canonical` for those).
fn aecon_type_tag(vals: &[&Value]) -> Option<char> {
    if vals.is_empty() {
        return None;
    }
    if vals.iter().all(|v| matches!(v, Value::Str(_))) {
        let ambiguous = vals.iter().any(|v| match v {
            // Empty / tab / newline strings render JSON-quoted and decode exactly,
            // so only *bare* ambiguous strings need the tag.
            Value::Str(s) => {
                !s.is_empty() && !s.contains('\t') && !s.contains('\n') && aecon_str_is_ambiguous(s)
            }
            _ => false,
        });
        return ambiguous.then_some('s');
    }
    if vals.iter().all(|v| matches!(v, Value::Float(_))) {
        let ambiguous = vals.iter().any(|v| match v {
            Value::Float(f) => f.is_finite() && f.fract() == 0.0,
            _ => false,
        });
        return ambiguous.then_some('f');
    }
    None
}

/// Decode a cell honoring an explicit type tag (`s` → string, `f` → float),
/// falling back to inference when there is no tag.
fn aecon_decode_atom_typed(cell: &str, tag: Option<&char>) -> Value {
    match tag {
        Some('s') => {
            if cell.starts_with('"') {
                serde_json::from_str::<String>(cell)
                    .map(Value::Str)
                    .unwrap_or_else(|_| Value::Str(cell.to_string()))
            } else {
                Value::Str(cell.to_string())
            }
        }
        Some('f') => cell
            .parse::<f64>()
            .map(Value::Float)
            .unwrap_or_else(|_| aecon_decode_atom(cell)),
        _ => aecon_decode_atom(cell),
    }
}

/// Reverse `aecon_atom`: best-effort typed reconstruction of a single cell.
/// JSON-quoted cells (empty/tab/newline strings) are decoded exactly; otherwise
/// `null`/`true`/`false`/integer/float are recognized, falling back to a bare
/// string. The string↔number boundary is inferred (a string `"123"` decodes as
/// `Int`), exactly like CSV — for lossless typing use `canonical` (JSON).
fn aecon_decode_atom(cell: &str) -> Value {
    if cell.starts_with('"') {
        if let Ok(s) = serde_json::from_str::<String>(cell) {
            return Value::Str(s);
        }
    }
    // Composite values render as bare JSON, and `aecon_atom` quotes any *string*
    // that would open the same way, so a leading `{`/`[` unambiguously means one.
    if cell.starts_with('{') || cell.starts_with('[') {
        if let Ok(j) = serde_json::from_str::<serde_json::Value>(cell) {
            return Value::from_json(&j);
        }
    }
    match cell {
        "null" => return Value::Null,
        "true" => return Value::Bool(true),
        "false" => return Value::Bool(false),
        _ => {}
    }
    if let Ok(i) = cell.parse::<i64>() {
        return Value::Int(i);
    }
    if let Ok(f) = cell.parse::<f64>() {
        return Value::Float(f);
    }
    Value::Str(cell.to_string())
}

/// Rebuild the nested records that `@nest` flattened away. Only columns whose first
/// dotted segment is named in `nest` are rebuilt — every other key is kept verbatim,
/// so a column that merely *contains* a dot is never mistaken for a nested field.
fn aecon_unflatten(
    flat: BTreeMap<String, Value>,
    nest: &std::collections::HashSet<String>,
) -> BTreeMap<String, Value> {
    let mut out: BTreeMap<String, Value> = BTreeMap::new();
    for (k, v) in flat {
        let head = k.split('.').next().unwrap_or("");
        if !nest.contains(head) || !k.contains('.') {
            out.insert(k, v);
            continue;
        }
        let segments: Vec<&str> = k.split('.').collect();
        // Walk down, creating records as needed, and place the leaf at the bottom.
        let mut cursor = &mut out;
        for seg in &segments[..segments.len() - 1] {
            let entry = cursor
                .entry((*seg).to_string())
                .or_insert_with(|| Value::Record(BTreeMap::new()));
            if !matches!(entry, Value::Record(_)) {
                *entry = Value::Record(BTreeMap::new());
            }
            cursor = match entry {
                Value::Record(m) => m,
                _ => unreachable!("just forced to a record"),
            };
        }
        cursor.insert(segments[segments.len() - 1].to_string(), v);
    }
    out
}

/// Decode the tabular AECON form (header + optional `@const`/`@dict`/`@delta`/
/// `@prefix`/`@suffix`/`@same`/`@type` metadata lines + positional rows) back to an
/// `Array<Record>`.
/// Inverse of the tabular branch of `aecon_render`: `@const` columns are restored to
/// every row, `@dict` indices are resolved to their string values, `@delta` columns
/// are reconstructed by running sum, `@prefix`/`@suffix` columns get their shared
/// runs re-attached, `@same` columns resolve an empty cell to the row above, and
/// `@type` tags force the exact type of columns
/// the compact form would otherwise infer wrongly (numeric-looking strings,
/// integral floats) — making the round-trip lossless. Returns the parsed array;
/// non-tabular input (a single `{k=v}` record, a scalar array, or a bare scalar)
/// is returned as a best-effort single value. A `@delta` cell that is not an
/// integer is refused: read as 0, it shifted every later row of its column.
fn aecon_decode(s: &str) -> Result<Value> {
    let lines: Vec<&str> = s.split('\n').collect();
    if lines.is_empty() {
        return Ok(Value::Null);
    }
    let header = lines[0];
    // Non-tabular fallbacks: a single record / scalar array / bare scalar.
    if !header.contains('\t') && (header.starts_with('{') || header.starts_with('[')) {
        return Ok(aecon_decode_atom(header));
    }
    let var_keys: Vec<String> = header.split('\t').map(|s| s.to_string()).collect();

    // `@const` is decoded *after* the metadata loop because `@type` (which can
    // correct a const's inferred type) is emitted after it; collect the raw
    // key=value pairs first, then apply tags.
    let mut const_raw: Vec<(String, String)> = Vec::new();
    let mut dicts: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();
    let mut prefixes: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    let mut suffixes: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    let mut same_set: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut nest_set: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut delta_set: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut type_tags: std::collections::HashMap<String, char> = std::collections::HashMap::new();
    let mut row_start = 1;
    for (i, line) in lines.iter().enumerate().skip(1) {
        if let Some(rest) = line.strip_prefix("@const ") {
            for kv in rest.split('\t') {
                if let Some((k, v)) = kv.split_once('=') {
                    const_raw.push((k.to_string(), v.to_string()));
                }
            }
        } else if let Some(rest) = line.strip_prefix("@dict ") {
            if let Some((col, vals)) = rest.split_once(": ") {
                dicts.insert(
                    col.to_string(),
                    vals.split('\t').map(|s| s.to_string()).collect(),
                );
            }
        } else if let Some(rest) = line.strip_prefix("@prefix ") {
            if let Some((col, p)) = rest.split_once(": ") {
                prefixes.insert(col.to_string(), p.to_string());
            }
        } else if let Some(rest) = line.strip_prefix("@suffix ") {
            if let Some((col, p)) = rest.split_once(": ") {
                suffixes.insert(col.to_string(), p.to_string());
            }
        } else if let Some(rest) = line.strip_prefix("@same ") {
            for c in rest.split('\t') {
                same_set.insert(c.to_string());
            }
        } else if let Some(rest) = line.strip_prefix("@nest ") {
            for c in rest.split('\t') {
                nest_set.insert(c.to_string());
            }
        } else if let Some(rest) = line.strip_prefix("@delta: ") {
            for c in rest.split('\t') {
                delta_set.insert(c.to_string());
            }
        } else if let Some(rest) = line.strip_prefix("@type ") {
            for spec in rest.split('\t') {
                if let Some((col, tag)) = spec.rsplit_once(':') {
                    if let Some(c) = tag.chars().next() {
                        type_tags.insert(col.to_string(), c);
                    }
                }
            }
        } else {
            row_start = i;
            break;
        }
        row_start = i + 1;
    }
    let consts: Vec<(String, Value)> = const_raw
        .iter()
        .map(|(k, v)| (k.clone(), aecon_decode_atom_typed(v, type_tags.get(k))))
        .collect();

    // Running absolute value per delta column, advanced as rows are read in order.
    let mut delta_run: std::collections::HashMap<String, i128> = std::collections::HashMap::new();
    // Last emitted value per `@same` column, so an elided (empty) cell resolves to
    // the row above it.
    let mut prev_same: std::collections::HashMap<String, Value> = std::collections::HashMap::new();
    let mut out_rows: Vec<Value> = Vec::new();
    // Trailing blank lines are formatting; an *interior* blank line is a real row
    // whose every cell was factored away — a single-column table whose value equals
    // its `@prefix`+`@suffix` renders exactly that way. Trim the former so the
    // latter is not silently dropped.
    let mut row_end = lines.len();
    while row_end > row_start && lines[row_end - 1].is_empty() {
        row_end -= 1;
    }
    for line in &lines[row_start..row_end] {
        let cells: Vec<&str> = line.split('\t').collect();
        let mut m = BTreeMap::new();
        for (ci, k) in var_keys.iter().enumerate() {
            let cell = cells.get(ci).copied().unwrap_or("");
            let val = if same_set.contains(k) && cell.is_empty() && prev_same.contains_key(k) {
                prev_same[k].clone()
            } else if delta_set.contains(k) {
                let n: i128 = cell.parse().map_err(|_| {
                    crate::safety::bad_arg(
                        "aecon_decode",
                        &format!("an integer in @delta column {k}"),
                        cell,
                    )
                })?;
                let abs = match delta_run.get(k) {
                    Some(prev) => prev + n, // later rows carry the difference
                    None => n,              // row 0 carries the absolute value
                };
                delta_run.insert(k.clone(), abs);
                let abs = i64::try_from(abs).map_err(|_| {
                    crate::safety::bad_arg(
                        "aecon_decode",
                        &format!("@delta column {k} to stay within Int"),
                        &abs.to_string(),
                    )
                })?;
                Value::Int(abs)
            } else if let Some(values) = dicts.get(k) {
                match cell.parse::<usize>().ok().and_then(|i| values.get(i)) {
                    Some(s) => Value::Str(s.clone()),
                    None => aecon_decode_atom(cell),
                }
            } else if prefixes.contains_key(k) || suffixes.contains_key(k) {
                let prefix = prefixes.get(k).map(String::as_str).unwrap_or("");
                let suffix = suffixes.get(k).map(String::as_str).unwrap_or("");
                Value::Str(format!("{prefix}{cell}{suffix}"))
            } else {
                aecon_decode_atom_typed(cell, type_tags.get(k))
            };
            if same_set.contains(k) {
                prev_same.insert(k.clone(), val.clone());
            }
            m.insert(k.clone(), val);
        }
        for (k, v) in &consts {
            m.insert(k.clone(), v.clone());
        }
        out_rows.push(Value::Record(if nest_set.is_empty() {
            m
        } else {
            aecon_unflatten(m, &nest_set)
        }));
    }
    Ok(Value::Array(out_rows))
}

/// Token count used by the token-economy builtins (`tokens`/`budget`/`digest`)
/// and the Agent API accounting. With `--features real-tokens` this is the
/// **real GPT-4 cl100k BPE** (vocab embedded in `tiktoken-rs`); otherwise a
/// labeled heuristic (alphanumeric run ≈ ceil(len/4) tokens; each symbol ≈ 1).
#[cfg(feature = "real-tokens")]
pub fn est_token_count(s: &str) -> usize {
    use std::sync::OnceLock;
    static BPE: OnceLock<tiktoken_rs::CoreBPE> = OnceLock::new();
    let bpe = BPE.get_or_init(|| tiktoken_rs::cl100k_base().expect("load cl100k_base"));
    bpe.encode_with_special_tokens(s).len()
}

#[cfg(not(feature = "real-tokens"))]
pub fn est_token_count(s: &str) -> usize {
    let mut toks = 0usize;
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c.is_whitespace() {
            continue;
        }
        if c.is_alphanumeric() || c == '_' {
            let mut len = 1usize;
            while let Some(&n) = chars.peek() {
                if n.is_alphanumeric() || n == '_' {
                    len += 1;
                    chars.next();
                } else {
                    break;
                }
            }
            toks += len.div_ceil(4).max(1);
        } else {
            toks += 1;
        }
    }
    toks
}

/// aecon(value?) - Render a value (argument or piped input) as compact AECON
/// text. Saves output tokens on homogeneous record arrays by emitting keys once.
fn bi_aecon(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let v = args.into_iter().next().or(input).ok_or_else(|| {
        crate::safety::bad_arg("aecon", "a value (argument or piped input)", "nothing")
    })?;
    Ok(Value::Str(aecon_render(&v)))
}

/// aecon_decode(text?) - Parse tabular AECON text (argument or piped input) back
/// into an `Array<Record>`, reversing `@const`/`@dict`/`@delta`/`@prefix`/`@suffix`/
/// `@same` factoring.
/// The inverse of `aecon` for homogeneous tables; the string↔number boundary is
/// inferred (use `canonical` for lossless typing).
fn bi_aecon_decode(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let v = args.into_iter().next().or(input).ok_or_else(|| {
        crate::safety::bad_arg(
            "aecon_decode",
            "AECON text (argument or piped input)",
            "nothing",
        )
    })?;
    let s = match v {
        Value::Str(s) => s,
        other => {
            return Err(crate::safety::bad_arg(
                "aecon_decode",
                "a String of AECON text",
                &format!("{:?}", other),
            ))
        }
    };
    aecon_decode(&s)
}

/// tokens(value?) - Estimate the token count of a value's rendered form (its
/// string content if a String, else its display form). Pair with `aecon` to
/// compare output costs, e.g. `tokens(v)` vs `tokens(aecon(v))`.
fn bi_tokens(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let v = args.into_iter().next().or(input).ok_or_else(|| {
        crate::safety::bad_arg("tokens", "a value (argument or piped input)", "nothing")
    })?;
    let s = match &v {
        Value::Str(s) => s.clone(),
        other => other.to_display_string(),
    };
    Ok(Value::Int(est_token_count(&s) as i64))
}

/// A compact structural type descriptor for a value: a Record maps each key to
/// its type name; an Array reports its element type; a scalar reports its type.
/// Lets `digest` convey shape in a handful of tokens.
fn value_shape(v: &Value) -> Value {
    match v {
        Value::Record(m) => Value::Record(
            m.iter()
                .map(|(k, val)| (k.clone(), Value::Str(val.type_name().to_string())))
                .collect(),
        ),
        Value::Array(a) => Value::Str(format!(
            "Array<{}>",
            a.first().map(|e| e.type_name()).unwrap_or("Any")
        )),
        other => Value::Str(other.type_name().to_string()),
    }
}

/// digest(value?) - A constant-token structural summary of a value: its kind,
/// size, element/field shape, a 2-element sample, and the token cost of the full
/// value (default render vs compact AECON). Lets an agent understand a large
/// result's shape and size cheaply, then decide whether to page (`budget`),
/// compact (`aecon`), or skip it — maximal information per token.
fn bi_digest(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let v = args.into_iter().next().or(input).ok_or_else(|| {
        crate::safety::bad_arg("digest", "a value (argument or piped input)", "nothing")
    })?;
    let mut r = BTreeMap::new();
    match &v {
        Value::Array(a) => {
            r.insert("kind".to_string(), Value::Str("array".to_string()));
            r.insert("len".to_string(), Value::Int(a.len() as i64));
            if let Some(first) = a.first() {
                r.insert("element".to_string(), value_shape(first));
            }
            r.insert(
                "sample".to_string(),
                Value::Array(a.iter().take(2).cloned().collect()),
            );
        }
        Value::Table(t) => {
            r.insert("kind".to_string(), Value::Str("table".to_string()));
            r.insert("rows".to_string(), Value::Int(t.rows.len() as i64));
            r.insert(
                "cols".to_string(),
                Value::Array(t.schema.iter().map(|c| Value::Str(c.clone())).collect()),
            );
            r.insert(
                "sample".to_string(),
                Value::Array(
                    t.rows
                        .iter()
                        .take(2)
                        .map(|row| Value::Record(row.clone()))
                        .collect(),
                ),
            );
        }
        Value::Record(m) => {
            r.insert("kind".to_string(), Value::Str("record".to_string()));
            r.insert("keys".to_string(), Value::Int(m.len() as i64));
            r.insert("shape".to_string(), value_shape(&v));
        }
        Value::Str(s) => {
            r.insert("kind".to_string(), Value::Str("string".to_string()));
            r.insert("len".to_string(), Value::Int(s.chars().count() as i64));
            r.insert(
                "preview".to_string(),
                Value::Str(s.chars().take(60).collect::<String>()),
            );
        }
        other => {
            r.insert(
                "kind".to_string(),
                Value::Str(other.type_name().to_string()),
            );
            r.insert("value".to_string(), other.clone());
        }
    }
    r.insert(
        "full_tokens".to_string(),
        Value::Int(est_token_count(&v.to_display_string()) as i64),
    );
    r.insert(
        "compact_tokens".to_string(),
        Value::Int(est_token_count(&aecon_render(&v)) as i64),
    );
    Ok(Value::Record(r))
}

/// Project a record to only the named fields (in the given order, skipping
/// fields that don't exist).
fn pick_record(m: &BTreeMap<String, Value>, fields: &[String]) -> Value {
    let mut out = BTreeMap::new();
    for f in fields {
        if let Some(v) = m.get(f) {
            out.insert(f.clone(), v.clone());
        }
    }
    Value::Record(out)
}

/// pick(value?, fields...) - Source-side projection: keep only the named fields
/// of each record (an array of records, a single record, or a table), dropping
/// the rest *before* rendering. The biggest output-token saver — pair with
/// `aecon`: `data | pick("name", "size") | aecon`. With piped input the args are
/// the field names; otherwise the first arg is the value.
fn bi_pick(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let collect_fields = |vals: &[Value]| -> Vec<String> {
        vals.iter()
            .filter_map(|a| match a {
                Value::Str(s) => Some(s.clone()),
                _ => None,
            })
            .collect()
    };
    let (value, fields) = if let Some(inp) = input {
        (inp, collect_fields(&args))
    } else {
        let value = args
            .first()
            .cloned()
            .ok_or_else(|| crate::safety::bad_arg("pick", "value, fields: String...", "nothing"))?;
        (value, collect_fields(&args[1..]))
    };
    if fields.is_empty() {
        return Err(crate::safety::bad_arg(
            "pick",
            "at least one field name",
            "none",
        ));
    }
    // The subject is an Array of Records or a single Record. Anything else is
    // refused: passing it through unchanged made `pick("a", "b")` return "a".
    let result = match value {
        Value::Array(a) => {
            let mut rows = Vec::with_capacity(a.len());
            for (i, e) in a.iter().enumerate() {
                match e {
                    Value::Record(m) => rows.push(pick_record(m, &fields)),
                    other => {
                        return Err(crate::safety::bad_arg(
                            "pick",
                            "an Array of Records",
                            &format!("element {i} as {}", other.type_name()),
                        ))
                    }
                }
            }
            Value::Array(rows)
        }
        Value::Record(m) => pick_record(&m, &fields),
        Value::Table(t) => Value::Array(t.rows.iter().map(|m| pick_record(m, &fields)).collect()),
        other => {
            return Err(crate::safety::bad_arg(
                "pick",
                "an Array of Records or a Record",
                other.type_name(),
            ))
        }
    };
    Ok(result)
}

/// JSON-escape and quote a string (delegates to serde_json for correctness).
fn json_quote(s: &str) -> String {
    serde_json::to_string(s).unwrap_or_else(|_| format!("{:?}", s))
}

/// Write a Value as canonical JSON: deterministic and byte-stable across
/// platforms/locale. Record keys are emitted in sorted order (Records are
/// BTreeMaps); floats use Rust's shortest round-trip, locale-independent
/// formatting; non-finite floats and non-serializable values (lambdas/futures)
/// become explicit sentinels so output never varies or fails.
fn canonical_write(v: &Value, out: &mut String) {
    match v {
        Value::Null => out.push_str("null"),
        Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        Value::Int(n) => out.push_str(&n.to_string()),
        Value::Float(f) => {
            if f.is_finite() {
                out.push_str(&format!("{}", f));
            } else {
                out.push_str("null"); // NaN/Inf are not representable in JSON
            }
        }
        Value::Str(s) | Value::Uri(s) => out.push_str(&json_quote(s)),
        Value::Array(a) => {
            out.push('[');
            for (i, e) in a.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                canonical_write(e, out);
            }
            out.push(']');
        }
        Value::Record(m) => {
            out.push('{');
            for (i, (k, val)) in m.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&json_quote(k));
                out.push(':');
                canonical_write(val, out);
            }
            out.push('}');
        }
        Value::Table(t) => {
            // Canonical object with keys in sorted order: "rows" then "schema".
            out.push_str("{\"rows\":[");
            for (i, r) in t.rows.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push('{');
                for (j, (k, val)) in r.iter().enumerate() {
                    if j > 0 {
                        out.push(',');
                    }
                    out.push_str(&json_quote(k));
                    out.push(':');
                    canonical_write(val, out);
                }
                out.push('}');
            }
            out.push_str("],\"schema\":[");
            for (i, c) in t.schema.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&json_quote(c));
            }
            out.push_str("]}");
        }
        Value::Lambda(_) | Value::AsyncLambda(_) | Value::Future(_) => out.push_str("null"),
        Value::Error(msg) => {
            out.push_str("{\"error\":");
            out.push_str(&json_quote(msg));
            out.push('}');
        }
        Value::Builtin(b) => {
            out.push_str("{\"builtin\":");
            out.push_str(&json_quote(&b.name));
            out.push('}');
        }
    }
}

fn canonical_render(v: &Value) -> String {
    let mut out = String::new();
    canonical_write(v, &mut out);
    out
}

/// canonical(value?) - Render a value as canonical JSON: deterministic and
/// byte-identical for equal values across OS/locale (sorted keys, shortest
/// round-trip floats, explicit null for non-finite/non-serializable). The
/// lossless counterpart to `aecon`; the basis for reproducible output/diffs.
fn bi_canonical(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let v = args.into_iter().next().or(input).ok_or_else(|| {
        crate::safety::bad_arg("canonical", "a value (argument or piped input)", "nothing")
    })?;
    Ok(Value::Str(canonical_render(&v)))
}

/// Budget a rendered string to `max` estimated tokens, never silently lossy:
/// over budget → keep a prefix and append an explicit elision marker.
fn budget_string_record(s: &str, max: usize) -> Value {
    let total = est_token_count(s);
    let mut r = BTreeMap::new();
    if total <= max {
        r.insert("page".to_string(), Value::Str(s.to_string()));
        r.insert("truncated".to_string(), Value::Bool(false));
        r.insert("page_tokens".to_string(), Value::Int(total as i64));
        r.insert("total_tokens".to_string(), Value::Int(total as i64));
        r.insert("elided_chars".to_string(), Value::Int(0));
    } else {
        let keep = max.saturating_mul(4); // ~4 chars/token heuristic
        let prefix: String = s.chars().take(keep).collect();
        let elided = s.chars().count().saturating_sub(keep);
        let page = format!("{}…({} more chars elided)", prefix, elided);
        let page_tokens = est_token_count(&page);
        r.insert("page".to_string(), Value::Str(page));
        r.insert("truncated".to_string(), Value::Bool(true));
        r.insert("page_tokens".to_string(), Value::Int(page_tokens as i64));
        r.insert("total_tokens".to_string(), Value::Int(total as i64));
        r.insert("elided_chars".to_string(), Value::Int(elided as i64));
    }
    Value::Record(r)
}

/// budget(value?, max_tokens, cursor?) - Render a value to fit within an
/// estimated token budget, never silently lossy. For arrays/tables it returns a
/// page of rows starting at `cursor` plus paging metadata (`next_cursor`,
/// `elided`, `total`, `page_tokens`); for other values it truncates the AECON
/// rendering with an explicit elision marker. With piped input the args are
/// `(max_tokens, cursor?)`; otherwise `(value, max_tokens, cursor?)`.
fn bi_budget(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let mut args = args.into_iter();
    let value = input
        .or_else(|| args.next())
        .ok_or_else(|| crate::safety::arg_err("budget requires value and max_tokens"))?;
    let max = rl_positive_size(
        "budget max_tokens",
        &args
            .next()
            .ok_or_else(|| crate::safety::arg_err("budget requires max_tokens"))?,
    )?;
    let cursor = match args.next() {
        None => 0,
        Some(Value::Int(n)) => usize::try_from(n).map_err(|_| {
            crate::safety::arg_err("budget cursor must be a nonnegative representable Int")
        })?,
        Some(_) => {
            return Err(crate::safety::arg_err(
                "budget cursor must be a nonnegative Int",
            ))
        }
    };
    if !matches!(&value, Value::Array(_) | Value::Table(_)) && cursor != 0 {
        return Err(crate::safety::arg_err(
            "budget nonzero cursor requires Array or Table",
        ));
    }
    Ok(budget_value(&value, max, cursor))
}

/// Core of `budget`: render `value` to fit ~`max` estimated tokens, paging
/// arrays/tables from `cursor` (with metadata) and truncating other values'
/// AECON rendering losslessly. Public so the REPL can apply `IRONSHELL_TOKEN_BUDGET`.
pub fn budget_value(value: &Value, max: usize, cursor: usize) -> Value {
    let total = match value {
        Value::Table(t) => t.rows.len(),
        Value::Array(a) => a.len(),
        other => return budget_string_record(&aecon_render(other), max),
    };
    let start = cursor.min(total);
    let mut end = start;
    let mut used = 0usize;
    while end < total {
        // Conservative per-row estimate (a single record renders with its keys;
        // the final page shares one header, so this never under-counts).
        let rendered = match value {
            Value::Table(t) => aecon_render(&Value::Record(t.rows[end].clone())),
            Value::Array(a) => aecon_render(&a[end]),
            _ => unreachable!("row value was checked"),
        };
        let row_tok = est_token_count(&rendered);
        if end > start && (used > max || row_tok > max.saturating_sub(used)) {
            break;
        }
        used = used.saturating_add(row_tok);
        end += 1;
    }
    if end == start && total > start {
        end = start + 1; // always make progress, even on a single oversized row
    }

    let page_slice = Value::Array(match value {
        Value::Table(t) => t.rows[start..end]
            .iter()
            .cloned()
            .map(Value::Record)
            .collect(),
        Value::Array(a) => a[start..end].to_vec(),
        _ => unreachable!("row value was checked"),
    });
    let page_str = aecon_render(&page_slice);
    let page_tokens = est_token_count(&page_str);
    let shown = end - start;

    let mut r = BTreeMap::new();
    r.insert("page".to_string(), Value::Str(page_str));
    r.insert("shown".to_string(), Value::Int(shown as i64));
    r.insert("from".to_string(), Value::Int(start as i64));
    r.insert("total".to_string(), Value::Int(total as i64));
    r.insert("elided".to_string(), Value::Int((total - end) as i64));
    r.insert("page_tokens".to_string(), Value::Int(page_tokens as i64));
    r.insert(
        "next_cursor".to_string(),
        if end < total {
            Value::Int(end as i64)
        } else {
            Value::Null
        },
    );
    r.insert(
        "truncated".to_string(),
        Value::Bool(end < total || start > 0),
    );
    Value::Record(r)
}

/// Render a result for **agent mode** (`IRONSHELL_MODE=agent`): compact, deterministic
/// AECON instead of the human pretty-printer (no ANSI, keys emitted once, the
/// four structural levers applied). `Null` prints nothing and a bare `Str` is
/// returned raw (a single field value is what the agent asked for). When a token
/// budget is set, the value is paged via `budget_value` and rendered as the AECON
/// page followed by one compact `@page …` metadata line (`shown`/`total`/`elided`/
/// `next_cursor`/…), avoiding the double-encoding that pretty-printing the
/// envelope record would cause.
pub fn render_agent(v: &Value, budget: Option<usize>) -> Option<String> {
    // Scrub secret shapes from the value before it enters the agent's context
    // window (§7.6). Agent-path only — the human pretty-printer keeps full
    // fidelity. Opt out with IRONSHELL_REDACT=off.
    // Owned when redacted, so a handle can take it without a copy. With
    // redaction off the caller's value is borrowed and a handle copies it once.
    let v = if crate::safety::redaction_enabled() {
        std::borrow::Cow::Owned(redact_value(v))
    } else {
        std::borrow::Cow::Borrowed(v)
    };
    match v.as_ref() {
        Value::Null => None,
        Value::Str(s) => Some(s.clone()),
        _ => {
            let full = match budget {
                Some(max) if max > 0 => render_budget_envelope(&budget_value(v.as_ref(), max, 0)),
                _ => aecon_render(v.as_ref()),
            };
            // A result too large to be worth sending whole is kept server-side
            // and referenced instead. The agent narrows it down with a pipeline
            // and only the small answer crosses back — the saving no encoder can
            // reach, because it is the bytes never sent.
            let whole = crate::handles::take_show_whole();
            if !whole && crate::handles::worth_handling(v.as_ref(), full.len()) {
                match render_handle(v.into_owned(), full.len()) {
                    Ok(handle) => Some(handle),
                    // At the handle cap the result is not sent: it is over the
                    // budget, which is why it was being handled. The refusal says
                    // so and how large it was, rather than flooding the output.
                    Err(e) => Some(format!(
                        "@handle refused: {e}\nthe result ({} bytes) is over the output budget and was not shown; release a handle with handle_drop(id) and run it again",
                        full.len()
                    )),
                }
            } else {
                Some(full)
            }
        }
    }
}

/// The hint for a bad bare step count. A bare Int counts steps; an id needs the
/// Record form. Spelled out because the two read alike.
const UNDO_STEP_HINT: &str =
    "undo(n) undoes the last n steps; to undo the step with id n, write undo({id: n})";

/// `undo(n = 1)` — put back what the last `n` mutating steps overwrote.
///
/// Returns one record per step, **including the ones it could not reverse**.
/// The counts are reported separately because "3 restored" and "3 restored, 1
/// irreversible" call for different decisions, and collapsing them is how a
/// partial recovery gets mistaken for a complete one.
// Each refuses pipeline input in its body rather than in its dispatch arm:
// tests/fallback_dispatch.rs reads the arms as `name => bi_fn(..)` pairs.
fn bi_undo(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_pipeline_input("undo", &input)?;
    if let Some(id) = undo_id("undo", &args)? {
        // An id names one step, so a step count next to it would say what else to take.
        if args.iter().any(|v| !matches!(v, Value::Record(_))) {
            return Err(crate::safety::arg_err(
                "undo takes a step count or an id, not both",
            ));
        }
        let force = undo_force("undo", &args)?;
        refuse_unless_recording("undo")?;
        return undo_by_id_record("undo", id, force);
    }
    let n = match args.iter().find(|v| !matches!(v, Value::Record(_))) {
        None => 1,
        Some(Value::Int(n)) if *n < 0 => {
            return Err(crate::safety::bad_arg_with_hint(
                "undo",
                "a step count from 0",
                &n.to_string(),
                UNDO_STEP_HINT,
            ))
        }
        Some(v) => v
            .as_int()
            .map_err(|_| {
                crate::safety::bad_arg_with_hint(
                    "undo",
                    "a step count",
                    "a non-integer",
                    UNDO_STEP_HINT,
                )
            })?
            .max(0) as usize,
    };
    let force = undo_force("undo", &args)?;
    refuse_unless_recording("undo")?;
    undo_record("undo", n, force)
}

/// The `force` option of undo and session_undo: `undo({force: true})`, or the
/// same record after a step count. Restores a file a hand edit changed after
/// its step, which the undo would otherwise refuse.
fn undo_force(builtin: &str, args: &[Value]) -> Result<bool> {
    let mut force = false;
    for arg in args {
        if let Value::Record(options) = arg {
            for (key, value) in options {
                match (key.as_str(), value) {
                    ("force", Value::Bool(flag)) => force = *flag,
                    ("force", other) => {
                        return Err(crate::safety::bad_arg(
                            builtin,
                            "force: Bool",
                            other.type_name(),
                        ))
                    }
                    // Read by undo_id, which takes the id of one step.
                    ("id", _) if builtin == "undo" => {}
                    _ => {
                        return Err(crate::safety::arg_err(format!(
                            "{builtin} unknown option {key}"
                        )))
                    }
                }
            }
        }
    }
    Ok(force)
}

/// Undo `n` steps and render the record. A refused first step is an error that
/// names the file and the way past the refusal; nothing was undone.
fn undo_record(builtin: &str, n: usize, force: bool) -> Result<Value> {
    let force_call = format!("{builtin}({{force: true}})");
    let outcomes = crate::journal::undo(n, force)
        .map_err(|(path, removed)| changed_refusal(builtin, &path, removed, &force_call))?;
    Ok(Value::Record(rewind_record(&outcomes, "restored")))
}

/// The `id` option of undo: `undo({id: N})` names one journal entry by the `seq`
/// its journal row shows. `None` when no argument names an id.
fn undo_id(builtin: &str, args: &[Value]) -> Result<Option<usize>> {
    let mut id = None;
    for arg in args {
        let Value::Record(options) = arg else {
            continue;
        };
        let Some(value) = options.get("id") else {
            continue;
        };
        let parsed = match value {
            Value::Int(n) if *n >= 1 => Some(*n as usize),
            Value::Str(s) => s.trim().parse::<usize>().ok().filter(|n| *n >= 1),
            _ => None,
        };
        match parsed {
            Some(n) => id = Some(n),
            None => {
                return Err(crate::safety::bad_arg(
                    builtin,
                    "id: the Int id a journal row shows, from 1",
                    &value.to_display_string(),
                ))
            }
        }
    }
    Ok(id)
}

/// Undo the one journal entry `seq`, and render the record as `undo` does.
fn undo_by_id_record(builtin: &str, seq: usize, force: bool) -> Result<Value> {
    use crate::journal::UndoRefusal;
    let force_call = format!("{builtin}({{id: {seq}, force: true}})");
    let outcomes = crate::journal::undo_by_id(seq, force).map_err(|refusal| match refusal {
        UndoRefusal::NotFound => crate::safety::journal_step_not_found(builtin, seq),
        UndoRefusal::LaterStep { seq: later, path } => crate::safety::bad_state_with_hint(
            builtin,
            &format!(
                "entry {seq} changed {path}, and later entry {later} changed it too; undoing {seq} would also undo that change"
            ),
            &format!(
                "{builtin}({{id: {later}}}) first, or {force_call} to undo {seq} anyway"
            ),
        ),
        UndoRefusal::Changed { path, removed } => {
            changed_refusal(builtin, &path, removed, &force_call)
        }
    })?;
    Ok(Value::Record(rewind_record(&outcomes, "restored")))
}

/// The refusal for a file that changed (or was removed) after its step. `force_call`
/// is the call that restores the file anyway, named in the hint.
fn changed_refusal(builtin: &str, path: &str, removed: bool, force_call: &str) -> anyhow::Error {
    if removed {
        crate::safety::bad_state_with_hint(
            builtin,
            &format!("{path} was removed after this step; undoing would recreate it"),
            &format!("{force_call} recreates it anyway"),
        )
    } else {
        crate::safety::bad_state_with_hint(
            builtin,
            &format!("{path} changed after this step; undoing would discard those changes"),
            &format!("read the file, or {force_call} to restore it anyway"),
        )
    }
}

/// Refuse an undo or a redo when the journal is not recording in this session.
///
/// The journal records a write only in agent mode or with IRONSHELL_JOURNAL=on.
/// In a human session nothing was recorded, so `undo()` answered
/// `complete: true` with nothing restored, and the file kept the write it was
/// meant to reverse. That reads as success. The refusal names the switch.
fn refuse_unless_recording(builtin: &str) -> Result<()> {
    if crate::journal::enabled() {
        return Ok(());
    }
    Err(crate::safety::bad_state_with_hint(
        builtin,
        "the journal is not recording in this session, so no write was recorded and there is nothing to undo or redo",
        "start the shell with --agent (or set IRONSHELL_MODE=agent), or set IRONSHELL_JOURNAL=on before the writes you want to reverse; a write made while it is off is not recorded",
    ))
}

/// The record shared by `undo` and `session_redo`: one count per outcome, the
/// steps themselves, and `complete`. `applied_key` names the count of steps
/// that were put back (`restored` for undo, `reapplied` for redo).
///
/// Every outcome is counted and listed, including the ones that could not be
/// applied. The counts are kept apart because "3 restored" and "3 restored, 1
/// skipped" call for different decisions.
fn rewind_record(
    outcomes: &[crate::journal::Rewound],
    applied_key: &str,
) -> std::collections::BTreeMap<String, Value> {
    let (mut applied, mut removed, mut skipped, mut failed) = (0, 0, 0, 0);
    let mut rows = Vec::with_capacity(outcomes.len());
    for r in outcomes {
        let mut m = std::collections::BTreeMap::new();
        // The step's id, as journal() and session_history() name it.
        if let Some(seq) = r.seq {
            m.insert("seq".to_string(), Value::Int(seq as i64));
        }
        let (action, what, why) = match &r.outcome {
            crate::journal::Outcome::Restored(w) => {
                applied += 1;
                ("restored", w.clone(), String::new())
            }
            crate::journal::Outcome::Reapplied(w) => {
                applied += 1;
                ("reapplied", w.clone(), String::new())
            }
            crate::journal::Outcome::Removed(w) => {
                removed += 1;
                ("removed", w.clone(), String::new())
            }
            crate::journal::Outcome::Skipped { what, why } => {
                skipped += 1;
                ("skipped", what.clone(), why.clone())
            }
            crate::journal::Outcome::Failed { what, why } => {
                failed += 1;
                ("failed", what.clone(), why.clone())
            }
        };
        m.insert("action".to_string(), Value::Str(action.to_string()));
        m.insert("what".to_string(), Value::Str(what));
        if !why.is_empty() {
            m.insert("why".to_string(), Value::Str(why));
        }
        rows.push(Value::Record(m));
    }

    let mut out = std::collections::BTreeMap::new();
    out.insert(applied_key.to_string(), Value::Int(applied));
    out.insert("removed".to_string(), Value::Int(removed));
    out.insert("skipped".to_string(), Value::Int(skipped));
    out.insert("failed".to_string(), Value::Int(failed));
    out.insert("steps".to_string(), Value::Array(rows));
    // Say it in words as well as counts: a caller that reads only the summary
    // still learns the world was not fully restored.
    out.insert(
        "complete".to_string(),
        Value::Bool(skipped == 0 && failed == 0),
    );
    out
}

/// The rows `journal()` and `session_history()` report for done steps.
fn journal_rows(entries: &[crate::journal::Entry]) -> Vec<Value> {
    entries
        .iter()
        .map(|e| {
            let mut m = std::collections::BTreeMap::new();
            // `id` is the value undo({id: N}) takes; `seq` is the same number.
            m.insert("id".to_string(), Value::Int(e.seq as i64));
            m.insert("seq".to_string(), Value::Int(e.seq as i64));
            m.insert("builtin".to_string(), Value::Str(e.builtin.clone()));
            m.insert("effect".to_string(), Value::Str(e.effect.clone()));
            if !e.path.is_empty() {
                m.insert("path".to_string(), Value::Str(e.path.clone()));
            }
            m.insert("reversible".to_string(), Value::Bool(e.reversible()));
            if let crate::journal::Before::Irreversible(why) = &e.before {
                m.insert("why".to_string(), Value::Str(why.clone()));
            }
            Value::Record(m)
        })
        .collect()
}

/// `journal()` — the recorded steps, and how many of them can be reversed.
/// record_summary(): this session's opt-in evaluation records, summarised; see
/// src/record.rs. Zeros and `enabled: false` unless IRONSHELL_RECORD is set.
fn bi_record_summary(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("record_summary", &args, &input)?;
    Ok(crate::record::summary())
}

fn bi_journal() -> Result<Value> {
    let entries = crate::journal::entries();
    let reversible = crate::journal::reversible_count();
    let rows = journal_rows(&entries);
    let mut out = std::collections::BTreeMap::new();
    out.insert("steps".to_string(), Value::Int(entries.len() as i64));
    out.insert("reversible".to_string(), Value::Int(reversible as i64));
    out.insert(
        "irreversible".to_string(),
        Value::Int((entries.len() - reversible) as i64),
    );
    out.insert(
        "enabled".to_string(),
        Value::Bool(crate::journal::enabled()),
    );
    out.insert("entries".to_string(), Value::Array(rows));
    Ok(Value::Record(out))
}

/// `journal_clear()` — forget the recorded steps. Touches no files; the
/// captured contents are dropped, so anything before this point can no longer
/// be rewound.
fn bi_journal_clear(input: Option<Value>) -> Result<Value> {
    refuse_pipeline_input("journal_clear", &input)?;
    let n = crate::journal::entries().len();
    clear_journal_or_refuse("journal_clear")?;
    let mut m = std::collections::BTreeMap::new();
    m.insert("forgotten".to_string(), Value::Int(n as i64));
    m.insert(
        "note".to_string(),
        Value::Str("no files changed; these steps can no longer be undone".to_string()),
    );
    Ok(Value::Record(m))
}

/// Clear the journal, or say what survived: an answer that the steps are gone
/// must not stand while their files, which a later process loads, remain.
fn clear_journal_or_refuse(builtin: &str) -> Result<()> {
    crate::journal::try_clear().map_err(|(dir, err)| {
        crate::safety::io_fault(
            builtin,
            &format!(
                "the journal in {} could not be removed: {err}",
                dir.display()
            ),
            "remove that directory by hand; it may hold the contents of overwritten files, and a later process will load what is left",
        )
    })
}

/// `handle(id)` — the full value behind a handle, exactly as computed.
///
/// A missing id is a structured error rather than a null, and it names the live
/// handles: a handle from a previous process is gone, and an agent that gets
/// `null` back cannot tell that apart from an empty result.
fn bi_handle(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_pipeline_input("handle", &input)?;
    let id = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("handle(id): a handle id is required"))?;
    match crate::handles::get(&id) {
        Some(v) => {
            // Reading a handle whole is asking for its value, not for a new
            // handle to it.
            crate::handles::show_next_whole();
            Ok(v)
        }
        None => {
            let live: Vec<String> = crate::handles::list().into_iter().map(|h| h.id).collect();
            let got = if live.is_empty() {
                format!("'{id}' (no handles live — they do not survive the process)")
            } else {
                format!("'{id}' (live: {})", live.join(", "))
            };
            Err(crate::safety::bad_arg(
                "handle",
                "a live handle id, as listed by handles()",
                &got,
            ))
        }
    }
}

/// `handles()` — every live handle with its shape and size, without the data.
fn bi_handles() -> Result<Value> {
    Ok(Value::Array(
        crate::handles::list()
            .into_iter()
            .map(|h| {
                let mut m = std::collections::BTreeMap::new();
                m.insert("id".to_string(), Value::Str(h.id));
                m.insert("shape".to_string(), Value::Str(h.shape));
                m.insert("items".to_string(), Value::Int(h.items as i64));
                m.insert("bytes".to_string(), Value::Int(h.bytes as i64));
                Value::Record(m)
            })
            .collect(),
    ))
}

/// `handle_drop(id)` — release a handle, reporting whether it existed.
fn bi_handle_drop(args: Vec<Value>) -> Result<Value> {
    let id = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("handle_drop(id): a handle id is required"))?;
    Ok(Value::Bool(crate::handles::drop_handle(&id)))
}

/// Render a large result as a handle: what it is, how big, a short preview, and
/// the exact call that narrows it down.
///
/// The hint is not decoration — it is how the agent discovers `handle` at all.
/// These builtins are reachable but not in the ontology listing, so the call
/// site teaches itself at the moment it is needed, which beats requiring a
/// discovery round-trip to learn how to avoid a discovery round-trip.
fn render_handle(v: Value, full_bytes: usize) -> anyhow::Result<String> {
    let preview = crate::handles::preview_of(&v);
    let omitted = crate::handles::omitted(&v);
    let h = crate::handles::put(v, full_bytes)?;
    let mut out = String::new();
    out.push_str(&format!("@handle {}\n", h.id));
    out.push_str(&format!("@shape {}\n", h.shape));
    out.push_str(&format!("@items {}\n", h.items));
    out.push_str(&format!("@bytes {}\n", h.bytes));
    out.push_str(&aecon_render(&preview));
    if omitted > 0 {
        // Stated explicitly: a preview that looks like a result is how silent
        // truncation misleads.
        out.push_str(&format!("\n@omitted {omitted}"));
    }
    out.push_str(&format!(
        "\n@hint handle(\"{}\") | where(...) | take(5)  — full value kept, nothing lost",
        h.id
    ));
    Ok(out)
}

/// Recursively redact known secret shapes from a value before it is rendered to
/// an agent. Scalar strings are shape-scrubbed (API-key prefixes, JWTs, PEM
/// blocks, URL credentials, `key=secret` assignments) via `safety::redact_str`;
/// any record/table field whose *name* denotes a secret is replaced with the
/// marker even when its value doesn't match a shape. Structure is preserved —
/// only secret leaves change — and the transform is deterministic.
pub fn redact_value(v: &Value) -> Value {
    match v {
        Value::Str(s) => {
            let (r, _) = crate::safety::redact_str(s);
            Value::Str(r)
        }
        Value::Uri(s) => {
            let (r, _) = crate::safety::redact_str(s);
            Value::Uri(r)
        }
        Value::Array(items) => Value::Array(items.iter().map(redact_value).collect()),
        Value::Record(m) => Value::Record(redact_field_map(m)),
        Value::Table(t) => Value::Table(crate::value::Table {
            rows: t.rows.iter().map(redact_field_map).collect(),
            schema: t.schema.clone(),
        }),
        other => other.clone(),
    }
}

/// Redact a record/row field map: secret-named fields become the marker;
/// every other field is recursively redacted.
fn redact_field_map(
    m: &std::collections::BTreeMap<String, Value>,
) -> std::collections::BTreeMap<String, Value> {
    let mut out = std::collections::BTreeMap::new();
    for (k, val) in m {
        if crate::safety::is_secret_name(k) && redactable_by_name(val) {
            out.insert(
                k.clone(),
                Value::Str(crate::safety::REDACTION_MARKER.to_string()),
            );
        } else {
            out.insert(k.clone(), redact_value(val));
        }
    }
    out
}

/// Whether a value under a secret-*sounding* field name should actually be
/// replaced by the marker.
///
/// `is_secret_name` matches substrings, so `TOKEN` also matches `full_tokens`,
/// `compact_tokens`, `page_tokens` and `tokens_in`. Those hold **counts**, and
/// redacting them made the token-economy surface — the thing this project
/// measures itself by — report `[REDACTED]` to agents instead of numbers.
///
/// Two rules, both narrow:
///
/// * A secret is a string. A number, bool or null under a secret-sounding name
///   cannot be one, and blanking it destroys information for no gain.
/// * An **approval or plan token** (`apv_…`, `apl_…`) is a capability the agent
///   is required to echo back, not a credential to hide. `plan()` returned
///   `token="[REDACTED]"` in its machine-readable field while printing the real
///   token in `hint` — incoherent, and it broke the documented plan/apply flow
///   for any caller reading the structured field.
///
/// Found by driving the shell as an agent.
fn redactable_by_name(v: &Value) -> bool {
    match v {
        Value::Str(s) | Value::Uri(s) => !crate::safety::is_capability_token(s),
        // Containers are walked normally so genuine secrets inside are still
        // caught by shape and by their own field names.
        Value::Array(_) | Value::Record(_) | Value::Table(_) => false,
        _ => false,
    }
}

/// Render a result for **deterministic mode** (`--deterministic` / `IRONSHELL_DETERMINISTIC`):
/// canonical JSON — byte-identical for equal values across OS/locale (sorted keys,
/// shortest round-trip floats), for snapshot tests, content-addressable caching,
/// and cross-tool diffs. The whole value is emitted (no budget truncation, which
/// would break reproducibility of the full result). `Null` prints nothing.
pub fn render_canonical(v: &Value) -> Option<String> {
    match v {
        Value::Null => None,
        _ => Some(canonical_render(v)),
    }
}

/// Format a `budget_value`/`budget_string_record` envelope as AECON page text plus
/// a single `@page k=v…` metadata line (the page field is already AECON text, so
/// it is emitted raw rather than re-quoted).
fn render_budget_envelope(env: &Value) -> String {
    if let Value::Record(m) = env {
        let page = match m.get("page") {
            Some(Value::Str(s)) => s.clone(),
            _ => String::new(),
        };
        let meta: Vec<String> = m
            .iter()
            .filter(|(k, _)| k.as_str() != "page")
            .map(|(k, val)| format!("{}={}", k, aecon_atom(val)))
            .collect();
        if meta.is_empty() {
            page
        } else {
            format!("{}\n@page {}", page, meta.join("\t"))
        }
    } else {
        aecon_render(env)
    }
}

// ─────────────────────────────────────────────────────────────────────────
// Plan / Apply (docs/AGENTIC_FIRST_DESIGN.md §9): a destructive batch is
// described declaratively, reviewed (typed plan + blast radius + a bound token),
// approved once, then applied ATOMICALLY inside a transaction (all-or-nothing,
// auto-rollback on any failure). Composes approval (safety) + transactions (tx)
// + structured output. Supported ops: write{path,content}, rm{path}, mkdir{path}.
// ─────────────────────────────────────────────────────────────────────────

/// A content-bound token for a plan (`apl_<16 hex of sha256(canonical(ops))>`),
/// so approving one plan cannot authorize a different set of operations.
fn plan_token(ops: &Value) -> Result<String> {
    let digest = ic_sha256("plan/apply", canonical_render(ops).as_bytes())?;
    let hex: String = digest
        .iter()
        .take(8)
        .map(|b| format!("{:02x}", b))
        .collect();
    Ok(format!("apl_{}", hex))
}

/// Validate and normalize plan ops into `(op, path, content?)` tuples.
#[allow(clippy::type_complexity)]
fn parse_plan_ops(ops: &Value) -> Result<Vec<(String, String, Option<String>, Option<String>)>> {
    let arr = match ops {
        Value::Array(a) => a,
        other => {
            return Err(crate::safety::bad_arg(
                "plan/apply",
                "ops: Array<Record{op, path, content?}>",
                other.type_name(),
            ))
        }
    };
    let mut out = Vec::with_capacity(arr.len());
    for (i, e) in arr.iter().enumerate() {
        let m = match e {
            Value::Record(m) => m,
            _ => {
                return Err(crate::safety::arg_err(format!(
                    "plan: op #{} must be a record {{op, path, content?}}",
                    i
                )))
            }
        };
        let op = match m.get("op") {
            Some(Value::Str(s)) => s.clone(),
            _ => {
                return Err(crate::safety::arg_err(format!(
                    "plan: op #{} missing 'op' string",
                    i
                )))
            }
        };
        let path = match m.get("path") {
            Some(Value::Str(s)) => s.clone(),
            _ => {
                return Err(crate::safety::arg_err(format!(
                    "plan: op #{} missing 'path' string",
                    i
                )))
            }
        };
        let content = match m.get("content") {
            Some(Value::Str(s)) => Some(s.clone()),
            _ => None,
        };
        // `copy`/`move` carry a destination path in `dest` (or `to`).
        let dest = match m.get("dest").or_else(|| m.get("to")) {
            Some(Value::Str(s)) => Some(s.clone()),
            _ => None,
        };
        match op.as_str() {
            "write" | "append" if content.is_none() => {
                return Err(crate::safety::arg_err(format!(
                    "plan: {} op #{} requires 'content'",
                    op, i
                )))
            }
            "copy" | "move" if dest.is_none() => {
                return Err(crate::safety::arg_err(format!(
                    "plan: {} op #{} requires 'dest' (destination path)",
                    op, i
                )))
            }
            "write" | "append" | "rm" | "mkdir" | "copy" | "move" => {}
            other => {
                return Err(crate::safety::arg_err(format!(
                    "plan: op #{} unsupported op '{}' (expected write|append|rm|mkdir|copy|move)",
                    i, other
                )))
            }
        }
        out.push((op, path, content, dest));
    }
    Ok(out)
}

/// plan(ops) - Produce a typed, reviewable plan for a destructive batch without
/// executing it: a summary (writes/deletes/mkdirs), operation count, and a
/// content-bound approval `token`. Review, `approve(token)`, then `apply(ops)`.
fn bi_plan(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let ops = args
        .first()
        .cloned()
        .ok_or_else(|| crate::safety::bad_arg("plan", "ops: Array<Record{op, path}>", "nothing"))?;
    let parsed = parse_plan_ops(&ops)?;
    let (mut writes, mut appends, mut deletes, mut mkdirs, mut copies, mut moves) =
        (0i64, 0i64, 0i64, 0i64, 0i64, 0i64);
    for (op, _, _, _) in &parsed {
        match op.as_str() {
            "write" => writes += 1,
            "append" => appends += 1,
            "rm" => deletes += 1,
            "mkdir" => mkdirs += 1,
            "copy" => copies += 1,
            "move" => moves += 1,
            _ => {}
        }
    }
    let token = plan_token(&ops)?;
    let mut summary = BTreeMap::new();
    summary.insert("writes".to_string(), Value::Int(writes));
    summary.insert("appends".to_string(), Value::Int(appends));
    summary.insert("deletes".to_string(), Value::Int(deletes));
    summary.insert("mkdirs".to_string(), Value::Int(mkdirs));
    summary.insert("copies".to_string(), Value::Int(copies));
    summary.insert("moves".to_string(), Value::Int(moves));
    let mut r = BTreeMap::new();
    r.insert("operations".to_string(), Value::Int(parsed.len() as i64));
    r.insert("summary".to_string(), Value::Record(summary));
    r.insert("token".to_string(), Value::Str(token.clone()));
    r.insert(
        "hint".to_string(),
        Value::Str(format!(
            "review, then a human approves this token out of band (IRONSHELL_APPROVE={}), then apply(<ops>); an agent cannot approve its own plan",
            token
        )),
    );
    r.insert("plan".to_string(), ops);
    Ok(Value::Record(r))
}

/// plan_diff(ops) - What a plan would change, as text a reviewer can read.
///
/// `plan()` answers "how many operations, of what kinds". That is enough to
/// decide whether a plan is the right *shape* and not enough to decide whether
/// it is correct: two plans with identical summaries can write entirely
/// different bytes. This renders the actual before/after.
///
/// A separate builtin rather than a field on `plan()` on purpose. A diff is
/// unbounded in a way a summary is not, and this project's convention is
/// progressive disclosure -- an agent that wants the detail asks for it, and
/// one that only wants the shape does not pay for it.
///
/// Output is capped per file, with the elided count reported rather than
/// silently dropped -- the same contract `budget()` uses.
fn bi_plan_diff(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    const MAX_LINES_PER_OP: usize = 40;

    let ops = args.first().cloned().ok_or_else(|| {
        crate::safety::bad_arg("plan_diff", "ops: Array<Record{op, path}>", "nothing")
    })?;
    let parsed = parse_plan_ops(&ops)?;

    let mut entries = Vec::with_capacity(parsed.len());
    let mut total_added = 0i64;
    let mut total_removed = 0i64;

    for (op, path, content, dest) in &parsed {
        let mut rec = BTreeMap::new();
        rec.insert("op".to_string(), Value::Str(op.clone()));
        rec.insert("path".to_string(), Value::Str(path.clone()));

        // What is there now. `None` means the path does not exist or cannot be
        // read as text -- reported, never guessed at.
        let existing = read_text_capped("plan_diff", path).ok();
        let exists = std::path::Path::new(path).exists();

        let (before, after): (Vec<String>, Vec<String>) = match op.as_str() {
            "write" => (
                existing
                    .as_deref()
                    .unwrap_or("")
                    .lines()
                    .map(str::to_string)
                    .collect(),
                content
                    .as_deref()
                    .unwrap_or("")
                    .lines()
                    .map(str::to_string)
                    .collect(),
            ),
            "append" => {
                let base: Vec<String> = existing
                    .as_deref()
                    .unwrap_or("")
                    .lines()
                    .map(str::to_string)
                    .collect();
                let mut end = base.clone();
                end.extend(content.as_deref().unwrap_or("").lines().map(str::to_string));
                (base, end)
            }
            "rm" => (
                existing
                    .as_deref()
                    .unwrap_or("")
                    .lines()
                    .map(str::to_string)
                    .collect(),
                Vec::new(),
            ),
            _ => (Vec::new(), Vec::new()),
        };

        let mut lines: Vec<Value> = Vec::new();
        let mut added = 0i64;
        let mut removed = 0i64;

        match op.as_str() {
            "write" | "append" | "rm" => {
                // A line-set difference, not a longest-common-subsequence diff:
                // it answers "what appears and what disappears" without claiming
                // to reconstruct how an editor would have moved things.
                for l in &before {
                    if !after.contains(l) {
                        removed += 1;
                        if lines.len() < MAX_LINES_PER_OP {
                            lines.push(Value::Str(format!("-{l}")));
                        }
                    }
                }
                for l in &after {
                    if !before.contains(l) {
                        added += 1;
                        if lines.len() < MAX_LINES_PER_OP {
                            lines.push(Value::Str(format!("+{l}")));
                        }
                    }
                }
                if existing.is_none() && exists {
                    rec.insert(
                        "note".to_string(),
                        Value::Str("path exists but is not readable as text".to_string()),
                    );
                }
            }
            "mkdir" => {
                rec.insert(
                    "note".to_string(),
                    Value::Str(if exists {
                        "directory already exists".to_string()
                    } else {
                        "creates directory".to_string()
                    }),
                );
            }
            "copy" | "move" => {
                let d = dest.clone().unwrap_or_default();
                rec.insert("dest".to_string(), Value::Str(d.clone()));
                rec.insert(
                    "note".to_string(),
                    Value::Str(if std::path::Path::new(&d).exists() {
                        format!("{op} over an existing {d}")
                    } else {
                        format!("{op} to a new {d}")
                    }),
                );
            }
            _ => {}
        }

        rec.insert("exists".to_string(), Value::Bool(exists));
        rec.insert("added".to_string(), Value::Int(added));
        rec.insert("removed".to_string(), Value::Int(removed));
        let shown = lines.len() as i64;
        let elided = (added + removed) - shown;
        rec.insert("lines".to_string(), Value::Array(lines));
        if elided > 0 {
            rec.insert("elided".to_string(), Value::Int(elided));
        }

        total_added += added;
        total_removed += removed;
        entries.push(Value::Record(rec));
    }

    let mut out = BTreeMap::new();
    out.insert("operations".to_string(), Value::Int(parsed.len() as i64));
    out.insert("added".to_string(), Value::Int(total_added));
    out.insert("removed".to_string(), Value::Int(total_removed));
    out.insert("diff".to_string(), Value::Array(entries));
    out.insert("token".to_string(), Value::Str(plan_token(&ops)?));
    Ok(Value::Record(out))
}

/// The refusal, if any, that `apply` gives one op: a path or destination outside
/// the workspace jail (when enforced), or a copy/move onto its own source.
/// Paths are already resolved by the caller. Pure: no filesystem writes, audit
/// entries or budget charges, so it can run for every op before any op executes.
fn apply_op_refusal(
    op: &str,
    path: &str,
    dest: Option<&str>,
    enforce_jail: bool,
) -> Option<String> {
    if enforce_jail && !crate::safety::within_workspace(path) {
        return Some(format!("'{}' is outside the workspace", path));
    }
    // `apply` is self-guarded, so the paths `guard` protects are refused here.
    if let Some(why) = crate::safety::protected_write_refusal(path) {
        return Some(format!("'{path}' is {why}"));
    }
    // copy/move write a destination — it is jailed too.
    if let Some(d) = dest {
        if enforce_jail && !crate::safety::within_workspace(d) {
            return Some(format!("destination '{}' is outside the workspace", d));
        }
        if let Some(why) = crate::safety::protected_write_refusal(d) {
            return Some(format!("destination '{d}' is {why}"));
        }
        if d == path {
            return Some(format!("{} {}: destination is the source", op, path));
        }
    }
    None
}

/// The first refusal among a whole plan, checked before the transaction opens.
fn apply_preflight_refusal(
    ops: &[(String, String, Option<String>, Option<String>)],
    enforce_jail: bool,
) -> Option<String> {
    ops.iter()
        .find_map(|(op, path, _, dest)| apply_op_refusal(op, path, dest.as_deref(), enforce_jail))
}

/// The `apply` result for a plan refused before anything ran. Nothing was
/// written, so there is no transaction and nothing to roll back.
fn apply_refused_record(err: String, token: &str) -> Value {
    let _ = crate::safety::audit(
        "apply",
        crate::safety::Effect::Destructive,
        "failed",
        token,
        serde_json::json!({ "error": err, "rolled_back": 0, "preflight": true }),
    );
    let mut r = BTreeMap::new();
    r.insert("status".to_string(), Value::Str("failed".to_string()));
    r.insert("error".to_string(), Value::Str(err));
    r.insert("rolled_back".to_string(), Value::Bool(false));
    r.insert("restored".to_string(), Value::Int(0));
    r.insert("preflight".to_string(), Value::Bool(true));
    Value::Record(r)
}

/// The most ops one `apply` runs, as file_edit and file_patch cap their batches.
const APPLY_MAX_OPS: usize = 10_000;

/// apply(ops) - Execute a plan atomically inside a transaction. In agent mode it
/// requires the plan's token to be approved (else fails with E_NEEDS_APPROVAL, whose `approval.token` is the plan's token);
/// any failure rolls the whole batch back. Filesystem paths are confined to the
/// workspace jail when enforced. Every op is checked before the first one runs.
fn bi_apply(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let ops = args.first().cloned().ok_or_else(|| {
        crate::safety::bad_arg("apply", "ops: Array<Record{op, path}>", "nothing")
    })?;
    // Each op may copy a file into the transaction journal, so a plan is held
    // to the batch limit file_edit and file_patch use, before it is parsed.
    if let Value::Array(a) = &ops {
        if a.len() > APPLY_MAX_OPS {
            return Err(crate::safety::budget_exceeded(
                "apply",
                format!(
                    "the plan has {} ops; at most {APPLY_MAX_OPS} run in one apply",
                    a.len()
                ),
                "split the plan into smaller ones",
            ));
        }
    }
    let parsed = parse_plan_ops(&ops)?;
    let token = plan_token(&ops)?;
    let agent = matches!(crate::safety::current_mode(), crate::safety::Mode::Agent);

    if agent && !crate::safety::is_approved(&token) {
        // Refused like every other gated call: the error has the exit status a
        // script can branch on (75), and the plan token in `approval.token`. A
        // success-shaped record here let a script chained on `apply` go on as
        // though the plan had run.
        let targets: Vec<String> = parsed.iter().map(|(_, path, _, _)| path.clone()).collect();
        let _ = crate::safety::audit(
            "apply",
            crate::safety::Effect::Destructive,
            "needs_approval",
            &token,
            serde_json::json!({ "token": token, "operations": parsed.len() }),
        );
        return Err(anyhow::Error::new(crate::safety::plan_needs_approval(
            "apply",
            &token,
            targets,
            parsed.len(),
        )));
    }

    if agent {
        // An approval is spent by the apply it authorised. Without this, one
        // human approval of a plan token stayed in the in-process grant set
        // for the life of the process, so the same token could re-run the
        // same batch later, against whatever the paths now hold. Revoking
        // before the batch runs is fail-closed: if it fails, the agent needs a
        // fresh out-of-band approval. An `IRONSHELL_APPROVE` entry is operator
        // configuration and is not touched here.
        crate::safety::revoke_approval(&token);
    }

    let enforce_jail = agent || std::env::var("IRONSHELL_WORKSPACE").is_ok();
    // Resolve relative paths once, the way the jail judges them (see
    // resolve_path_str), so the checks and the operations use the same path.
    let resolved: Vec<(String, String, Option<String>, Option<String>)> = parsed
        .iter()
        .map(|(op, path, content, dest)| {
            (
                op.clone(),
                crate::safety::resolve_path_str(path),
                content.clone(),
                dest.as_deref().map(crate::safety::resolve_path_str),
            )
        })
        .collect();
    // Preflight: every op's path checks run before the transaction opens and
    // before any op executes, so a plan refused at op N never touches the disk.
    if let Some(err) = apply_preflight_refusal(&resolved, enforce_jail) {
        return Ok(apply_refused_record(err, &token));
    }
    crate::tx::begin()?;
    // The journal steps this apply adds start here. A failed apply that rolls
    // its files back drops them, since nothing it did remains to be undone.
    let journal_mark = crate::journal::mark();

    let mut applied = 0i64;
    let mut failure: Option<String> = None;
    for (op, path, content, dest) in &resolved {
        // Already checked by the preflight; repeated here so no write can
        // ever run in front of an unchecked path.
        if let Some(err) = apply_op_refusal(op, path, dest.as_deref(), enforce_jail) {
            failure = Some(err);
            break;
        }
        // Each file this op changes is kept before it changes, so `undo` can
        // put it back: one journal step per file. A journal step is one path,
        // so the batch is not one step; `mkdir` changes no file and is not kept.
        let mut touched: Vec<String> = match op.as_str() {
            "write" | "append" | "rm" | "move" => vec![path.clone()],
            _ => Vec::new(),
        };
        if matches!(op.as_str(), "copy" | "move") {
            if let Some(d) = dest {
                touched.push(d.clone());
            }
        }
        crate::journal::record_paths("apply", crate::safety::Effect::Destructive, touched);
        crate::tx::snapshot(path);
        if let Some(d) = dest {
            crate::tx::snapshot(d);
        }
        let res: std::io::Result<()> = match op.as_str() {
            "write" => {
                write_file_atomically("apply", path, content.as_deref().unwrap_or("").as_bytes())
                    .map_err(|e| std::io::Error::other(e.to_string()))
            }
            "append" => {
                use std::io::Write;
                crate::safety::refuse_hard_linked_write("apply", path)
                    .map_err(|e| std::io::Error::other(e.to_string()))
                    .and_then(|()| {
                        crate::safety::open_in_place("apply", std::path::Path::new(path), true)
                            .map_err(|e| std::io::Error::other(e.to_string()))
                            .and_then(|mut f| {
                                f.write_all(content.as_deref().unwrap_or("").as_bytes())
                            })
                    })
            }
            "rm" => std::fs::remove_file(path),
            "mkdir" => std::fs::create_dir_all(path),
            // A copy truncates an existing destination and writes it in place,
            // so the destination is opened first and its link count read from
            // that handle, as for every in-place write.
            "copy" => {
                // The source is opened first: a missing source must leave an
                // existing destination as it was.
                let to = dest.as_deref().unwrap_or("");
                std::fs::File::open(path).and_then(|mut from| {
                    crate::safety::refuse_hard_linked_write("apply", to)
                        .and_then(|()| {
                            crate::safety::open_in_place("apply", std::path::Path::new(to), false)
                        })
                        .map_err(|e| std::io::Error::other(e.to_string()))
                        .and_then(|mut out| std::io::copy(&mut from, &mut out).map(|_| ()))
                })
            }
            "move" => std::fs::rename(path, dest.as_deref().unwrap_or("")),
            _ => Ok(()),
        };
        if let Err(e) = res {
            failure = Some(format!("{} {}: {}", op, path, e));
            break;
        }
        applied += 1;
    }

    // Seal the steps with the state the ops left their files in. The dispatcher
    // does not settle an apply's steps (its effect is `Exec`), so this is the
    // only place they are sealed. A rollback below drops the ones it undid.
    crate::journal::seal_steps(journal_mark);
    let mut r = BTreeMap::new();
    if let Some(err) = failure {
        // Old code reported rolled_back: true even when the rollback itself
        // failed (unwrap_or(0)). Report the rollback error instead.
        let (rolled_back, restored, rollback_error) = match crate::tx::rollback() {
            Ok(n) => (true, n, None),
            Err(e) => (false, 0, Some(e.to_string())),
        };
        // Every file is back as it was, so the steps this apply recorded
        // describe nothing. If the rollback failed, the files may still hold
        // the batch's changes, and the steps stay so `undo` can reach them.
        if rolled_back {
            crate::journal::rollback_to(journal_mark);
        }
        let _ = crate::safety::audit(
            "apply",
            crate::safety::Effect::Destructive,
            "failed",
            &token,
            serde_json::json!({
                "error": err,
                "rolled_back": restored,
                "rollback_error": rollback_error,
            }),
        );
        r.insert("status".to_string(), Value::Str("failed".to_string()));
        r.insert("error".to_string(), Value::Str(err));
        r.insert("rolled_back".to_string(), Value::Bool(rolled_back));
        r.insert("restored".to_string(), Value::Int(restored as i64));
        if let Some(rb) = rollback_error {
            r.insert("rollback_error".to_string(), Value::Str(rb));
        }
    } else if let Err(e) = crate::tx::commit() {
        // Old code ignored a failed commit (let _ =) and reported "applied".
        let err = format!("commit: {}", e);
        let _ = crate::safety::audit(
            "apply",
            crate::safety::Effect::Destructive,
            "failed",
            &token,
            serde_json::json!({ "error": err, "rolled_back": 0 }),
        );
        r.insert("status".to_string(), Value::Str("failed".to_string()));
        r.insert("error".to_string(), Value::Str(err));
        r.insert("rolled_back".to_string(), Value::Bool(false));
        r.insert("restored".to_string(), Value::Int(0));
    } else {
        // The operations and the commit have already happened, so a failed
        // required audit write cannot undo them. It must still not report
        // "applied" as if the record were kept.
        if let Err(e) = crate::safety::audit(
            "apply",
            crate::safety::Effect::Destructive,
            "applied",
            &token,
            serde_json::json!({ "operations": applied }),
        ) {
            return Err(crate::safety::io_fault(
                "apply",
                &format!(
                    "the {applied} operations WERE applied and committed, but the required audit record could not be written: {e}"
                ),
                "the changes are in place; do not re-run this plan. Fix the audit log path (IRONSHELL_AUDIT_REQUIRED is set) and check the audit log",
            ));
        }
        r.insert("status".to_string(), Value::Str("applied".to_string()));
        r.insert("applied".to_string(), Value::Int(applied));
    }
    Ok(Value::Record(r))
}

/// tx_begin() - Start a filesystem transaction. Subsequent file_write/rm calls
/// record their pre-modification state so the batch can be rolled back.
fn bi_tx_begin(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("tx_begin", &input)?;
    let id = crate::tx::begin()?;
    let mut r = BTreeMap::new();
    r.insert("transaction".to_string(), Value::Str(id));
    r.insert("active".to_string(), Value::Bool(true));
    // Nesting depth after this begin (1 = outermost; a nested begin pushes a child).
    r.insert("depth".to_string(), Value::Int(crate::tx::depth() as i64));
    Ok(Value::Record(r))
}

/// tx_commit() - Commit the active transaction (keep changes, discard journal).
fn bi_tx_commit(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("tx_commit", &input)?;
    let n = crate::tx::commit()?;
    let mut r = BTreeMap::new();
    r.insert("committed".to_string(), Value::Bool(true));
    r.insert("operations".to_string(), Value::Int(n as i64));
    Ok(Value::Record(r))
}

/// tx_rollback() - Roll back the active transaction, restoring every recorded
/// path to its pre-transaction state.
fn bi_tx_rollback(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("tx_rollback", &input)?;
    let n = crate::tx::rollback()?;
    let mut r = BTreeMap::new();
    r.insert("rolled_back".to_string(), Value::Bool(true));
    r.insert("restored".to_string(), Value::Int(n as i64));
    Ok(Value::Record(r))
}

/// tx_status() - Report whether a transaction is active and its operation count.
fn bi_tx_status(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut r = BTreeMap::new();
    match crate::tx::status() {
        Some((id, n)) => {
            r.insert("active".to_string(), Value::Bool(true));
            r.insert("transaction".to_string(), Value::Str(id));
            r.insert("operations".to_string(), Value::Int(n as i64));
            r.insert("depth".to_string(), Value::Int(crate::tx::depth() as i64));
        }
        None => {
            r.insert("active".to_string(), Value::Bool(false));
            r.insert("depth".to_string(), Value::Int(0));
        }
    }
    Ok(Value::Record(r))
}

/// tx_savepoint(name) - Mark a named savepoint inside the active transaction; a
/// later `tx_rollback_to(name)` reverts only the operations recorded after it.
fn bi_tx_savepoint(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("tx_savepoint", &input)?;
    let name = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::bad_arg(
                "tx_savepoint",
                "name: String",
                "nothing",
            ))
        }
    };
    crate::tx::savepoint(&name)?;
    let mut r = BTreeMap::new();
    r.insert("savepoint".to_string(), Value::Str(name));
    Ok(Value::Record(r))
}

/// tx_rollback_to(name) - Roll back to a named savepoint, reverting only the
/// operations recorded after it; the transaction stays open.
fn bi_tx_rollback_to(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("tx_rollback_to", &input)?;
    let name = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::bad_arg(
                "tx_rollback_to",
                "name: String",
                "nothing",
            ))
        }
    };
    let n = crate::tx::rollback_to(&name)?;
    let mut r = BTreeMap::new();
    r.insert("rolled_back_to".to_string(), Value::Str(name));
    r.insert("restored".to_string(), Value::Int(n as i64));
    Ok(Value::Record(r))
}

/// safety_status() - Report the current safety operating envelope so an agent
/// knows what it may do before acting: execution mode, acting principal,
/// workspace jail root, audit log, whether a transaction is active, and the
/// resolved policy decision (allow/deny/approve) for every effect class.
fn bi_safety_status(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    use crate::safety::{Decision, Effect, Mode};
    let mode = crate::safety::current_mode();
    let mode_str = match mode {
        Mode::Agent => "agent",
        Mode::Human => "human",
    };
    let effects = [
        Effect::Pure,
        Effect::ReadLocal,
        Effect::WriteLocal,
        Effect::Network,
        Effect::Process,
        Effect::Destructive,
        Effect::Exec,
        Effect::Privileged,
    ];
    let mut policy = BTreeMap::new();
    for e in effects {
        let d = match crate::safety::effective_decision(e, mode) {
            Decision::Allow => "allow",
            Decision::Deny => "deny",
            Decision::Approve => "approve",
        };
        policy.insert(e.as_str().to_string(), Value::Str(d.to_string()));
    }
    let mut r = BTreeMap::new();
    r.insert("mode".to_string(), Value::Str(mode_str.to_string()));
    r.insert(
        "principal".to_string(),
        crate::safety::current_principal()
            .map(Value::Str)
            .unwrap_or(Value::Null),
    );
    r.insert(
        "workspace".to_string(),
        Value::Str(
            crate::safety::workspace_root()
                .to_string_lossy()
                .to_string(),
        ),
    );
    r.insert(
        "audit_log".to_string(),
        crate::safety::audit_path()
            .map(|p| Value::Str(p.to_string_lossy().to_string()))
            .unwrap_or(Value::Null),
    );
    r.insert(
        "transaction_active".to_string(),
        Value::Bool(crate::tx::is_active()),
    );
    r.insert("policy".to_string(), Value::Record(policy));
    r.insert(
        "governor".to_string(),
        Value::from_json(&crate::safety::governor_snapshot()),
    );
    Ok(Value::Record(r))
}

/// governor_status() - Report the resource-governor envelope (§7.6): current
/// counts (ops/files/procs), the configured limits (null = unlimited), elapsed
/// wall-clock ms, and whether governors are active (agent mode). Lets an agent
/// watch its blast-radius budget burn down before it hits `E_BUDGET_EXCEEDED`.
fn bi_governor_status(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::from_json(&crate::safety::governor_snapshot()))
}

/// governor_reset() - Reset the resource-governor counters and wall-clock start,
/// beginning a fresh envelope (e.g. after deliberately raising a limit or at a
/// session boundary).
///
/// In agent mode it is refused in the body, as `approve` is. Left callable, an
/// agent could clear its own IRONSHELL_MAX_OPS/FILES/PROCS/NET counters and its
/// wall-clock envelope, which is the budget the governor exists to enforce. The
/// limits are environment variables read at startup, so the out-of-band route is
/// to raise them before launch, not to reset them mid-run. Human mode is untouched.
fn bi_governor_reset(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if crate::safety::current_mode() == crate::safety::Mode::Agent {
        return Err(anyhow::Error::new(crate::safety::SafetyError {
            code: crate::safety::ErrorCode::PolicyDeny,
            message: "governor_reset: an agent may not reset its own budget".to_string(),
            builtin: "governor_reset".to_string(),
            hint: "the limits are set by whoever launched the agent: raise \
                   IRONSHELL_MAX_OPS, IRONSHELL_MAX_FILES, IRONSHELL_MAX_PROCS, \
                   IRONSHELL_MAX_NET or IRONSHELL_TIMEOUT_MS before launch"
                .to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: String::new(),
            got: String::new(),
            extra: serde_json::Map::new(),
        }));
    }
    crate::safety::governor_reset();
    Ok(Value::Bool(true))
}

// ─────────────────────────────────────────────────────────────────────────
// Stateful sessions (docs/AGENTIC_FIRST_DESIGN.md §6.3): a persistent Env keyed
// by session id, so an agent builds up state across calls (`let x = …` then use
// `x` later) WITHOUT re-sending prior context each turn — a token-efficiency and
// capability win over the single-shot eval path.
// ─────────────────────────────────────────────────────────────────────────

static SESS_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// A stateful session: a persistent environment plus running token accounting.
struct Session {
    env: crate::env::Env,
    tokens_in: u64,
    tokens_out: u64,
    evals: u64,
}

impl Session {
    fn new() -> Self {
        // Register the module namespaces (file, sys, str, http, …) so a session
        // can run module-qualified calls like `file.read(…)`, not just builtins.
        let env = crate::modules::env_with_modules();
        Self {
            env,
            tokens_in: 0,
            tokens_out: 0,
            evals: 0,
        }
    }
}

lazy_static::lazy_static! {
    static ref SESSIONS: std::sync::Mutex<HashMap<String, Session>> =
        std::sync::Mutex::new(HashMap::new());
}

/// Most sessions one process holds open. A session carries a whole Env.
const SESSION_MAX: usize = 64;
/// Longest code one sess_eval call may send.
const SESSION_CODE_MAX: usize = 64 * 1024;

/// sess_open() - Create a stateful session and return its id. Subsequent
/// `sess_eval(id, code)` calls share one persistent environment.
fn bi_sess_open(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("sess_open", &input)?;
    if !args.is_empty() {
        return Err(crate::safety::arg_err("sess_open takes no arguments"));
    }
    let id = format!(
        "sess_{}_{}",
        std::process::id(),
        SESS_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
    );
    let mut store = SESSIONS
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("sess_open", "the session store"))?;
    if store.len() >= SESSION_MAX {
        return Err(crate::safety::budget_exceeded(
            "sess_open",
            format!("sess_open: {SESSION_MAX} sessions are already open"),
            "close one with sess_close, then open another",
        ));
    }
    store.insert(id.clone(), Session::new());
    let mut r = BTreeMap::new();
    r.insert("session".to_string(), Value::Str(id));
    r.insert("active".to_string(), Value::Bool(true));
    Ok(Value::Record(r))
}

/// sess_eval(id, code) - Evaluate code in a session's persistent environment;
/// `let` bindings and mutations persist across calls. Returns the result value.
/// Each builtin the code calls passes the same dispatch guard as at the REPL, so
/// agent-mode policy applies inside a session too.
fn bi_sess_eval(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("sess_eval", &input)?;
    let id = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "sess_eval",
                "session_id: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let code = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "sess_eval",
                "code: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    if code.len() > SESSION_CODE_MAX {
        return Err(crate::safety::budget_exceeded(
            "sess_eval",
            format!(
                "sess_eval: the code is {} bytes; one call evaluates at most {SESSION_CODE_MAX}",
                code.len()
            ),
            "split the code across calls; bindings persist between them",
        ));
    }
    // Take the env out (not holding the lock across eval — avoids deadlock if the
    // evaluated code touches the session store) and put it back afterward so
    // bindings made before any error still persist.
    let mut session = {
        let mut store = SESSIONS
            .lock()
            .map_err(|_| crate::safety::lock_poisoned("sess_eval", "the session store"))?;
        match store.remove(&id) {
            Some(s) => s,
            None => return Err(crate::safety::not_found("sess_eval", "session", &id)),
        }
    };
    let result = (|| -> Result<Value> {
        let stmts = crate::parser::parse_program(&code)?;
        crate::eval::eval_program(&stmts, &mut session.env)
    })();
    // Accumulate running token usage for this session.
    session.evals += 1;
    session.tokens_in += est_token_count(&code) as u64;
    let out_str = match &result {
        Ok(v) => v.to_display_string(),
        Err(e) => e.to_string(),
    };
    session.tokens_out += est_token_count(&out_str) as u64;
    SESSIONS
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("sess_eval", "the session store"))?
        .insert(id, session);
    result
}

/// sess_usage(id) - Running token accounting for a session: estimated
/// `tokens_in`/`tokens_out`/`tokens_total` and the number of `evals`.
fn bi_sess_usage(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("sess_usage", &input)?;
    let id = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "sess_usage",
                "session_id: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let store = SESSIONS
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("sess_usage", "the session store"))?;
    match store.get(&id) {
        Some(s) => {
            let mut r = BTreeMap::new();
            r.insert("tokens_in".to_string(), Value::Int(s.tokens_in as i64));
            r.insert("tokens_out".to_string(), Value::Int(s.tokens_out as i64));
            r.insert(
                "tokens_total".to_string(),
                Value::Int((s.tokens_in + s.tokens_out) as i64),
            );
            r.insert("evals".to_string(), Value::Int(s.evals as i64));
            Ok(Value::Record(r))
        }
        None => Err(crate::safety::not_found("sess_usage", "session", &id)),
    }
}

/// sess_close(id) - Discard a session and its environment.
fn bi_sess_close(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let id = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "sess_close",
                "session_id: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let existed = SESSIONS
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("sess_close", "the session store"))?
        .remove(&id)
        .is_some();
    let mut r = BTreeMap::new();
    r.insert("closed".to_string(), Value::Bool(existed));
    Ok(Value::Record(r))
}

/// ontology_manifest() - Compact root of the ontology for progressive
/// disclosure: categories with builtin counts, effect classes, and samples,
/// plus the effect legend. Load this cheaply, then `ontology_describe` the slice
/// you need instead of carrying the full ontology in context.
fn bi_ontology_manifest(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::from_json(&crate::agent_api::ontology_manifest_json()))
}

/// ontology_describe(name) - Expand one ontology slice: a category name → its
/// builtins (name, signature, effect), or a builtin name → its full definition
/// (effect, params, examples).
fn bi_ontology_describe(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    crate::handles::show_next_whole();
    let q = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "ontology_describe",
                "name: String (category or builtin)",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    // An empty name looked up as a builtin named nothing: "unknown builtin: ".
    // help("") comes here too.
    if q.trim().is_empty() {
        return Err(crate::safety::bad_arg_in(
            "ontology_describe",
            "name must not be empty",
            "help() lists the core builtins; ontology_manifest() lists categories",
        ));
    }
    let described = crate::agent_api::ontology_describe_json(&q);
    if described.get("error").is_some() {
        // An unknown name is a failed lookup, as an unknown builtin call is: an
        // E_UNKNOWN_BUILTIN error with the nearest real builtin or category
        // names, not a successful record that carries an error field.
        let categories = crate::agent_api::ontology_category_names();
        let candidates = nearest_names(
            q.trim(),
            BUILTIN_LOOKUP
                .keys()
                .copied()
                .chain(categories.iter().map(String::as_str)),
        );
        return Err(crate::safety::unknown_builtin(q.trim(), candidates));
    }
    Ok(Value::from_json(&described))
}

/// Pull a string field out of a caught-error record, accepting either the
/// wrapper form `{error: {...}}` that try/catch binds or the bare inner record.
fn diag_field<'a>(err: &'a BTreeMap<String, Value>, key: &str) -> Option<&'a Value> {
    if let Some(Value::Record(inner)) = err.get("error") {
        if let Some(v) = inner.get(key) {
            return Some(v);
        }
    }
    err.get(key)
}

/// diagnose(error) - The **minimal** repair context for a failed call.
///
/// Progressive disclosure applied to failure (§5.4): given the structured error
/// a `catch` block bound, return only what is needed to fix *this* call — the
/// code, whether retrying can help, the offending builtin's signature and effect
/// class, its required parameters, and one example — instead of making the agent
/// pay for a full `ontology_describe` dump or, worse, the whole ontology.
///
/// Deliberately returns *less* than `ontology_describe`: no prose description,
/// no category listing, at most one example. Unknown/absent builtin names yield
/// the code and hint alone rather than an invented suggestion.
fn bi_diagnose(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let subject = args.first().cloned().or(input);
    let err = match subject {
        Some(Value::Record(r)) => r,
        // A bare string is what a non-safety failure used to look like. Report
        // it honestly as uncoded rather than guessing a code from its prose.
        Some(Value::Str(s)) => {
            let mut out = BTreeMap::new();
            out.insert("code".to_string(), Value::Str("E_UNKNOWN".to_string()));
            out.insert("retryable".to_string(), Value::Bool(false));
            out.insert("message".to_string(), Value::Str(s));
            out.insert(
                "hint".to_string(),
                Value::Str(
                    "this failure carries no structured code; it cannot be \
                     repaired programmatically"
                        .to_string(),
                ),
            );
            return Ok(Value::Record(out));
        }
        other => {
            return Err(crate::safety::bad_arg(
                "diagnose",
                "error: Record (the value bound by catch)",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    let mut out = BTreeMap::new();
    let code = match diag_field(&err, "code") {
        Some(Value::Str(c)) => c.clone(),
        _ => "E_UNKNOWN".to_string(),
    };
    out.insert("code".to_string(), Value::Str(code.clone()));
    if let Some(v) = diag_field(&err, "retryable") {
        out.insert("retryable".to_string(), v.clone());
    }
    // `bad_arg`'s hint is "pass an argument matching: {expected}", and `expected`
    // is emitted below as its own field. Carrying both is the same duplication
    // this builtin already refuses for `return_type` and `parameters` -- and it
    // is not free: an expected clause that names a full signature costs as much
    // again. Emitted only when it says something `expected` does not.
    if let Some(Value::Str(hint)) = diag_field(&err, "hint") {
        let restates_expected = matches!(
            diag_field(&err, "expected"),
            Some(Value::Str(e)) if !e.is_empty() && hint.ends_with(e.as_str())
        // ...and only when `expected` actually survives into the output, which
        // it does only alongside `got`. Otherwise dropping the hint would drop
        // the information rather than deduplicate it.
        ) && diag_field(&err, "got").is_some();
        if !restates_expected {
            out.insert("hint".to_string(), Value::Str(hint.clone()));
        }
    }
    if let Some(v) = diag_field(&err, "did_you_mean") {
        out.insert("did_you_mean".to_string(), v.clone());
    }
    if let Some(v) = diag_field(&err, "approval") {
        out.insert("approval".to_string(), v.clone());
    }
    // The typed argument pair, when the failure carries one: an agent repairing a
    // `E_BAD_ARG` should not have to parse English to learn what shape was wanted.
    if let (Some(e), Some(g)) = (diag_field(&err, "expected"), diag_field(&err, "got")) {
        out.insert("expected".to_string(), e.clone());
        out.insert("got".to_string(), g.clone());
    }

    // The expensive part — the builtin's own contract — is fetched only when the
    // error actually names a builtin that exists.
    let name = match diag_field(&err, "builtin") {
        Some(Value::Str(b)) if !b.is_empty() => b.clone(),
        _ => return Ok(Value::Record(out)),
    };
    let def = crate::agent_api::ontology_describe_json(&name);
    if def.get("builtin").and_then(|v| v.as_str()).is_none() {
        // Named a builtin the ontology does not document: say so, don't invent.
        return Ok(Value::Record(out));
    }
    for key in ["builtin", "signature", "effect"] {
        if let Some(v) = def.get(key) {
            out.insert(key.to_string(), Value::from_json(v));
        }
    }
    // A declared builtin refuses a malformed call by naming its signature, and
    // the signature field above is generated from that same declaration. When
    // they are the same string, one of them is free to go; `got` still says
    // what was wrong with the call.
    if let (Some(e), Some(sg)) = (out.get("expected"), out.get("signature")) {
        if e == sg {
            out.remove("expected");
        }
    }
    // Whether re-running the *operation* is safe, which is a different question from
    // whether the *error* was transient (`retryable`). After a timeout an agent knows
    // the error may be worth retrying; only this says whether retrying can duplicate
    // the effect. Emitted only when it adds something `retryable` does not already
    // imply — a retryable error on an idempotent call is the uninteresting case.
    let idem = crate::safety::idempotent(&name);
    let err_retryable = matches!(out.get("retryable"), Some(Value::Bool(true)));
    if !idem || err_retryable {
        out.insert("idempotent".to_string(), Value::Bool(idem));
    }
    // A signature already spells out the parameters and the return type. Emitting
    // them again is pure duplication in the exact place we are trying to be cheap,
    // so the expanded forms appear only when there is no signature to read.
    let has_signature = matches!(out.get("signature"), Some(Value::Str(s)) if !s.is_empty());
    if !has_signature {
        if let Some(v) = def.get("return_type") {
            out.insert("return_type".to_string(), Value::from_json(v));
        }
    }
    if let Some(params) = def
        .get("parameters")
        .and_then(|v| v.as_array())
        .filter(|_| !has_signature)
    {
        // Compact: name:type, required-ness only — descriptions are prose the
        // repair does not need.
        let compact: Vec<Value> = params
            .iter()
            .map(|p| {
                let nm = p.get("name").and_then(|v| v.as_str()).unwrap_or("_");
                let ty = p.get("type").and_then(|v| v.as_str()).unwrap_or("Any");
                let req = p.get("required").and_then(|v| v.as_bool()).unwrap_or(false);
                Value::Str(format!("{}:{}{}", nm, ty, if req { "" } else { "?" }))
            })
            .collect();
        out.insert("parameters".to_string(), Value::Array(compact));
    }
    if let Some(ex) = def
        .get("examples")
        .and_then(|v| v.as_array())
        .and_then(|a| a.first())
        .and_then(|e| e.get("code"))
        .and_then(|c| c.as_str())
    {
        out.insert("example".to_string(), Value::Str(ex.to_string()));
    }
    Ok(Value::Record(out))
}

/// try_repair(code) - Run `code` so that a *failed* attempt leaves no trace.
///
/// The honest description: this does not invent a fix. It makes retrying safe.
/// A self-healing loop that re-runs a mutating batch is only sound if a failed
/// attempt is undone first — otherwise attempt N+1 starts from the debris of
/// attempt N and the failures compound. `try_repair` brackets the evaluation in
/// a named savepoint (§9) and, on failure, rolls back to it, so every attempt
/// starts from identical state.
///
/// Returns `{ok, value}` on success, or `{ok: false, restored, error, retryable}`
/// on failure — `error` being the same structured record `catch` would bind, so
/// it feeds straight into `diagnose()`. Rolls back only the ops *this* call
/// recorded: an enclosing transaction stays open and keeps its earlier work.
fn bi_try_repair(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    let code = match args.first().cloned().or(input) {
        Some(Value::Str(s)) => s,
        other => {
            return Err(crate::safety::bad_arg(
                "try_repair",
                "code: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // Reuse an enclosing transaction when there is one (its earlier work must
    // survive); otherwise open one for the duration of the attempt.
    let owned = !crate::tx::is_active();
    if owned {
        crate::tx::begin().map_err(|e| {
            // A journal directory that could not be made keeps its own code.
            if e.downcast_ref::<crate::safety::SafetyError>().is_some() {
                return e;
            }
            crate::safety::bad_state_with_hint(
                "try_repair",
                &e.to_string(),
                "finish or roll back the open transaction",
            )
        })?;
    }
    let mark = format!("__repair_{}", REPAIR_SEQ.fetch_add(1, Ordering::Relaxed));
    crate::tx::savepoint(&mark).map_err(|e| {
        crate::safety::bad_state_with_hint(
            "try_repair",
            &e.to_string(),
            "finish or roll back the open transaction",
        )
    })?;

    let result = (|| -> Result<Value> {
        let stmts = crate::parser::parse_program(&code)?;
        crate::eval::eval_program(&stmts, env)
    })();

    let mut out = BTreeMap::new();
    match result {
        Ok(v) => {
            if owned {
                crate::tx::commit().map_err(|e| {
                    crate::safety::bad_state_with_hint(
                        "try_repair",
                        &e.to_string(),
                        "finish or roll back the open transaction",
                    )
                })?;
            }
            out.insert("ok".to_string(), Value::Bool(true));
            out.insert("value".to_string(), v);
        }
        Err(e) => {
            // Undo this attempt's mutations before reporting, so the caller's
            // next attempt starts from the same state this one did.
            // A restore that failed means the next attempt would not start
            // from this one's state; it is reported, and the attempt is then
            // not retryable.
            let (restored, mut restore_error) = match crate::tx::rollback_to(&mark) {
                Ok(n) => (n, None),
                Err(e) => (0, Some(e.to_string())),
            };
            if owned {
                if let Err(e) = crate::tx::rollback() {
                    restore_error.get_or_insert(e.to_string());
                }
            }
            // Every failure reaching here is structured (the builtin boundary
            // guarantees it), but a parse error raised before dispatch is not —
            // so pass it through the same net.
            let coded = crate::safety::ensure_structured("try_repair", e);
            let json = coded
                .downcast_ref::<crate::safety::SafetyError>()
                .map(|se| se.to_json())
                .unwrap_or(serde_json::Value::Null);
            // `to_json` wraps in `{error: {...}}`; unwrap it so the caller reads
            // `result.error.code`, not `result.error.error.code`.
            let structured = Value::from_json(json.get("error").unwrap_or(&json));
            let retryable = match &structured {
                Value::Record(r) => match r.get("retryable") {
                    Some(Value::Bool(b)) => *b,
                    _ => false,
                },
                _ => false,
            };
            out.insert("ok".to_string(), Value::Bool(false));
            out.insert("restored".to_string(), Value::Int(restored as i64));
            out.insert(
                "retryable".to_string(),
                Value::Bool(retryable && restore_error.is_none()),
            );
            if let Some(why) = restore_error {
                out.insert("restore_error".to_string(), Value::Str(why));
            }
            out.insert("error".to_string(), structured);
        }
    }
    Ok(Value::Record(out))
}

/// Monotonic counter making each `try_repair` savepoint name unique, so nested
/// or sequential attempts cannot roll back to each other's mark.
static REPAIR_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

lazy_static::lazy_static! {
    /// The process-global RBAC manager backing the in-shell `rbac_*` builtins
    /// and the safety layer's principal authorization.
    static ref GLOBAL_RBAC: std::sync::Arc<crate::auth::RbacManager> =
        std::sync::Arc::new(crate::auth::RbacManager::new());
}

/// Return the global RBAC manager, (re-)installing it into the safety layer so
/// guarded builtins consult it. Idempotent; called by each `rbac_*` builtin.
fn global_rbac() -> std::sync::Arc<crate::auth::RbacManager> {
    let m = GLOBAL_RBAC.clone();
    crate::safety::set_rbac_manager(m.clone());
    m
}

/// rbac_principal(user_id?) - Set or get the current acting principal for safety
/// authorization. With an argument, sets the principal (creating the user if
/// needed) and activates RBAC; with none, returns the current principal or null.
fn bi_rbac_principal(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mgr = global_rbac();
    match args.first() {
        Some(Value::Str(uid)) => {
            if uid.is_empty() || uid.len() > 256 || uid.chars().any(char::is_control) {
                return Err(crate::safety::bad_arg(
                    "rbac_principal",
                    "a user id of 1 to 256 characters with no control characters",
                    &format!("{uid:?}"),
                ));
            }
            // Only the *setting* form is privileged; reading back the current
            // principal (the argless form below) is not, and an agent that
            // cannot ask what it is acting as will guess.
            crate::safety::guard(crate::safety::GuardCtx {
                builtin: "rbac_principal",
                effect: crate::safety::Effect::Privileged,
                what: "act as a different principal",
                targets: vec![uid.clone()],
                blast_radius: serde_json::json!({ "principal": true }),
                reversible: true,
                fs_paths: false,
            })?;
            // Naming a user who has a password does not prove anything: that
            // account is entered through `rbac_login`, or it is not entered.
            // Without this check `rbac_principal("admin")` became admin.
            // The name may be the account's id or its username; either one
            // resolves to the same password-protected account.
            if let Some(account) = resolve_rbac_user(&mgr, uid) {
                if GLOBAL_AUTH.has_password(&account.id) {
                    return Err(crate::safety::policy_deny(
                        "rbac_principal",
                        format!(
                            "rbac_principal: '{uid}' has a password and cannot be assumed by name"
                        ),
                        "authenticate as that user with rbac_login(username, password)",
                    ));
                }
            }
            if mgr.get_user(uid).is_none() {
                let mut u = crate::auth::User::new(uid.clone());
                u.id = uid.clone(); // use the id as the principal handle
                mgr.add_user(u)?;
            }
            crate::safety::set_principal(Some(uid.clone()));
            Ok(Value::Str(uid.clone()))
        }
        None | Some(Value::Null) => Ok(crate::safety::current_principal()
            .map(Value::Str)
            .unwrap_or(Value::Null)),
        _ => Err(crate::safety::arg_err(
            "rbac_principal: expected a user id string or no argument",
        )),
    }
}

/// rbac_grant(user_id, permission) - Grant a direct permission (e.g.
/// "effect:destructive", "effect:*", "builtin:rm", "*:*") to a user so that,
/// when acting as that principal, guarded ops of that class bypass approval.
fn bi_rbac_grant(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let uid = rbac_user_id("rbac_grant", args.first())?;
    let perm = match args.get(1) {
        Some(Value::Str(s)) => rbac_permission_arg("rbac_grant", s)?,
        other => {
            return Err(crate::safety::bad_arg(
                "rbac_grant",
                "a permission string such as \"effect:destructive\"",
                other.map_or("nothing", Value::type_name),
            ))
        }
    };
    let mgr = global_rbac();
    // A registered account is granted by its id or its username, to the same
    // record; a name that is neither is created, as before.
    let mut user = resolve_rbac_user(&mgr, &uid).unwrap_or_else(|| {
        let mut u = crate::auth::User::new(uid.clone());
        u.id = uid.clone();
        u
    });
    let user_id = user.id.clone();
    // A grant that is already held changed nothing, and says so rather than
    // reporting a fresh grant each time it is repeated.
    let changed = user.permissions.insert(perm.clone());
    if changed {
        mgr.add_user(user)?;
        mgr.invalidate_user_cache(&user_id);
    }
    let mut rec = BTreeMap::new();
    rec.insert("user".to_string(), Value::Str(user_id));
    rec.insert("granted".to_string(), Value::Str(perm));
    rec.insert("changed".to_string(), Value::Bool(changed));
    Ok(Value::Record(rec))
}

/// The account a name refers to: by id first, then by username, since a
/// registered account's id and its username differ.
fn resolve_rbac_user(mgr: &crate::auth::RbacManager, name: &str) -> Option<crate::auth::User> {
    mgr.get_user(name)
        .or_else(|| mgr.get_user_by_username(name))
}

/// A user id argument for the `rbac_*` family: a non-empty string of at most
/// 256 bytes with no control characters, since it is written into the audit
/// trail and echoed back.
fn rbac_user_id(builtin: &str, v: Option<&Value>) -> Result<String> {
    match v {
        Some(Value::Str(s))
            if !s.is_empty() && s.len() <= 256 && !s.chars().any(char::is_control) =>
        {
            Ok(s.clone())
        }
        other => Err(crate::safety::bad_arg(
            builtin,
            "a user id string of 1 to 256 characters with no control characters",
            other.map_or("nothing", Value::type_name),
        )),
    }
}

/// A permission argument: `resource:capability`, both halves non-empty, the
/// whole of at most 128 characters from letters, digits and `_ - . * /`.
/// Anything else is refused, so a typo cannot be stored as a grant that
/// matches nothing and looks like one that does.
fn rbac_permission_arg(builtin: &str, s: &str) -> Result<String> {
    let well_formed = s.len() <= 128
        && s.split_once(':').is_some_and(|(a, b)| {
            !a.is_empty()
                && !b.is_empty()
                && !b.contains(':')
                && s.chars().all(|c| {
                    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '*' | '/' | ':')
                })
        });
    if well_formed {
        Ok(s.to_string())
    } else {
        Err(crate::safety::bad_arg(
            builtin,
            "a permission of the form resource:capability, e.g. \"effect:destructive\"",
            &format!("{s:?}"),
        ))
    }
}

/// rbac_can(permission) - Whether the current principal holds `permission`
/// (resolving roles + wildcards). Returns false if no principal is set.
fn bi_rbac_can(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let perm = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "rbac_can: expected a permission string",
            ))
        }
    };
    let mgr = global_rbac();
    let allowed = match crate::safety::current_principal() {
        Some(p) => mgr.check_permission(&p, &perm),
        None => false,
    };
    Ok(Value::Bool(allowed))
}

// ------------------------------------------------------------------------
// Interactive login (§7.1)
//
// `auth::AuthManager` -- registration, password verification, sessions, tokens,
// API keys, its own audit trail -- existed in full and had no caller anywhere
// in the crate. The only way to become a principal was `rbac_principal(id)`,
// which asserts an identity rather than proving one: any caller could name any
// user and be treated as them.
//
// These four builtins are that missing door. `rbac_login` proves the identity
// against a stored Argon2id hash before it touches `set_principal`, so the
// principal the guard trusts is one somebody authenticated as.
//
// They are `Privileged`, and therefore denied in agent mode: logging in is how
// authority is acquired, and an agent that could acquire authority on its own
// has none. An agent receives its principal from `IRONSHELL_PRINCIPAL` or the RBAC
// config file at startup, chosen by whoever launched it.
// ------------------------------------------------------------------------

lazy_static::lazy_static! {
    /// The process-global authentication manager, sharing the RBAC store that
    /// the safety layer consults -- one user directory, not two.
    static ref GLOBAL_AUTH: std::sync::Arc<crate::auth::AuthManager> =
        std::sync::Arc::new(crate::auth::AuthManager::new(GLOBAL_RBAC.clone()));

    /// The session established by the last successful `rbac_login`.
    static ref LOGIN_SESSION: std::sync::Mutex<Option<LoginSession>> =
        std::sync::Mutex::new(None);
}

#[derive(Clone)]
struct LoginSession {
    session_id: String,
    user_id: String,
    username: String,
    expires_at: String,
}

/// Read a password from the argument if given, and interactively otherwise.
/// Refuses to prompt when stdin is not a terminal: a prompt nobody can answer
/// is a hang, and silently reading a password off a pipe is worse.
fn password_arg(builtin: &str, args: &[Value], idx: usize, prompt: &str) -> Result<String> {
    if let Some(p) = args.get(idx) {
        return match p {
            Value::Str(p) if !p.is_empty() && p.len() <= 1024 => Ok(p.clone()),
            other => Err(crate::safety::bad_arg(
                builtin,
                "a password string of 1 to 1024 bytes",
                other.type_name(),
            )),
        };
    }
    use std::io::IsTerminal;
    if !std::io::stdin().is_terminal() {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: no password given and stdin is not a terminal -- pass it as the second argument"
        )));
    }
    let got = bi_input_read_password(vec![Value::Str(prompt.to_string())], None)?;
    match got {
        Value::Str(p) if !p.is_empty() => Ok(p),
        _ => Err(crate::safety::arg_err(format!(
            "{builtin}: no password entered"
        ))),
    }
}

/// rbac_register(username, password?) - Create a credentialed user. With no
/// password argument, prompts twice and requires the two to match. The password
/// is stored as an Argon2id PHC string, never in the clear and never as a bare
/// digest.
fn bi_rbac_register(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let username = rbac_user_id("rbac_register", args.first())?;
    let password = password_arg(
        "rbac_register",
        &args,
        1,
        &format!("Password for {username}: "),
    )?;
    if args.get(1).is_none() {
        let again = password_arg("rbac_register", &[], 0, "Repeat password: ")?;
        if again != password {
            return Err(crate::safety::arg_err(
                "rbac_register: the two passwords do not match",
            ));
        }
    }
    let _ = global_rbac(); // install the shared store into the safety layer
    if global_rbac().get_user_by_username(&username).is_some() {
        return Err(crate::safety::bad_arg(
            "rbac_register",
            "a username that is not yet registered",
            &format!("{username:?}, which is registered already"),
        ));
    }
    let user = GLOBAL_AUTH.register_user(&username, &password)?;
    let mut rec = BTreeMap::new();
    rec.insert("user".to_string(), Value::Str(user.username));
    rec.insert("user_id".to_string(), Value::Str(user.id));
    Ok(Value::Record(rec))
}

/// rbac_login(username, password?) - Authenticate and become that principal.
/// With no password argument, prompts (terminal only). On success the acting
/// principal is set to the authenticated user id, so RBAC grants apply to a
/// proven identity rather than an asserted one.
fn bi_rbac_login(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let username = rbac_user_id("rbac_login", args.first())?;
    let password = password_arg(
        "rbac_login",
        &args,
        1,
        &format!("Password for {username}: "),
    )?;
    let _ = global_rbac();
    let result = GLOBAL_AUTH.authenticate(crate::auth::Credential::Password {
        username: username.clone(),
        password,
    })?;
    if !result.success {
        // Deliberately unspecific: which half was wrong is the attacker's
        // question, and `AuthManager` has already recorded the detail in its
        // own audit log. A coded refusal, so it is not mistaken for a crash.
        return Err(crate::safety::policy_deny(
            "rbac_login",
            "rbac_login: invalid credentials",
            "check the username and password; repeated failures are recorded in the audit trail",
        ));
    }
    let user = result.user.ok_or_else(|| {
        crate::safety::policy_deny(
            "rbac_login",
            "rbac_login: authentication succeeded without a user record",
            "this is an internal fault; do not retry with the same credentials",
        )
    })?;
    let session = result.session.ok_or_else(|| {
        crate::safety::policy_deny(
            "rbac_login",
            "rbac_login: authentication succeeded without a session",
            "this is an internal fault; do not retry with the same credentials",
        )
    })?;
    let expires_at = session.expires_at.to_rfc3339();
    let mut login = LOGIN_SESSION
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("rbac_login", "the login record"))?;
    *login = Some(LoginSession {
        session_id: session.id.clone(),
        user_id: user.id.clone(),
        username: user.username.clone(),
        expires_at: expires_at.clone(),
    });
    drop(login);
    crate::safety::set_principal(Some(user.id.clone()));
    let mut rec = BTreeMap::new();
    rec.insert("user".to_string(), Value::Str(user.username));
    rec.insert("user_id".to_string(), Value::Str(user.id));
    rec.insert("session".to_string(), Value::Str(session.id));
    rec.insert("expires_at".to_string(), Value::Str(expires_at));
    Ok(Value::Record(rec))
}

/// rbac_logout() - End the session and drop back to anonymous. Never gated:
/// giving up authority is the one privilege operation that cannot be an
/// escalation.
fn bi_rbac_logout(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // The principal is cleared before the login record is read, so a record that
    // cannot be read still leaves the shell anonymous.
    crate::safety::set_principal(None);
    let was = LOGIN_SESSION
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("rbac_logout", "the login record"))?
        .take();
    match was {
        Some(s) => {
            // The local principal was cleared above. If the auth store cannot
            // end the session, say so rather than report a clean logout.
            GLOBAL_AUTH.logout(&s.session_id).map_err(|e| {
                crate::safety::io_fault(
                    "rbac_logout",
                    &format!(
                        "the local login was cleared, but the auth store did not end session {}: {e}",
                        s.session_id
                    ),
                    "this shell is anonymous again; the session may stay valid in the auth store until it expires, so revoke it there",
                )
            })?;
            Ok(Value::Bool(true))
        }
        None => Ok(Value::Bool(false)),
    }
}

/// rbac_session() - The current login session as a record, or null when
/// anonymous or expired. Read-only, so an agent can always ask who it is.
fn bi_rbac_session(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // A poisoned table is not "anonymous": the session in it may still be live.
    let current = LOGIN_SESSION
        .lock()
        .map_err(|_| crate::safety::lock_poisoned("rbac_session", "the login session"))?
        .clone();
    let Some(s) = current else {
        return Ok(Value::Null);
    };
    // An expired session is not a session. Report it as gone and clear the
    // principal, rather than leaving the guard trusting a dead identity.
    if GLOBAL_AUTH.validate_session(&s.session_id).is_none() {
        let _ = bi_rbac_logout(vec![], None);
        return Ok(Value::Null);
    }
    let mut rec = BTreeMap::new();
    rec.insert("user".to_string(), Value::Str(s.username));
    rec.insert("user_id".to_string(), Value::Str(s.user_id));
    rec.insert("session".to_string(), Value::Str(s.session_id));
    rec.insert("expires_at".to_string(), Value::Str(s.expires_at));
    Ok(Value::Record(rec))
}

/// audit_tail(n?) - Return the most recent n audit entries (default 20) from the
/// active hash-chained log as an array of records, so an agent can review what
/// it did and what was allowed/denied/approved. Read-only.
fn bi_audit_tail(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // A count that is not a count used to fall back silently to 20, and a
    // huge one read the whole log into the agent's context. Both are refused.
    const MAX_TAIL: usize = 10_000;
    let n = match args.first() {
        None => 20,
        Some(Value::Int(k)) if (0..=MAX_TAIL as i64).contains(k) => *k as usize,
        other => {
            return Err(crate::safety::bad_arg(
                "audit_tail",
                &format!("an Int from 0 to {MAX_TAIL} (the default is 20)"),
                other.map_or("nothing", Value::type_name),
            ))
        }
    };
    // `read_audit_tail` answers [] for a missing or unreadable log alike. Look
    // first, so "nothing was recorded" and "the log cannot be read" stay
    // different answers.
    let Some(path) = crate::safety::audit_path() else {
        return Err(crate::safety::bad_state_with_hint(
            "audit_tail",
            "no audit log is active",
            "run in agent mode, or set IRONSHELL_AUDIT_LOG to a file",
        ));
    };
    match std::fs::File::open(&path) {
        Ok(_) => {}
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Value::Array(Vec::new())),
        Err(e) => return Err(crate::safety::fs_error("audit_tail", &path, &e)),
    }
    let entries: Vec<Value> = crate::safety::read_audit_tail(n)
        .iter()
        .map(Value::from_json)
        .collect();
    Ok(Value::Array(entries))
}

/// approve(token) - Grant a safety approval token in-process so a subsequent
/// guarded action bound to that token may proceed. Pairs with the
/// E_NEEDS_APPROVAL error returned by guarded builtins in agent mode (§7.2).
fn bi_approve(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let token = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "approve: expected an approval token string",
            ))
        }
    };

    // The approver must not be the party being approved (AS-2026-02's sibling,
    // AS-2026-01).
    //
    // §5.3 grades `Destructive` and `Exec` as *approve* in agent mode, and §7.2
    // documents the loop as `E_NEEDS_APPROVAL` -> `approve(token)` -> re-run.
    // That loop is right for a human at a REPL and wrong for an agent, because
    // the agent holds the token it was just refused with: demonstrated in
    // `tests/approval_self_grant.rs`, where the denied call succeeds on retry.
    // Against an agent that errs the second step is a real speed bump; against
    // one that is adversarial or prompt-injected the `approve` cell is simply
    // `allow`.
    //
    // So the in-band path is refused in agent mode only. Human mode is
    // untouched, and the out-of-band channel the design already provides —
    // `IRONSHELL_APPROVE` / `IRONSHELL_APPROVE_ALL`, set by whoever launches the
    // agent — still works. No capability is removed that was not already
    // reachable by someone outside the agent's control.
    if crate::safety::current_mode() == crate::safety::Mode::Agent {
        return Err(anyhow::Error::new(crate::safety::SafetyError {
            code: crate::safety::ErrorCode::PolicyDeny,
            message: "approve: an agent may not approve its own call".to_string(),
            builtin: "approve".to_string(),
            hint: "the token was issued to the caller that was refused, so spending it \
                   here would make the approval gate self-service; approve out of band \
                   with IRONSHELL_APPROVE=<token> (or IRONSHELL_APPROVE_ALL=1 for trusted \
                   automation), which is set by whoever launched the agent"
                .to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: String::new(),
            got: String::new(),
            extra: serde_json::Map::new(),
        }));
    }

    crate::safety::grant_approval(&token);
    let mut rec = BTreeMap::new();
    rec.insert("approved".to_string(), Value::Bool(true));
    rec.insert("token".to_string(), Value::Str(token));
    Ok(Value::Record(rec))
}

/// The note on an `audit_verify` record whose chain is not keyed.
const UNKEYED_AUDIT_NOTE: &str = "the chain is not keyed: set IRONSHELL_AUDIT_KEY so an edited log cannot be re-chained; set IRONSHELL_AUDIT_LOG to keep the log outside the workspace";

/// audit_verify(path?) - Verify the tamper-evident, hash-chained audit log
/// (§7.5). With no argument, verifies the currently active log. Returns a
/// record {valid, entries, path, keyed} or {valid: false, error, path, keyed}.
/// An unkeyed chain also carries a note. A log that does not exist is an
/// E_NOT_FOUND error naming the path, not a record.
fn bi_audit_verify(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) if !s.is_empty() => std::path::PathBuf::from(s),
        // An argument that is present but not a path is an error, not a
        // request to verify the active log instead.
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "audit_verify",
                "a path string to a log file (or no argument for the active log)",
                other.type_name(),
            ))
        }
        None => match crate::safety::audit_path() {
            Some(p) => p,
            None => {
                return Err(crate::safety::bad_state_with_hint(
                    "audit_verify",
                    "no audit log is active",
                    "pass the path of a log to verify, or run in agent mode, which keeps one",
                ))
            }
        },
    };
    // A log that is not there is an error, not a verdict: `valid: false` for a
    // file that does not exist reads like a broken chain. A remote share is not
    // probed, since asking Windows about one opens a session to its host.
    let shown = path.to_string_lossy().to_string();
    if !crate::safety::names_a_remote_share(&shown)
        && matches!(std::fs::metadata(&path), Err(ref e) if e.kind() == std::io::ErrorKind::NotFound)
    {
        return Err(crate::safety::not_found("audit_verify", "file", &shown));
    }
    let mut rec = BTreeMap::new();
    rec.insert("path".to_string(), Value::Str(shown));
    // Whether the chain is keyed says how much a `valid` answer proves: an
    // unkeyed chain can be rewritten end to end by anyone who can write the
    // file, so it shows corruption, not tampering.
    let keyed = crate::safety::audit_key().is_some();
    rec.insert("keyed".to_string(), Value::Bool(keyed));
    if !keyed {
        let note = match crate::safety::audit_key_rejected() {
            Some(var) => format!(
                "{} is set, but the key it gives is shorter than 32 characters, so the chain is not keyed; {}",
                var, UNKEYED_AUDIT_NOTE
            ),
            None => UNKEYED_AUDIT_NOTE.to_string(),
        };
        rec.insert("note".to_string(), Value::Str(note));
    }
    match crate::safety::verify_audit(&path) {
        // A log with no entries is what a truncation leaves behind, so it
        // attests to nothing and must not read as valid.
        Ok(0) => {
            rec.insert("valid".to_string(), Value::Bool(false));
            rec.insert("entries".to_string(), Value::Int(0));
            rec.insert(
                "error".to_string(),
                Value::Str(
                    "the log holds no entries, so there is nothing it attests to".to_string(),
                ),
            );
        }
        Ok(n) => {
            rec.insert("valid".to_string(), Value::Bool(true));
            rec.insert("entries".to_string(), Value::Int(n as i64));
        }
        Err(e) => {
            rec.insert("valid".to_string(), Value::Bool(false));
            rec.insert("error".to_string(), Value::Str(e));
        }
    }
    Ok(Value::Record(rec))
}

/// now() - Get current Unix timestamp in seconds
fn bi_now(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    use std::time::{SystemTime, UNIX_EPOCH};
    let duration = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| {
        crate::safety::io_fault(
            "now",
            "the system clock reads earlier than 1970",
            "set the system clock, then retry",
        )
    })?;
    Ok(Value::Int(duration.as_secs() as i64))
}

/// sort_by(key, order?) - Sort rows by a field name or a lambda key
/// Usage: arr | sort_by(fn(x) => x.name) or arr | sort_by("size", "desc")
/// The order is asc or desc in any letter case; anything else is refused.
fn bi_sort_by(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    let arr = input
        .as_ref()
        .and_then(|v| match v {
            Value::Array(a) => Some(a.as_slice()),
            _ => None,
        })
        .or_else(|| {
            args.first().and_then(|v| match v {
                Value::Array(a) => Some(a.as_slice()),
                _ => None,
            })
        })
        .ok_or_else(|| crate::safety::arg_err("sort_by requires array input"))?;

    // The arguments after the subject: a key, then an optional order. The
    // subject is the first argument only when no piped Array took its place.
    let positional: &[Value] = if matches!(input, Some(Value::Array(_))) {
        &args
    } else {
        args.get(1..).unwrap_or(&[])
    };
    if positional.len() > 2 {
        return Err(crate::safety::bad_arg_with_hint(
            "sort_by",
            "a key and an optional order: sort_by(key, \"asc\" or \"desc\")",
            &format!("{} arguments", positional.len()),
            "pass the key first, then asc or desc",
        ));
    }

    // A lone "asc" or "desc" is a direction with no key, so it is refused
    // rather than read as a field named that. A field with such a name needs
    // the lambda form.
    let is_direction = |v: &Value| matches!(v, Value::Str(s) if s.eq_ignore_ascii_case("asc") || s.eq_ignore_ascii_case("desc"));
    let key = match positional.first() {
        Some(v) if matches!(v, Value::Lambda(_)) => Some(v),
        Some(v) if matches!(v, Value::Str(_)) && !(positional.len() == 1 && is_direction(v)) => {
            Some(v)
        }
        _ => None,
    };
    let (lambda, field) = match key {
        Some(Value::Lambda(l)) => (Some(l), None),
        Some(Value::Str(s)) => (None, Some(s)),
        _ => {
            return Err(crate::safety::bad_arg(
                "sort_by",
                "a key: either a field name (\"size\") or a lambda (fn(x) => x.size)",
                "neither",
            ))
        }
    };

    // Ascending unless the order says desc. Any other word is refused, not
    // ignored: a sideways order sorted the rows the same as asc did.
    let descending = match positional.get(1) {
        None => false,
        Some(Value::Str(s)) if s.eq_ignore_ascii_case("asc") => false,
        Some(Value::Str(s)) if s.eq_ignore_ascii_case("desc") => true,
        Some(other) => {
            let got = match other {
                Value::Str(s) => format!("\"{s}\""),
                o => o.type_name().to_string(),
            };
            return Err(crate::safety::bad_arg_with_hint(
                "sort_by",
                "an order of \"asc\" or \"desc\"",
                &got,
                "pass asc or desc, in any letter case, or leave the order out for ascending",
            ));
        }
    };

    // Extract keys for each element. A row with no such field is refused, not
    // given a Null key: a Null key has no place in the order.
    let mut keyed: Vec<(Value, Value)> = Vec::with_capacity(arr.len());
    for (row, item) in arr.iter().enumerate() {
        let key =
            match (lambda, field) {
                (Some(l), _) => call_lambda(l, &[item.clone()], env)?,
                (None, Some(f)) => match item {
                    Value::Record(m) => match m.get(f) {
                        Some(v) => v.clone(),
                        None => {
                            let keys: Vec<&str> = m.keys().map(String::as_str).collect();
                            return Err(sort_by_missing_field(
                                row,
                                f,
                                crate::builtins::nearest_names(f, keys.iter().copied()),
                                crate::safety::record_keys_hint(keys.iter().copied()),
                            ));
                        }
                    },
                    other => return Err(crate::safety::bad_arg_with_hint(
                        "sort_by",
                        "records when sorting by a field name",
                        other.type_name(),
                        "use the lambda form, sort_by(fn(r) => ...), for rows that are not records",
                    )),
                },
                (None, None) => Value::Null,
            };
        keyed.push((key, item.clone()));
    }

    // Keys must all be numbers or all Strings, as `sort` requires of its
    // elements. A Null, a Bool, or a number among Strings has no order, and the
    // rows would come back in input order with exit 0.
    let mut first_kind: Option<&'static str> = None;
    for (row, (key, _)) in keyed.iter().enumerate() {
        let kind = match key {
            Value::Int(_) | Value::Float(_) => "number",
            Value::Str(_) => "String",
            _ => "",
        };
        if kind.is_empty() || matches!(first_kind, Some(f) if f != kind) {
            return Err(sort_by_unordered_key(row, key));
        }
        if first_kind.is_none() {
            first_kind = Some(kind);
        }
    }

    // Sort by keys
    keyed.sort_by(|(a, _), (b, _)| {
        let cmp = sort_compare_values(a, b);
        if descending {
            cmp.reverse()
        } else {
            cmp
        }
    });

    let result: Vec<Value> = keyed.into_iter().map(|(_, v)| v).collect();
    Ok(Value::Array(result))
}

/// A row that has no field named `field`: the E_UNKNOWN_FIELD the lambda form
/// gives, with the row named and the candidates from that row's own fields.
fn sort_by_missing_field(
    row: usize,
    field: &str,
    candidates: Vec<String>,
    hint: String,
) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::UnknownField,
        message: format!("sort_by: row {row} has no field '{field}'"),
        builtin: "sort_by".to_string(),
        hint,
        approval: None,
        did_you_mean: candidates,
        expected: String::new(),
        got: String::new(),
        extra: serde_json::Map::new(),
    })
}

/// A key `sort_by` cannot order: a Null, a Bool, or a value of another kind
/// than the rows before it.
fn sort_by_unordered_key(row: usize, key: &Value) -> anyhow::Error {
    let shown = match key {
        Value::Str(s) => format!("\"{s}\""),
        Value::Int(_) | Value::Float(_) => key.to_display_string(),
        other => other.type_name().to_string(),
    };
    crate::safety::bad_arg_in(
        "sort_by",
        format!("sort_by: row {row}'s key is {shown}; keys must all be numbers or all strings"),
        "filter the rows with where first, or give every row a key in the lambda, such as a default for a missing value",
    )
}

/// Helper to compare two values for sorting
fn sort_compare_values(a: &Value, b: &Value) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => x.cmp(y),
        (Value::Float(x), Value::Float(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
        (Value::Int(x), Value::Float(y)) => (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal),
        (Value::Float(x), Value::Int(y)) => x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal),
        (Value::Str(x), Value::Str(y)) => x.cmp(y),
        (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
        _ => Ordering::Equal,
    }
}

/// save_json(path, value?) - Save value as JSON to file
/// Usage: data | save_json("output.json") or save_json("output.json", data)
fn bi_save_json(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err("save_json requires a file path"));
    }

    let path = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "save_json",
                "path: String",
                other.type_name(),
            ))
        }
    };

    // Piped: the value is the input and the path is the only argument.
    // Unpiped: path, then value. A piped value used to be ignored whenever a
    // second argument was present.
    let value = match (input, args.len()) {
        (Some(_), n) if n > 1 => {
            return Err(crate::safety::bad_arg(
                "save_json",
                "with piped input, the path only",
                &format!("{n} arguments"),
            ))
        }
        (Some(v), _) => v,
        (None, 2) => args[1].clone(),
        (None, 1) => return Err(crate::safety::arg_err("save_json requires a value to save")),
        (None, n) => {
            return Err(crate::safety::bad_arg(
                "save_json",
                "a path and a value (or a path and piped input)",
                &format!("{n} arguments"),
            ))
        }
    };

    // The write is jailed like every other local write: a relative path lands
    // in the workspace, and an absolute path outside it is refused. Before this
    // call nothing checked the path, so an agent could write any file.
    let path = guard_local_write("save_json", &path)?;

    // Convert Value to JSON: a NaN or an infinity is refused before the write.
    let json = value_to_json_strict("save_json", &value, "value")?;
    let json_str = serde_json::to_string_pretty(&json).map_err(|e| {
        crate::safety::arg_err(format!(
            "save_json: the value cannot be written as JSON: {e}"
        ))
    })?;

    // An existing file is replaced, and the record says so: a save that quietly
    // destroyed an earlier file is the surprise to avoid.
    let overwrote = std::path::Path::new(&path).exists();
    crate::tx::snapshot(&path); // record pre-save state if a transaction is active
    write_file_atomically("save_json", &path, json_str.as_bytes())?;

    let mut record = BTreeMap::new();
    record.insert("path".to_string(), Value::Str(path));
    record.insert("bytes".to_string(), Value::Int(json_str.len() as i64));
    record.insert("overwrote".to_string(), Value::Bool(overwrote));
    record.insert("success".to_string(), Value::Bool(true));

    Ok(Value::Record(record))
}

/// mcp_server_start(config) - Start a custom MCP server
/// Usage: mcp_server_start({name: "fs", type: "builtin", config: {...}})
fn bi_mcp_server_start(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("mcp_server_start", &input)?;
    let config = match args.first() {
        Some(Value::Record(r)) => r,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "mcp_server_start",
                "config: Record",
                other.type_name(),
            ))
        }
        None => {
            return Err(crate::safety::bad_arg(
                "mcp_server_start",
                "config: Record",
                "nothing",
            ))
        }
    };

    // Keys this declaration does not describe are refused rather than dropped,
    // and a name or type that is not text is refused rather than replaced by a
    // default ("default", "builtin").
    for key in config.keys() {
        if !matches!(key.as_str(), "name" | "type" | "endpoint" | "config") {
            return Err(crate::safety::bad_arg(
                "mcp_server_start",
                "config keys name, type, endpoint, config",
                key,
            ));
        }
    }
    let text_field = |key: &str, default: &str| -> Result<String> {
        match config.get(key) {
            None => Ok(default.to_string()),
            Some(v) => Ok(expect_string("mcp_server_start", v)?.to_string()),
        }
    };
    let name = text_field("name", "default")?;
    let server_type = text_field("type", "builtin")?;

    // This reported status "started" with an endpoint on a port derived from
    // the clock, and started nothing. It now says what it is: a declaration.
    // `ish mcp serve` is the real server.
    let mut result = BTreeMap::new();
    result.insert("name".to_string(), Value::Str(name));
    result.insert("type".to_string(), Value::Str(server_type));
    if let Some(ep) = config.get("endpoint") {
        result.insert("endpoint".to_string(), ep.clone());
    }
    result.insert(
        "status".to_string(),
        Value::Str("declared (not started)".to_string()),
    );
    result.insert(
        "hint".to_string(),
        Value::Str("run `ish mcp serve` to start an MCP server".to_string()),
    );
    if let Some(inner_config) = config.get("config") {
        result.insert("config".to_string(), inner_config.clone());
    }
    Ok(Value::Record(result))
}

/// Prefix for an MCP server's tools in an agent's tool list. Without an endpoint
/// it is stripped from a builtin name; with one, a name that carries it is a
/// server tool only when the server's own tools/list names it.
const AGENT_MCP_PREFIX: &str = "mcp:";

/// A tool name the endpoint may serve: ASCII letters, digits, `_`, `-` and `.`,
/// at most 128 bytes. The name goes into a request path, so it is checked first.
fn is_plain_mcp_tool_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 128
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
}

/// Split the requested tool names between the endpoint's tools and the builtins.
/// Without an endpoint (`endpoint_tools` is None) every name is a builtin with
/// any `mcp:` prefix stripped. With one, `mcp:<t>` is a server tool only when `t`
/// is a plain name the server lists; any other `mcp:` name stays as written, so
/// it is refused as unknown rather than run as a builtin of the same name.
/// Returns (server tool names, builtin names).
fn split_agent_tool_names(
    requested: &[String],
    endpoint_tools: Option<&[String]>,
) -> (Vec<String>, Vec<String>) {
    let mut remote: Vec<String> = Vec::new();
    let mut builtin: Vec<String> = Vec::new();
    for name in requested {
        let raw = name.as_str();
        let Some(served) = endpoint_tools else {
            builtin.push(
                raw.strip_prefix(AGENT_MCP_PREFIX)
                    .unwrap_or(raw)
                    .to_string(),
            );
            continue;
        };
        match raw.strip_prefix(AGENT_MCP_PREFIX) {
            Some(t) if is_plain_mcp_tool_name(t) && served.iter().any(|s| s == t) => {
                if !remote.iter().any(|r| r == t) {
                    remote.push(t.to_string());
                }
            }
            _ => builtin.push(raw.to_string()),
        }
    }
    (remote, builtin)
}

/// A tool served by the endpoint's MCP server. The agent sees it as `mcp:<tool>`.
/// Each call is guarded as a network effect and sent with the MCP client; the
/// client (and its connection) is dropped when the agent run ends.
struct AgentMcpTool {
    name: String,
    server_tool: String,
    description: String,
    endpoint: String,
    client: std::sync::Arc<crate::ai::mcp::McpClient>,
}

impl crate::ai::agents::Tool for AgentMcpTool {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn call(&self, input: &str, _env: &mut Env) -> Result<Value> {
        crate::safety::guard(crate::safety::GuardCtx {
            builtin: "agent_with_mcp",
            effect: crate::safety::Effect::Network,
            what: "request",
            targets: vec![format!("{}/{}", self.endpoint, self.server_tool)],
            blast_radius: serde_json::json!({ "tool": self.name, "endpoint": self.endpoint }),
            reversible: false,
            fs_paths: false,
        })?;
        let arguments: serde_json::Value = serde_json::from_str(input)
            .unwrap_or_else(|_| serde_json::Value::String(input.to_string()));
        self.client.validate_input(&self.server_tool, &arguments)?;
        let out = self.client.call_tool(&self.server_tool, input)?;
        Ok(Value::Str(out))
    }
}

/// Connect to an MCP server the way `mcp_connect` does: only an endpoint that
/// `detect_mcp_servers` found (its loopback probe) is matched, and no other
/// address is contacted. Returns the client and the tools the server lists.
fn connect_agent_mcp(
    endpoint: &str,
) -> Result<(
    crate::ai::mcp::McpClient,
    Vec<crate::ai::mcp::McpToolSchema>,
)> {
    let detected = crate::ai::detect_mcp_servers()
        .iter()
        .any(|s| s.endpoint == endpoint);
    if !detected {
        return Err(crate::safety::not_found(
            "agent_with_mcp",
            "detected MCP server",
            endpoint,
        ));
    }
    let client = crate::ai::mcp::McpClient::new(endpoint);
    let schemas = client.discover_tools()?;
    Ok((client, schemas))
}

/// agent_with_mcp(goal, tools, endpoint?) - Run a model-driven agent over named
/// tools. Builtin tools are in-process and every call passes the normal dispatch
/// guard. With an endpoint, the MCP server at it is connected as `mcp_connect`
/// connects (only a loopback server that `detect_mcp_servers` finds), and each
/// `mcp:<name>` it lists is a tool; each such call is guarded as a network
/// effect. The model call itself is a Network effect, so it is guarded here and
/// rate limited like `agent`. The run is `completed` only when the model gives a
/// final answer.
/// Usage: agent_with_mcp("Task description", ["mcp:read_file", "mcp:list_dir"])
fn bi_agent_with_mcp(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    refuse_piped_subject("agent_with_mcp", &input)?;
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "agent_with_mcp requires goal and tools array",
        ));
    }
    let goal_text = collab_text_arg("agent_with_mcp", "goal", args.first(), 8192)?;
    let goal = crate::security::validate_ai_prompt(&goal_text).map_err(|e| {
        crate::safety::bad_arg(
            "agent_with_mcp",
            "goal: a prompt that passes validation",
            &e.to_string(),
        )
    })?;

    let names: Vec<String> = match args.get(1) {
        Some(Value::Array(items)) => {
            if items.len() > 32 {
                return Err(crate::safety::budget_exceeded(
                    "agent_with_mcp",
                    format!(
                        "agent_with_mcp: {} tools requested; at most 32",
                        items.len()
                    ),
                    "give the agent fewer tools",
                ));
            }
            let mut out = Vec::with_capacity(items.len());
            for item in items {
                match item {
                    Value::Str(s) => out.push(s.clone()),
                    other => {
                        return Err(crate::safety::bad_arg(
                            "agent_with_mcp",
                            "tools: an array of tool names (String)",
                            other.type_name(),
                        ))
                    }
                }
            }
            out
        }
        other => {
            return Err(crate::safety::bad_arg(
                "agent_with_mcp",
                "tools: an array of tool names (String)",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // The endpoint is optional. When it is given, the server is connected before
    // any tool name is checked, because its tools/list decides what `mcp:` names mean.
    let endpoint: Option<String> = match args.get(2) {
        None | Some(Value::Null) => None,
        Some(v) => Some(expect_string("agent_with_mcp", v)?.to_string()),
    };
    let connection = match endpoint.as_deref() {
        Some(ep) => Some(connect_agent_mcp(ep)?),
        None => None,
    };
    let server_tools: Option<Vec<String>> = connection
        .as_ref()
        .map(|(_, schemas)| schemas.iter().map(|t| t.name.clone()).collect());
    let (remote, base_tools) = split_agent_tool_names(&names, server_tools.as_deref());
    let base_refs: Vec<&str> = base_tools.iter().map(String::as_str).collect();
    // The agent's own resolver answers for any name, so the check is against the
    // dispatcher: a name it does not serve is refused, not left to fail mid-run.
    for name in &base_refs {
        if !is_dispatched(name) {
            return Err(crate::safety::not_found("agent_with_mcp", "tool", name));
        }
    }

    crate::security::check_rate_limit("agent_with_mcp", 10, Duration::from_secs(60)).map_err(
        |e| {
            crate::safety::budget_exceeded(
                "agent_with_mcp",
                format!("agent_with_mcp: {e}"),
                "wait a minute before the next agent run",
            )
        },
    )?;

    let model =
        std::env::var("IRONSHELL_AGENT_MODEL_URI").unwrap_or_else(|_| "default".to_string());
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "agent_with_mcp",
        effect: crate::safety::Effect::Network,
        what: "request",
        targets: vec![model.clone()],
        blast_radius: serde_json::json!({
            "model": model,
            "max_steps": 10,
            "tools": names.clone(),
            "endpoint": endpoint.clone(),
        }),
        reversible: false,
        fs_paths: false,
    })?;

    let mut tools = crate::ai::agents::ToolRegistry::with_builtins().resolve_many(&base_refs);
    if let (Some((client, schemas)), Some(ep)) = (connection, endpoint.as_deref()) {
        let client = std::sync::Arc::new(client);
        for name in &remote {
            if let Some(schema) = schemas.iter().find(|s| &s.name == name) {
                tools.push(Box::new(AgentMcpTool {
                    name: format!("{AGENT_MCP_PREFIX}{}", schema.name),
                    server_tool: schema.name.clone(),
                    description: schema.description.clone(),
                    endpoint: ep.to_string(),
                    client: std::sync::Arc::clone(&client),
                }));
            }
        }
    }

    let max_steps = 10;
    let result =
        crate::ai::agents::run_sync_with_tools(&goal, tools, max_steps, env).map_err(|e| {
            crate::safety::tool_failed("agent_with_mcp", "model backend", None, &e.to_string())
        })?;
    if result.starts_with("(incomplete)") {
        return Err(crate::safety::budget_exceeded(
            "agent_with_mcp",
            format!("agent_with_mcp: the agent used its {max_steps} steps without a final answer"),
            "narrow the goal or the tool list, then run it again",
        ));
    }

    let mut agent_record = BTreeMap::new();
    agent_record.insert("goal".to_string(), Value::Str(goal));
    agent_record.insert(
        "tools".to_string(),
        Value::Array(names.into_iter().map(Value::Str).collect()),
    );
    agent_record.insert("type".to_string(), Value::Str("mcp_agent".to_string()));
    agent_record.insert("result".to_string(), Value::Str(result));
    agent_record.insert("status".to_string(), Value::Str("completed".to_string()));
    Ok(Value::Record(agent_record))
}

#[cfg(test)]
mod agent_mcp_endpoint_tests {
    use super::{is_plain_mcp_tool_name, split_agent_tool_names};

    fn names(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn server_tool_names_must_be_plain() {
        assert!(is_plain_mcp_tool_name("read_file"));
        assert!(is_plain_mcp_tool_name("git.log-1"));
        assert!(!is_plain_mcp_tool_name(""));
        assert!(!is_plain_mcp_tool_name("../admin"));
        assert!(!is_plain_mcp_tool_name("a/b"));
        assert!(!is_plain_mcp_tool_name("a b"));
        assert!(!is_plain_mcp_tool_name(&"x".repeat(129)));
    }

    #[test]
    fn without_an_endpoint_every_name_is_a_builtin() {
        let (remote, builtin) = split_agent_tool_names(&names(&["mcp:ls", "pwd"]), None);
        assert!(remote.is_empty());
        assert_eq!(builtin, names(&["ls", "pwd"]));
    }

    #[test]
    fn only_listed_server_tools_are_remote() {
        let server = names(&["read_file", "bad/name"]);
        let requested = names(&["mcp:read_file", "mcp:bad/name", "mcp:rm", "pwd"]);
        let (remote, builtin) = split_agent_tool_names(&requested, Some(&server));
        assert_eq!(remote, names(&["read_file"]));
        // Unlisted `mcp:` names are kept as written, so they are refused as
        // unknown and never run as the builtin of the same name.
        assert_eq!(builtin, names(&["mcp:bad/name", "mcp:rm", "pwd"]));
    }

    #[test]
    fn an_empty_server_list_serves_nothing() {
        let (remote, builtin) = split_agent_tool_names(&names(&["mcp:ls"]), Some(&[]));
        assert!(remote.is_empty());
        assert_eq!(builtin, names(&["mcp:ls"]));
    }
}

/// each(fn) - Like map but for side effects, returns original array
/// Usage: arr | each(fn(x) => print(x))
fn bi_each(args: Vec<Value>, input: Option<Value>, env: &mut Env) -> Result<Value> {
    let arr = input
        .as_ref()
        .and_then(|v| match v {
            Value::Array(a) => Some(a.clone()),
            _ => None,
        })
        .or_else(|| {
            args.first().and_then(|v| match v {
                Value::Array(a) => Some(a.clone()),
                _ => None,
            })
        })
        .ok_or_else(|| crate::safety::arg_err("each requires array input"))?;

    let lambda = args
        .iter()
        .find_map(|v| match v {
            Value::Lambda(l) => Some(l),
            _ => None,
        })
        .ok_or_else(|| crate::safety::arg_err("each requires a lambda function"))?;

    // For side effects. The results are discarded, the errors are not: this
    // was `let _ = call_lambda(..)`, so a side effect that failed (a write
    // refused, a division by zero) left `each` reporting success.
    for item in &arr {
        call_lambda(lambda, &[item.clone()], env)?;
    }

    // Return original array
    Ok(Value::Array(arr))
}

/// in(value, collection) - Check if value is in collection
/// Usage: "x" | in(["a", "b", "x"]) or in("x", ["a", "b", "x"])
fn bi_in(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Membership: `in(needle, haystack)`, or `needle | in(haystack)`. Piped, the
    // needle is the input and the haystack is the one argument.
    let (needle, haystack) = match input {
        Some(inp) => {
            if args.len() != 1 {
                return Err(crate::safety::bad_arg(
                    "in",
                    "with piped input, exactly one argument: the collection",
                    &format!("{} arguments", args.len()),
                ));
            }
            (inp, args[0].clone())
        }
        None => {
            if args.len() != 2 {
                return Err(crate::safety::bad_arg(
                    "in",
                    "a value and a collection",
                    &format!("{} arguments", args.len()),
                ));
            }
            (args[0].clone(), args[1].clone())
        }
    };

    // A haystack that cannot hold anything, or a needle of the wrong type for a
    // string or record, used to answer false. That is the same answer as "not
    // present", so a mistyped call looked like a true negative. Refuse both.
    let found = match &haystack {
        Value::Array(arr) => arr.iter().any(|v| values_equal(&needle, v)),
        Value::Str(s) => match &needle {
            Value::Str(n) => s.contains(n.as_str()),
            other => {
                return Err(crate::safety::bad_arg(
                    "in",
                    "a String needle to search a String",
                    other.type_name(),
                ))
            }
        },
        Value::Record(rec) => match &needle {
            Value::Str(key) => rec.contains_key(key),
            other => {
                return Err(crate::safety::bad_arg(
                    "in",
                    "a String key to search a Record",
                    other.type_name(),
                ))
            }
        },
        other => {
            return Err(crate::safety::bad_arg(
                "in",
                "a collection: Array, String, or Record",
                other.type_name(),
            ))
        }
    };

    Ok(Value::Bool(found))
}

/// Check if two values are equal
fn values_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Null, Value::Null) => true,
        (Value::Bool(x), Value::Bool(y)) => x == y,
        (Value::Int(x), Value::Int(y)) => x == y,
        // Exact comparison. An absolute epsilon made 1e-300 and 2e-300 equal and
        // missed large values that differ in the last bit.
        (Value::Float(x), Value::Float(y)) => x == y,
        (Value::Int(x), Value::Float(y)) | (Value::Float(y), Value::Int(x)) => {
            crate::value::cmp_int_float(*x, *y) == Some(std::cmp::Ordering::Equal)
        }
        (Value::Str(x), Value::Str(y)) => x == y,
        (Value::Array(x), Value::Array(y)) => {
            x.len() == y.len() && x.iter().zip(y.iter()).all(|(a, b)| values_equal(a, b))
        }
        (Value::Record(x), Value::Record(y)) => {
            x.len() == y.len()
                && x.iter()
                    .zip(y.iter())
                    .all(|((ka, va), (kb, vb))| ka == kb && values_equal(va, vb))
        }
        _ => false,
    }
}

// ===================== Enterprise Feature Implementations =====================

/// role_create(name, permissions, description?) - Create a new RBAC role
fn bi_role_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // With the name piped in, the arguments are the parameters; called
    // directly, the name is the first. This read permissions from args[1]
    // either way, so a piped name took the description as its permissions.
    let piped = input.is_some();
    let name = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("role_create", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("role_create: missing 'name'"))?;
    let params = if piped {
        &args[..]
    } else {
        args.get(1..).unwrap_or(&[])
    };

    // Every entry must be a {resource, actions} record. Malformed entries were
    // dropped silently, so a role could be created with fewer permissions
    // than asked for and still report "created" -- the wrong failure mode for
    // an access-control builtin.
    let bad_permission = |got: &Value| {
        crate::safety::bad_arg(
            "role_create",
            "permissions: an array of {resource: String, actions: [String]} records",
            &got.to_display_string(),
        )
    };
    let permissions = match params.first() {
        None => Vec::new(),
        Some(Value::Array(arr)) => {
            let mut out = Vec::with_capacity(arr.len());
            for p in arr {
                let Value::Record(rec) = p else {
                    return Err(bad_permission(p));
                };
                let Some(Value::Str(resource)) = rec.get("resource") else {
                    return Err(bad_permission(p));
                };
                let actions = match rec.get("actions") {
                    None => Vec::new(),
                    Some(Value::Array(a)) => a
                        .iter()
                        .map(|v| match v {
                            Value::Str(s) => Ok(s.clone()),
                            _ => Err(bad_permission(p)),
                        })
                        .collect::<Result<Vec<_>>>()?,
                    Some(_) => return Err(bad_permission(p)),
                };
                out.push(Permission {
                    resource: resource.clone(),
                    actions,
                });
            }
            out
        }
        Some(other) => return Err(bad_permission(other)),
    };

    let description = params
        .get(1)
        .map(|v| v.to_display_string())
        .unwrap_or_default();

    let role = Role {
        name: name.clone(),
        permissions,
        description,
        created_at: std::time::Instant::now(),
    };

    RBAC_ROLES.write().unwrap().insert(name.clone(), role);

    let mut result = BTreeMap::new();
    result.insert("status".to_string(), Value::Str("created".to_string()));
    result.insert("role".to_string(), Value::Str(name));
    Ok(Value::Record(result))
}

/// role_delete(name) - Delete an RBAC role
fn bi_role_delete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("role_delete", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("role_delete: missing 'name'"))?;

    let existed = RBAC_ROLES.write().unwrap().remove(&name).is_some();
    if !existed {
        return Err(crate::safety::not_found("role_delete", "role", &name));
    }
    // Take the role from every holder as well. Left in place, a role created
    // again under the same name would silently give back everyone it had.
    let mut unassigned: i64 = 0;
    for roles in USER_ROLES.write().unwrap().values_mut() {
        let before = roles.len();
        roles.retain(|r| r != &name);
        unassigned += (before - roles.len()) as i64;
    }

    let mut result = BTreeMap::new();
    result.insert("status".to_string(), Value::Str("deleted".to_string()));
    result.insert("role".to_string(), Value::Str(name));
    result.insert("users_unassigned".to_string(), Value::Int(unassigned));
    Ok(Value::Record(result))
}

/// A name argument for the role store: a non-empty string of at most 256
/// bytes with no control characters. The old form took any value and stored
/// its display text, so `1` and `"1"` were the same user.
fn role_name_arg(builtin: &str, v: Option<&Value>, what: &str) -> Result<String> {
    match v {
        Some(Value::Str(s))
            if !s.is_empty() && s.len() <= 256 && !s.chars().any(char::is_control) =>
        {
            Ok(s.clone())
        }
        other => Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: a string of 1 to 256 characters with no control characters"),
            other.map_or("nothing", Value::type_name),
        )),
    }
}

/// role_grant(user, role) - Grant a role to a user
fn bi_role_grant(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let user = role_name_arg("role_grant", args.first(), "a user name")?;
    let role = role_name_arg("role_grant", args.get(1), "a role name")?;

    if !RBAC_ROLES.read().unwrap().contains_key(&role) {
        return Err(crate::safety::not_found("role_grant", "role", &role));
    }

    // Holding a role twice is holding it once. A repeated grant reports
    // "unchanged" rather than a fresh "granted" for an edit that did nothing.
    let mut user_roles = USER_ROLES.write().unwrap();
    let held = user_roles.entry(user.clone()).or_default();
    let changed = !held.contains(&role);
    if changed {
        held.push(role.clone());
    }

    let mut result = BTreeMap::new();
    result.insert(
        "status".to_string(),
        Value::Str(if changed { "granted" } else { "unchanged" }.to_string()),
    );
    result.insert("user".to_string(), Value::Str(user));
    result.insert("role".to_string(), Value::Str(role));
    Ok(Value::Record(result))
}

/// role_revoke(user, role) - Revoke a role from a user. A role the user does
/// not hold is an error, not a quiet "not_found" status: nothing was revoked.
fn bi_role_revoke(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let user = role_name_arg("role_revoke", args.first(), "a user name")?;
    let role = role_name_arg("role_revoke", args.get(1), "a role name")?;

    let mut user_roles = USER_ROLES.write().unwrap();
    let revoked = user_roles.get_mut(&user).is_some_and(|roles| {
        let before = roles.len();
        roles.retain(|r| r != &role);
        roles.len() < before
    });
    if !revoked {
        return Err(crate::safety::not_found(
            "role_revoke",
            "grant",
            &format!("{role} held by {user}"),
        ));
    }

    let mut result = BTreeMap::new();
    result.insert("status".to_string(), Value::Str("revoked".to_string()));
    result.insert("user".to_string(), Value::Str(user));
    result.insert("role".to_string(), Value::Str(role));
    Ok(Value::Record(result))
}

/// user_roles(user) - Get roles assigned to a user
fn bi_user_roles(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let user = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("user_roles", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("user_roles: missing 'user'"))?;

    let roles = USER_ROLES
        .read()
        .unwrap()
        .get(&user)
        .cloned()
        .unwrap_or_default();

    Ok(Value::Array(roles.into_iter().map(Value::Str).collect()))
}

/// check_permission(user, resource, action) - Check if user has permission
fn bi_check_permission(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Each argument must be the string it names. Display text made `1`, `"1"`
    // and `[1]` the same user, so a non-string could be granted by name.
    let user = role_name_arg("check_permission", args.first(), "a user name")?;
    let resource = role_name_arg("check_permission", args.get(1), "a resource")?;
    let action = role_name_arg("check_permission", args.get(2), "an action")?;

    let user_roles_guard = USER_ROLES.read().unwrap();
    let roles_guard = RBAC_ROLES.read().unwrap();

    let user_role_names = user_roles_guard.get(&user).cloned().unwrap_or_default();

    let has_permission = user_role_names.iter().any(|role_name| {
        if let Some(role) = roles_guard.get(role_name) {
            role.permissions.iter().any(|p| {
                (p.resource == "*" || p.resource == resource)
                    && (p.actions.contains(&"*".to_string())
                        || p.actions.iter().any(|a| a == &action))
            })
        } else {
            false
        }
    });

    Ok(Value::Bool(has_permission))
}

/// roles_list() - List all defined roles
fn bi_roles_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let roles = RBAC_ROLES.read().unwrap();

    let result: Vec<Value> = roles
        .values()
        .map(|role| {
            let mut rec = BTreeMap::new();
            rec.insert("name".to_string(), Value::Str(role.name.clone()));
            rec.insert(
                "description".to_string(),
                Value::Str(role.description.clone()),
            );
            rec.insert(
                "permissions".to_string(),
                Value::Int(role.permissions.len() as i64),
            );
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(result))
}
/// audit_log(action, resource, details?, severity?) - Log an audit entry
fn bi_audit_log(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Entries here are the agent's own assertions about what it did, so they
    // are bounded and kept in the same chained log as the shell's decisions,
    // labelled `asserted`, rather than sitting in memory where nothing can
    // say who put them there.
    const MAX_ENTRIES: usize = 10_000;
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "audit_log: requires action and resource arguments",
        ));
    }
    let action = audit_text_arg("audit_log", args.first(), "an action", false)?;
    let resource = audit_text_arg("audit_log", args.get(1), "a resource", false)?;
    let details = match args.get(2) {
        None => String::new(),
        Some(v) => audit_text_arg("audit_log", Some(v), "details", true)?,
    };
    let severity = match args.get(3) {
        None => AuditSeverity::Info,
        Some(Value::Str(s)) => match s.as_str() {
            "info" => AuditSeverity::Info,
            "warning" => AuditSeverity::Warning,
            "critical" => AuditSeverity::Critical,
            _ => {
                return Err(crate::safety::bad_arg(
                    "audit_log",
                    "a severity of info, warning or critical",
                    &format!("{s:?}"),
                ))
            }
        },
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "audit_log",
                "a severity of info, warning or critical",
                other.type_name(),
            ))
        }
    };

    if AUDIT_LOG.read().unwrap().len() >= MAX_ENTRIES {
        return Err(crate::safety::budget_exceeded(
            "audit_log",
            format!("the audit list holds {MAX_ENTRIES} entries and takes no more"),
            "entries are not dropped to make room; the chained audit log keeps the full record",
        ));
    }

    let id = format!(
        "audit_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let user = crate::safety::current_principal()
        .or_else(|| std::env::var("USER").ok())
        .unwrap_or_else(|| "system".to_string());

    // The chained log is what `audit_verify` checks. An assertion that lands
    // there is attributable and tamper-evident; `decision: asserted` says it
    // is a claim, not a decision the shell made. A required write that fails
    // is an error here, not a "logged" result: the entry is not kept in memory
    // either, so nothing reports it as logged.
    if let Err(e) = crate::safety::audit(
        "audit_log",
        crate::safety::Effect::WriteLocal,
        "asserted",
        &resource,
        serde_json::json!({
            "id": id,
            "action": action,
            "details": details,
            "severity": severity.as_str(),
            "user": user,
        }),
    ) {
        return Err(crate::safety::io_fault(
            "audit_log",
            &format!("the audit entry was not logged: {e}"),
            "the required audit log could not be written (IRONSHELL_AUDIT_REQUIRED is set); fix the audit log path or unset IRONSHELL_AUDIT_REQUIRED, then retry",
        ));
    }

    let entry = AuditEntry {
        id: id.clone(),
        timestamp: std::time::Instant::now(),
        user,
        action,
        resource,
        details,
        severity,
        success: true,
    };

    AUDIT_LOG
        .write()
        .map_err(|_| crate::safety::lock_poisoned("audit_log", "the in-process audit list"))?
        .push(entry);

    let mut result = BTreeMap::new();
    result.insert("status".to_string(), Value::Str("logged".to_string()));
    result.insert("id".to_string(), Value::Str(id));
    Ok(Value::Record(result))
}

/// A text field of an audit entry. Control characters are refused: a field
/// with a newline or a tab is how a reader of the plain-text view is misled
/// about where one entry ends and the next begins.
fn audit_text_arg(
    builtin: &str,
    v: Option<&Value>,
    what: &str,
    allow_empty: bool,
) -> Result<String> {
    const MAX: usize = 4096;
    match v {
        Some(Value::Str(s))
            if (allow_empty || !s.is_empty())
                && s.len() <= MAX
                && !s.chars().any(char::is_control) =>
        {
            Ok(s.clone())
        }
        other => Err(crate::safety::bad_arg(
            builtin,
            &format!(
                "{what}: a string of {}{MAX} bytes or fewer with no control characters",
                if allow_empty { "" } else { "1 to " }
            ),
            other.map_or("nothing", Value::type_name),
        )),
    }
}

/// audit_query(filter?) - Query audit log entries
fn bi_audit_query(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // A filter that is not a record, or names a field the log does not have,
    // used to be ignored, and the query then answered with everything. That
    // reads as a filtered answer, so it is refused.
    let filter = match args.first() {
        None => None,
        Some(Value::Record(rec)) => {
            if let Some(bad) = rec
                .keys()
                .find(|k| !matches!(k.as_str(), "builtin" | "action" | "resource"))
            {
                return Err(crate::safety::bad_arg(
                    "audit_query",
                    "a filter with only the fields builtin (or its alias action) and resource",
                    &format!("field {bad:?}"),
                ));
            }
            Some(rec.clone())
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "audit_query",
                "a filter Record such as {builtin: \"file_replace\"}",
                other.type_name(),
            ))
        }
    };

    // With a chained log active, the query reads the entries `audit_verify`
    // checks, as records, so a filter on `builtin` finds the calls the gate saw.
    if let Some(entries) = chained_audit_entries("audit_query")? {
        let rows: Vec<Value> = entries
            .iter()
            .filter(|e| chained_entry_matches(e, filter.as_ref()))
            .map(Value::from_json)
            .collect();
        return Ok(Value::Array(rows));
    }

    let log = AUDIT_LOG.read().unwrap();

    let entries: Vec<Value> = log
        .iter()
        .filter(|e| {
            if let Some(ref f) = filter {
                // In-process assertions were all recorded by audit_log, so the
                // name a filter gives is the action they were asserted under.
                let action_match = f
                    .get("action")
                    .or_else(|| f.get("builtin"))
                    .map(|v| e.action.contains(&v.to_display_string()))
                    .unwrap_or(true);
                let resource_match = f
                    .get("resource")
                    .map(|v| e.resource.contains(&v.to_display_string()))
                    .unwrap_or(true);
                action_match && resource_match
            } else {
                true
            }
        })
        .map(|e| {
            let mut rec = BTreeMap::new();
            rec.insert("id".to_string(), Value::Str(e.id.clone()));
            rec.insert("user".to_string(), Value::Str(e.user.clone()));
            rec.insert("action".to_string(), Value::Str(e.action.clone()));
            rec.insert("resource".to_string(), Value::Str(e.resource.clone()));
            rec.insert(
                "severity".to_string(),
                Value::Str(e.severity.as_str().to_string()),
            );
            rec.insert("success".to_string(), Value::Bool(e.success));
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(entries))
}

/// audit_export(format?) - Export audit log
fn bi_audit_export(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let format = args
        .first()
        .map(|v| v.to_display_string())
        .unwrap_or_else(|| "json".to_string());
    // The format was echoed back and otherwise ignored: audit_export("csv")
    // answered {format: "csv"} around the same records. Records are the only
    // shape produced, so only "json" is honest.
    if format != "json" {
        return Err(crate::safety::bad_arg(
            "audit_export",
            "format \"json\" (the only one implemented; the entries are records)",
            &format!("{format:?}"),
        ));
    }

    let log = AUDIT_LOG.read().unwrap();

    let entries: Vec<Value> = log
        .iter()
        .map(|e| {
            let mut rec = BTreeMap::new();
            rec.insert("id".to_string(), Value::Str(e.id.clone()));
            rec.insert("user".to_string(), Value::Str(e.user.clone()));
            rec.insert("action".to_string(), Value::Str(e.action.clone()));
            rec.insert("resource".to_string(), Value::Str(e.resource.clone()));
            rec.insert("details".to_string(), Value::Str(e.details.clone()));
            rec.insert(
                "severity".to_string(),
                Value::Str(e.severity.as_str().to_string()),
            );
            rec.insert("success".to_string(), Value::Bool(e.success));
            Value::Record(rec)
        })
        .collect();

    let mut result = BTreeMap::new();
    result.insert("format".to_string(), Value::Str(format));
    result.insert("count".to_string(), Value::Int(entries.len() as i64));
    result.insert("entries".to_string(), Value::Array(entries));
    Ok(Value::Record(result))
}

/// The entries of the chained audit log that `audit_verify` reads with no
/// argument, one per line, oldest first. `None` when no log is active; a log
/// not yet written holds nothing. Shared so that the statistics, the query and
/// the verifier all count the same entries.
fn chained_audit_entries(builtin: &str) -> Result<Option<Vec<serde_json::Value>>> {
    let Some(path) = crate::safety::audit_path() else {
        return Ok(None);
    };
    let content = match std::fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Some(Vec::new())),
        Err(e) => return Err(crate::safety::fs_error(builtin, &path, &e)),
    };
    Ok(Some(
        content
            .lines()
            .filter(|l| !l.trim().is_empty())
            .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
            .collect(),
    ))
}

/// Whether a chained entry matches an `audit_query` filter. `builtin` names the
/// call the entry records, and `action` is its alias. An `audit_log` assertion
/// records its own name in `detail.action`, which `action` also matches.
fn chained_entry_matches(
    entry: &serde_json::Value,
    filter: Option<&BTreeMap<String, Value>>,
) -> bool {
    let Some(filter) = filter else {
        return true;
    };
    fn text(v: Option<&serde_json::Value>) -> &str {
        v.and_then(|v| v.as_str()).unwrap_or("")
    }
    let builtin_ok = ["builtin", "action"]
        .iter()
        .all(|key| match filter.get(*key) {
            Some(want) => {
                let want = want.to_display_string();
                text(entry.get("builtin")).contains(&want)
                    || text(entry.get("detail").and_then(|d| d.get("action"))).contains(&want)
            }
            None => true,
        });
    let resource_ok = filter.get("resource").map_or(true, |want| {
        text(entry.get("resource")).contains(&want.to_display_string())
    });
    builtin_ok && resource_ok
}

/// audit_stats() - Get audit log statistics.
///
/// `total` and `by_decision` count the chained log that `audit_verify` reads,
/// so the two agree. With no active log they are the in-process list's count.
/// `info`, `warning` and `critical` count the in-process `audit_log` assertions
/// by severity, which the chained entries do not carry.
fn bi_audit_stats(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let log = AUDIT_LOG.read().unwrap();

    let mut info_count = 0;
    let mut warning_count = 0;
    let mut critical_count = 0;

    for entry in log.iter() {
        match entry.severity {
            AuditSeverity::Info => info_count += 1,
            AuditSeverity::Warning => warning_count += 1,
            AuditSeverity::Critical => critical_count += 1,
        }
    }

    let chained = chained_audit_entries("audit_stats")?;
    let mut by_decision: BTreeMap<String, i64> = BTreeMap::new();
    let total = match &chained {
        Some(entries) => {
            for entry in entries {
                let decision = entry
                    .get("decision")
                    .and_then(|d| d.as_str())
                    .unwrap_or("unknown");
                *by_decision.entry(decision.to_string()).or_insert(0) += 1;
            }
            entries.len()
        }
        None => log.len(),
    };

    let mut result = BTreeMap::new();
    result.insert("total".to_string(), Value::Int(total as i64));
    result.insert(
        "by_decision".to_string(),
        Value::Record(
            by_decision
                .into_iter()
                .map(|(k, n)| (k, Value::Int(n)))
                .collect(),
        ),
    );
    result.insert("info".to_string(), Value::Int(info_count));
    result.insert("warning".to_string(), Value::Int(warning_count));
    result.insert("critical".to_string(), Value::Int(critical_count));
    Ok(Value::Record(result))
}
/// sso_init(provider, client_id, issuer_url) - Initialize SSO configuration
fn bi_sso_init(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.len() < 3 {
        return Err(crate::safety::arg_err(
            "sso_init: requires provider, client_id, and issuer_url arguments",
        ));
    }
    let provider_str = role_name_arg("sso_init", args.first(), "a provider name")?;
    let client_id = role_name_arg("sso_init", args.get(1), "a client id")?;
    let issuer_url = role_name_arg("sso_init", args.get(2), "an issuer URL")?;

    let provider = SsoProvider::from_str(&provider_str).ok_or_else(|| {
        crate::safety::bad_arg(
            "sso_init",
            "a provider of oauth2, saml or oidc",
            &format!("{provider_str:?}"),
        )
    })?;
    // The issuer is where tokens will be trusted from, so it must be an
    // https address (plain http is allowed only for a loopback host).
    let loopback =
        issuer_url.starts_with("http://localhost") || issuer_url.starts_with("http://127.0.0.1");
    if !(issuer_url.starts_with("https://") || loopback) {
        return Err(crate::safety::bad_arg(
            "sso_init",
            "an issuer URL beginning https:// (http:// only for localhost)",
            &format!("{issuer_url:?}"),
        ));
    }

    let config = SsoConfig {
        provider,
        client_id,
        issuer_url,
        enabled: true,
    };

    *SSO_CONFIG.write().unwrap() = Some(config);
    // Tokens issued under the previous configuration are not honoured under
    // the new one.
    SSO_SESSIONS.write().unwrap().clear();

    let mut result = BTreeMap::new();
    result.insert("status".to_string(), Value::Str("initialized".to_string()));
    result.insert("provider".to_string(), Value::Str(provider_str));
    Ok(Value::Record(result))
}

/// sso_auth(callback_data) - Authenticate via SSO.
///
/// Not implemented. The callback is not exchanged with the identity provider
/// and its signature is not checked, so there is no identity to attest to.
/// This builtin used to accept any input, mint a token and name the user
/// `user_<length of the input>`, which made every SSO-gated check pass for
/// whoever called it.
fn bi_sso_auth(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Err(crate::safety::unimplemented(
        "sso_auth",
        "does not verify the callback with the identity provider, so it cannot say who authenticated; no token is issued",
        "use rbac_login with a local account for an authenticated principal",
    ))
}

/// sso_validate(token) - Validate an SSO token
fn bi_sso_validate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let token = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("sso_validate", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("sso_validate: missing 'token'"))?;

    let user_id = SSO_SESSIONS.read().unwrap().get(&token).cloned();
    let mut result = BTreeMap::new();
    result.insert("valid".to_string(), Value::Bool(user_id.is_some()));
    if let Some(uid) = user_id {
        result.insert("user_id".to_string(), Value::Str(uid));
    }
    Ok(Value::Record(result))
}

/// sso_logout(token) - Logout/invalidate an SSO session
fn bi_sso_logout(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let token = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("sso_logout", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("sso_logout: missing 'token'"))?;

    let removed = SSO_SESSIONS.write().unwrap().remove(&token).is_some();

    let mut result = BTreeMap::new();
    result.insert(
        "status".to_string(),
        Value::Str(if removed { "logged_out" } else { "not_found" }.to_string()),
    );
    Ok(Value::Record(result))
}

/// sso_status() - Get SSO configuration status
fn bi_sso_status(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let config = SSO_CONFIG.read().unwrap();
    let sessions = SSO_SESSIONS.read().unwrap();

    let mut result = BTreeMap::new();
    if let Some(ref c) = *config {
        result.insert("configured".to_string(), Value::Bool(true));
        result.insert(
            "provider".to_string(),
            Value::Str(c.provider.as_str().to_string()),
        );
        result.insert("enabled".to_string(), Value::Bool(c.enabled));
        result.insert(
            "active_sessions".to_string(),
            Value::Int(sessions.len() as i64),
        );
    } else {
        result.insert("configured".to_string(), Value::Bool(false));
    }
    Ok(Value::Record(result))
}
/// The standard named by a compliance builtin: piped in, or the first
/// argument. A standard the shell does not know is refused, not reported.
fn compliance_standard_arg(
    builtin: &str,
    input: &Option<Value>,
    args: &[Value],
) -> Result<ComplianceStandard> {
    let name = match input {
        Some(v) => role_name_arg(builtin, Some(v), "a standard")?,
        None => role_name_arg(builtin, args.first(), "a standard")?,
    };
    ComplianceStandard::from_str(&name).ok_or_else(|| {
        crate::safety::bad_arg(
            builtin,
            "a standard of GDPR, HIPAA, SOC2 or PCI",
            &format!("{name:?}"),
        )
    })
}

/// The controls a verdict rests on. `None` is a control the shell cannot
/// observe, which is not the same as the control being in place. Encryption
/// at rest was once asserted `true` here, so every standard was reported
/// compliant on a claim nothing checked.
fn compliance_checks() -> [(&'static str, Option<bool>); 4] {
    [
        ("data_encryption", None),
        (
            "access_logging",
            Some(!AUDIT_LOG.read().unwrap().is_empty()),
        ),
        // Presence of a defined role, not evidence that roles are enforced:
        // the role store is not consulted by the guard.
        (
            "role_based_access",
            Some(!RBAC_ROLES.read().unwrap().is_empty()),
        ),
        (
            "session_management",
            Some(SSO_CONFIG.read().unwrap().is_some()),
        ),
    ]
}

/// The verdict record both compliance builtins share. `compliant` is true only
/// when every control was observed and none failed.
fn compliance_verdict(standard: &ComplianceStandard) -> BTreeMap<String, Value> {
    let checks = compliance_checks();
    let names = |want: Option<bool>| -> Vec<Value> {
        checks
            .iter()
            .filter(|(_, v)| *v == want)
            .map(|(k, _)| Value::Str(k.to_string()))
            .collect()
    };
    let passed = names(Some(true));
    let failed = names(Some(false));
    let unverified = names(None);
    let compliant = failed.is_empty() && unverified.is_empty();

    let mut result = BTreeMap::new();
    result.insert(
        "standard".to_string(),
        Value::Str(standard.as_str().to_string()),
    );
    result.insert("passed".to_string(), Value::Array(passed));
    result.insert("failed".to_string(), Value::Array(failed));
    result.insert("unverified".to_string(), Value::Array(unverified));
    result.insert("compliant".to_string(), Value::Bool(compliant));
    result
}

/// compliance_check(standard, scope?) - Run compliance check
fn bi_compliance_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let standard = compliance_standard_arg("compliance_check", &input, &args)?;
    // A piped standard shifts the optional scope into the first argument.
    let scope_arg = if input.is_some() {
        args.first()
    } else {
        args.get(1)
    };
    let scope = match scope_arg {
        None => "all".to_string(),
        Some(Value::Str(s)) if s.as_str() == "all" => s.clone(),
        // Only the whole-system scope is checked. A subset used to be echoed
        // back and then ignored, so the verdict claimed a scope it did not have.
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "compliance_check",
                "a scope of \"all\", the only one implemented",
                &match other {
                    Value::Str(s) => format!("{s:?}"),
                    o => o.type_name().to_string(),
                },
            ))
        }
    };

    let mut result = compliance_verdict(&standard);
    result.insert("scope".to_string(), Value::Str(scope));
    Ok(Value::Record(result))
}

/// compliance_report(standard) - Generate compliance report: the same verdict
/// as `compliance_check`, with the counts behind it.
fn bi_compliance_report(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let standard = compliance_standard_arg("compliance_report", &input, &args)?;
    let mut result = compliance_verdict(&standard);
    result.insert(
        "generated_at".to_string(),
        Value::Str(chrono::Utc::now().to_rfc3339()),
    );
    result.insert(
        "audit_entries".to_string(),
        Value::Int(AUDIT_LOG.read().unwrap().len() as i64),
    );
    result.insert(
        "roles_defined".to_string(),
        Value::Int(RBAC_ROLES.read().unwrap().len() as i64),
    );
    result.insert(
        "sso_enabled".to_string(),
        Value::Bool(SSO_CONFIG.read().unwrap().is_some()),
    );
    Ok(Value::Record(result))
}
/// finetune_start(model, dataset, config?) - Start a fine-tuning job
fn bi_finetune_start(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.len() < 2 || args.len() > 3 {
        return Err(crate::safety::bad_arg(
            "finetune_start",
            "model, dataset, and an optional config Record",
            &format!("{} arguments", args.len()),
        ));
    }
    let model = match &args[0] {
        Value::Str(s) if !s.is_empty() => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "finetune_start",
                "model: a non-empty string",
                other.type_name(),
            ))
        }
    };
    let dataset = match &args[1] {
        Value::Str(s) if !s.is_empty() => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "finetune_start",
                "dataset: a non-empty string (a path or a dataset name)",
                other.type_name(),
            ))
        }
    };
    if let Some(other) = args.get(2) {
        if !matches!(other, Value::Record(_) | Value::Null) {
            return Err(crate::safety::bad_arg(
                "finetune_start",
                "config: a Record",
                other.type_name(),
            ));
        }
    }

    // No training backend is wired into this build. The job used to be recorded
    // as `pending` and reported as `started`, and nothing ever advanced it: a
    // job that will never run is a fabricated result. Refuse instead, so the
    // caller learns that nothing was started and what would be needed.
    Err(crate::safety::unimplemented(
        "finetune_start",
        &format!("no training job was started for model '{model}' on '{dataset}': no fine-tuning backend is wired"),
        "use a provider's own fine-tuning API (for example through http_post) or an external trainer",
    ))
}

/// finetune_status(job_id) - Get status of a fine-tuning job
fn bi_finetune_status(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let job_id = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("finetune_status", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("finetune_status: missing 'job_id'"))?;

    let jobs = FINETUNE_JOBS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("finetune_status", "the fine-tune job table"))?;
    let job = jobs
        .get(&job_id)
        .ok_or_else(|| crate::safety::not_found("finetune_status", "job", &job_id))?;

    let mut result = BTreeMap::new();
    result.insert("job_id".to_string(), Value::Str(job.id.clone()));
    result.insert("model".to_string(), Value::Str(job.model.clone()));
    result.insert("dataset".to_string(), Value::Str(job.dataset.clone()));
    result.insert(
        "status".to_string(),
        Value::Str(job.status.as_str().to_string()),
    );
    Ok(Value::Record(result))
}

/// finetune_list() - List all fine-tuning jobs
fn bi_finetune_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let jobs = FINETUNE_JOBS.read().unwrap();

    let result: Vec<Value> = jobs
        .values()
        .map(|job| {
            let mut rec = BTreeMap::new();
            rec.insert("job_id".to_string(), Value::Str(job.id.clone()));
            rec.insert("model".to_string(), Value::Str(job.model.clone()));
            rec.insert("dataset".to_string(), Value::Str(job.dataset.clone()));
            rec.insert(
                "status".to_string(),
                Value::Str(job.status.as_str().to_string()),
            );
            Value::Record(rec)
        })
        .collect();

    Ok(Value::Array(result))
}

/// finetune_cancel(job_id) - Cancel a fine-tuning job
fn bi_finetune_cancel(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let job_id = input
        .or_else(|| args.first().cloned())
        .map(|v| key_arg("finetune_cancel", v))
        .transpose()?
        .ok_or_else(|| crate::safety::arg_err("finetune_cancel: missing 'job_id'"))?;

    let mut jobs = FINETUNE_JOBS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("finetune_cancel", "the fine-tune job table"))?;

    if let Some(job) = jobs.get_mut(&job_id) {
        match job.status {
            FinetuneStatus::Pending | FinetuneStatus::Training => {
                job.status = FinetuneStatus::Cancelled;
                let mut result = BTreeMap::new();
                result.insert("status".to_string(), Value::Str("cancelled".to_string()));
                result.insert("job_id".to_string(), Value::Str(job_id));
                Ok(Value::Record(result))
            }
            _ => Err(crate::safety::bad_state_with_hint(
                "finetune_cancel",
                &format!(
                    "job '{}' cannot be cancelled (status: {})",
                    job_id,
                    job.status.as_str()
                ),
                "only a pending or training job can be cancelled",
            )),
        }
    } else {
        Err(crate::safety::not_found("finetune_cancel", "job", &job_id))
    }
}

// ===================== A2UI (Agent-to-User Interface) Builtins =====================

/// Refuse an interactive prompt when no UI has ever attached to the channel.
///
/// Checked before the prompt is queued, so no dangling prompt event is left for
/// a UI that does not exist. The channel's own check repeats this, but it names
/// `a2ui`, not the builtin the agent called.
fn require_a2ui_listener(builtin: &str) -> Result<()> {
    if A2UI_CHANNEL.ui_attached() {
        Ok(())
    } else {
        Err(crate::safety::no_ui(builtin))
    }
}

/// The message-or-subject and the parameters that follow it.
///
/// Piped, the subject is the input and every argument is a parameter. Called
/// directly, the first argument is the subject, as `validate` assumes.
fn a2ui_subject_and_rest<'a>(
    args: &'a [Value],
    input: &Option<Value>,
) -> (Option<Value>, &'a [Value]) {
    match input {
        Some(v) => (Some(v.clone()), args),
        None => (args.first().cloned(), args.get(1..).unwrap_or(&[])),
    }
}

/// a2ui_notify(message, {level: "info"|"success"|"warning"|"error"}) - Send notification to user
fn bi_a2ui_notify(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let message = input
        .or_else(|| args.first().cloned())
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_notify: missing message"))?;

    let level = args
        .get(1)
        .and_then(|v| {
            if let Value::Record(r) = v {
                r.get("level").map(|l| l.to_display_string())
            } else if let Value::Str(s) = v {
                Some(s.clone())
            } else {
                None
            }
        })
        .unwrap_or_else(|| "info".to_string())
        .parse::<NotificationLevel>()
        // An unknown level ("critical") was shown as info, silently.
        .map_err(|_| {
            crate::safety::bad_arg(
                "a2ui_notify",
                "level info, success, warning or error",
                "another level",
            )
        })?;

    A2UI_CHANNEL.notify_level("builtin", &message, level)?;

    Ok(Value::Record({
        let mut r = BTreeMap::new();
        r.insert("sent".to_string(), Value::Bool(true));
        r.insert(
            "ui_attached".to_string(),
            Value::Bool(A2UI_CHANNEL.ui_attached()),
        );
        r.insert("message".to_string(), Value::Str(message));
        r
    }))
}

/// a2ui_prompt(message) - Request text input from user (blocking)
///
/// Refused with `E_NO_UI` when no UI is attached. A user who cancels gets null.
/// Dispatch never reaches a reserved slot, since no name is registered at its
/// index; the entry only keeps the numbering of the ones after it.
fn reserved_slot() -> anyhow::Error {
    crate::safety::unimplemented(
        "reserved builtin slot",
        "no builtin is registered at this index",
        "call a registered builtin",
    )
}

/// The attached UI answered a prompt with a different kind of response, which
/// is a fault in the UI, not in the call: `E_IO`, naming what came back.
fn a2ui_wrong_answer(builtin: &str, asked: &str, got: &PromptResponse) -> anyhow::Error {
    let kind = match got {
        PromptResponse::Text(_) => "text",
        PromptResponse::Confirm(_) => "confirm",
        PromptResponse::Select(_) => "select",
        PromptResponse::MultiSelect(_) => "multi-select",
        PromptResponse::Cancelled => "cancelled",
    };
    crate::safety::io_fault(
        builtin,
        &format!("the attached UI answered a {asked} prompt with a {kind} response"),
        "check the UI client attached to the A2UI channel, then retry",
    )
}

#[cfg(test)]
mod coded_fault_tests {
    use super::*;
    use crate::safety::{ErrorCode, SafetyError};

    fn code(e: &anyhow::Error) -> ErrorCode {
        e.downcast_ref::<SafetyError>().expect("coded").code
    }

    #[test]
    fn reserved_slots_and_ui_protocol_faults_carry_codes() {
        assert_eq!(code(&reserved_slot()), ErrorCode::Unimplemented);
        let e = a2ui_wrong_answer("a2ui_prompt", "text", &PromptResponse::Confirm(true));
        assert_eq!(code(&e), ErrorCode::Io);
        assert!(e.to_string().contains("a confirm response"), "{e}");
    }
}

fn bi_a2ui_prompt(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (subject, _) = a2ui_subject_and_rest(&args, &input);
    let message = subject
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_prompt: missing message"))?;

    require_a2ui_listener("a2ui_prompt")?;
    match A2UI_CHANNEL.prompt_text("builtin", &message)? {
        PromptResponse::Text(s) => Ok(Value::Str(s)),
        PromptResponse::Cancelled => Ok(Value::Null),
        other => Err(a2ui_wrong_answer("a2ui_prompt", "text", &other)),
    }
}

/// a2ui_confirm(message) - Request yes/no confirmation from user (blocking)
///
/// Refused with `E_NO_UI` when no UI is attached. It never answers `false` for
/// "nobody is there": that is a decision, and nobody made it.
fn bi_a2ui_confirm(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (subject, _) = a2ui_subject_and_rest(&args, &input);
    let message = subject
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_confirm: missing message"))?;

    require_a2ui_listener("a2ui_confirm")?;
    let result = A2UI_CHANNEL.prompt_confirm("builtin", &message)?;
    Ok(Value::Bool(result))
}

/// a2ui_select(message, options) - Request selection from user (blocking)
///
/// Returns the chosen option, or null when the user cancels.
fn bi_a2ui_select(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (subject, rest) = a2ui_subject_and_rest(&args, &input);
    let message = subject
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_select: missing message"))?;

    let options: Vec<String> = match rest.first() {
        Some(Value::Array(arr)) if !arr.is_empty() => {
            arr.iter().map(|x| x.to_display_string()).collect()
        }
        Some(Value::Array(_)) => {
            return Err(crate::safety::bad_arg(
                "a2ui_select",
                "options: a non-empty Array",
                "an empty Array",
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "a2ui_select",
                "options: Array",
                other.type_name(),
            ))
        }
        None => {
            return Err(crate::safety::bad_arg(
                "a2ui_select",
                "options: Array",
                "nothing",
            ))
        }
    };

    require_a2ui_listener("a2ui_select")?;
    match A2UI_CHANNEL.prompt_select("builtin", &message, options.clone())? {
        PromptResponse::Select(idx) => match options.get(idx) {
            Some(chosen) => Ok(Value::Str(chosen.clone())),
            // An index past the end is the UI's answer being wrong. Null read as
            // "cancelled", which it was not.
            None => Err(crate::safety::bad_arg(
                "a2ui_select",
                "an index into the options",
                &format!("index {idx} of {}", options.len()),
            )),
        },
        PromptResponse::Cancelled => Ok(Value::Null),
        other => Err(a2ui_wrong_answer("a2ui_select", "select", &other)),
    }
}

/// a2ui_progress(label, current, total, progress_id?) - Update a progress indicator
///
/// Queued for the UI like the other display calls; it does not wait for one.
fn bi_a2ui_progress(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("a2ui_progress", &input)?;
    let label = args
        .first()
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_progress: missing label"))?;

    // Counts are whole and non-negative: a negative or fractional count used to
    // be cast to an unsigned number, silently.
    let count = |i: usize, what: &str| -> Result<u64> {
        match args.get(i) {
            Some(Value::Int(n)) if *n >= 0 => Ok(*n as u64),
            Some(other) => Err(crate::safety::bad_arg(
                "a2ui_progress",
                &format!("{what}: a whole number, 0 or more"),
                other.type_name(),
            )),
            None => Err(crate::safety::arg_err(format!(
                "a2ui_progress: missing {what} value"
            ))),
        }
    };
    let current = count(1, "current")?;
    let total = count(2, "total")?;
    if current > total {
        return Err(crate::safety::bad_arg(
            "a2ui_progress",
            "current: at most total",
            &format!("{current} of {total}"),
        ));
    }

    // Use the given progress ID, or make one. A given ID that is not a UUID was
    // replaced by a new one without a word.
    let progress_id = match args.get(3) {
        None => uuid::Uuid::new_v4(),
        Some(Value::Str(s)) => uuid::Uuid::parse_str(s)
            .map_err(|_| crate::safety::bad_arg("a2ui_progress", "progress_id: a UUID", s))?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "a2ui_progress",
                "progress_id: a UUID string",
                other.type_name(),
            ))
        }
    };

    A2UI_CHANNEL.progress("builtin", progress_id, &label, current, total)?;

    Ok(Value::Record({
        let mut r = BTreeMap::new();
        r.insert(
            "progress_id".to_string(),
            Value::Str(progress_id.to_string()),
        );
        r.insert("current".to_string(), Value::Int(current as i64));
        r.insert("total".to_string(), Value::Int(total as i64));
        r
    }))
}

/// a2ui_progress_complete(progress_id) - Complete a progress indicator
fn bi_a2ui_progress_complete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let id_str = input
        .or_else(|| args.first().cloned())
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_progress_complete: missing progress_id"))?;

    let progress_id = uuid::Uuid::parse_str(&id_str)
        .map_err(|_| crate::safety::arg_err("a2ui_progress_complete: invalid progress_id"))?;

    A2UI_CHANNEL.progress_complete("builtin", progress_id)?;

    Ok(Value::Bool(true))
}

/// a2ui_render(content) - Render content in the UI
fn bi_a2ui_render(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let content = input
        .or_else(|| args.first().cloned())
        .ok_or_else(|| crate::safety::arg_err("a2ui_render: missing content"))?;

    let render_content = match &content {
        Value::Str(s) => RenderContent::Text(s.clone()),
        Value::Record(r) => {
            // Check for specific render types
            if let Some(Value::Str(md)) = r.get("markdown") {
                RenderContent::Markdown(md.clone())
            } else if let Some(Value::Str(json_str)) = r.get("json") {
                // Invalid JSON rendered as null, silently.
                RenderContent::Json(serde_json::from_str(json_str).map_err(|e| {
                    crate::safety::bad_arg(
                        "a2ui_render",
                        "valid JSON in the json field",
                        &e.to_string(),
                    )
                })?)
            } else {
                RenderContent::Json(serde_json::to_value(&content).unwrap_or_default())
            }
        }
        Value::Array(_) => RenderContent::Json(serde_json::to_value(&content).unwrap_or_default()),
        _ => RenderContent::Text(content.to_display_string()),
    };

    A2UI_CHANNEL.render("builtin", render_content)?;

    Ok(Value::Bool(true))
}

/// a2ui_render_table(headers, rows) - Render a table in the UI
fn bi_a2ui_render_table(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let headers: Vec<String> = match args.first() {
        Some(Value::Array(arr)) => arr.iter().map(|x| x.to_display_string()).collect(),
        _ => {
            return Err(crate::safety::bad_arg(
                "a2ui_render_table",
                "headers: Array",
                args.first().map_or("nothing", |v| v.type_name()),
            ))
        }
    };

    // Rows come from the second argument, or from the pipe. A row that is
    // neither an array nor a record used to be filtered out without a word.
    let rows_value = args.get(1).or(input.as_ref());
    let Some(Value::Array(arr)) = rows_value else {
        return Err(crate::safety::bad_arg(
            "a2ui_render_table",
            "rows: Array",
            rows_value.map_or("nothing", |v| v.type_name()),
        ));
    };
    let mut rows: Vec<Vec<String>> = Vec::with_capacity(arr.len());
    for row in arr {
        match row {
            Value::Array(row_arr) => {
                rows.push(row_arr.iter().map(|x| x.to_display_string()).collect())
            }
            Value::Record(row_rec) => rows.push(
                headers
                    .iter()
                    .map(|h| {
                        row_rec
                            .get(h)
                            .map(|v| v.to_display_string())
                            .unwrap_or_default()
                    })
                    .collect(),
            ),
            other => {
                return Err(crate::safety::bad_arg(
                    "a2ui_render_table",
                    "each row: an Array or a Record",
                    other.type_name(),
                ))
            }
        }
    }

    A2UI_CHANNEL.render("builtin", RenderContent::Table { headers, rows })?;

    Ok(Value::Bool(true))
}

/// a2ui_render_code(language, code) - Render code with syntax highlighting
fn bi_a2ui_render_code(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let language = args
        .first()
        .map(|v| v.to_display_string())
        .filter(|s| !s.trim().is_empty())
        .ok_or_else(|| crate::safety::arg_err("a2ui_render_code: missing language"))?;

    let code = args
        .get(1)
        .or(input.as_ref())
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_render_code: missing code"))?;

    A2UI_CHANNEL.render(
        "builtin",
        RenderContent::Code {
            language,
            content: code,
        },
    )?;

    Ok(Value::Bool(true))
}

/// a2ui_toast(message, level, duration_ms) - Show a toast notification
fn bi_a2ui_toast(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let message = input
        .or_else(|| args.first().cloned())
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_toast: missing message"))?;

    let level = args
        .get(1)
        .map(|v| v.to_display_string())
        .unwrap_or_else(|| "info".to_string())
        .parse::<NotificationLevel>()
        // An unknown level ("critical") was shown as info, silently.
        .map_err(|_| {
            crate::safety::bad_arg(
                "a2ui_toast",
                "level info, success, warning or error",
                "another level",
            )
        })?;

    let duration_ms = args
        .get(2)
        .and_then(|v| match v {
            Value::Int(n) => Some(*n as u64),
            Value::Float(f) => Some(*f as u64),
            _ => None,
        })
        .unwrap_or(3000);

    A2UI_CHANNEL.toast("builtin", &message, level, duration_ms)?;

    Ok(Value::Bool(true))
}

/// a2ui_status(text) - Update the status bar
fn bi_a2ui_status(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let text = input
        .or_else(|| args.first().cloned())
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_status: missing text"))?;

    A2UI_CHANNEL.status("builtin", &text)?;

    Ok(Value::Bool(true))
}

/// a2ui_clear() - Clear the A2UI event channel
fn bi_a2ui_clear(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    A2UI_CHANNEL.clear()?;
    Ok(Value::Bool(true))
}

/// a2ui_agent_started(agent_id, task) - Notify that an agent started working
fn bi_a2ui_agent_started(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let agent_id = input
        .or_else(|| args.first().cloned())
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_agent_started: missing agent_id"))?;

    let task = args.get(1).map(|v| v.to_display_string());

    A2UI_CHANNEL.send(A2UIEvent::new(
        "builtin",
        A2UIEventType::AgentStarted { agent_id, task },
    ))?;

    Ok(Value::Bool(true))
}

/// a2ui_agent_completed(agent_id, success, result) - Notify that an agent completed
fn bi_a2ui_agent_completed(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let agent_id = input
        .or_else(|| args.first().cloned())
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_agent_completed: missing agent_id"))?;

    // An absent flag means success; a supplied flag must be a Bool. A string
    // such as "false" or a 0 is refused, not read as success.
    let success = match args.get(1) {
        None => true,
        Some(Value::Bool(b)) => *b,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "a2ui_agent_completed",
                "a success flag that is a Bool (true or false), or no flag",
                other.type_name(),
            ))
        }
    };

    let result = args.get(2).map(|v| v.to_display_string());

    A2UI_CHANNEL.send(A2UIEvent::new(
        "builtin",
        A2UIEventType::AgentCompleted {
            agent_id,
            result,
            success,
        },
    ))?;

    Ok(Value::Bool(true))
}

/// a2ui_agent_thinking(agent_id, thought, step) - Show agent's reasoning process
fn bi_a2ui_agent_thinking(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let agent_id = args
        .first()
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_agent_thinking: missing agent_id"))?;

    let thought = args
        .get(1)
        .or(input.as_ref())
        .map(|v| v.to_display_string())
        .ok_or_else(|| crate::safety::arg_err("a2ui_agent_thinking: missing thought"))?;

    let step = args
        .get(2)
        .and_then(|v| match v {
            Value::Int(n) => Some(*n as usize),
            _ => None,
        })
        .unwrap_or(0);

    A2UI_CHANNEL.send(A2UIEvent::new(
        "builtin",
        A2UIEventType::AgentThinking {
            agent_id,
            thought,
            step,
        },
    ))?;

    Ok(Value::Bool(true))
}

// ============================================================================
// 230-249: Process Management
// ============================================================================

/// Refuses pipeline input and more arguments than a builtin takes.
///
/// These builtins ignored a piped subject, and `proc_list(1, 2)` answered as
/// if no arguments had been given.
fn proc_check(builtin: &str, args: &[Value], input: &Option<Value>, max_args: usize) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            builtin,
            "no pipeline input",
            "pipeline input",
        ));
    }
    if args.len() > max_args {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("at most {max_args} argument(s)"),
            &args.len().to_string(),
        ));
    }
    Ok(())
}

/// A process's `sysinfo` record, refreshed for that one pid. The pid must
/// already have been checked to fit `u32` (see `proc_pid`).
fn proc_sys(pid: i64) -> System {
    let spid = sysinfo::Pid::from_u32(pid as u32);
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[spid]), true);
    sys
}

/// Whether a process with this pid is live now.
fn proc_live(pid: i64) -> bool {
    proc_sys(pid)
        .process(sysinfo::Pid::from_u32(pid as u32))
        .is_some()
}

/// E_NOT_FOUND unless the process is live. Every reader asks this first, so
/// a pid that does not exist is one coded error, never a null, a zero, an
/// empty record or an empty array.
fn proc_require(builtin: &str, pid: i64) -> Result<()> {
    if proc_live(pid) {
        Ok(())
    } else {
        Err(crate::safety::not_found(
            builtin,
            "process",
            &pid.to_string(),
        ))
    }
}

fn proc_is_self(pid: i64) -> bool {
    pid == i64::from(std::process::id())
}

/// Refuses this shell's own pid. Stopping it would stop the caller too.
fn proc_refuse_self(builtin: &str, pid: i64) -> Result<()> {
    if proc_is_self(pid) {
        return Err(crate::safety::bad_arg(
            builtin,
            "a process other than this shell",
            &format!("its own pid {pid}"),
        ));
    }
    Ok(())
}

/// A pid for a builtin that reads or acts on one process: a positive integer,
/// or its spelling, that the operating system's pid type can hold.
///
/// `pid_arg` admits any positive i64, and the sysinfo lookup casts it to
/// `u32`, which would turn 4294967297 into pid 1.
fn proc_pid(builtin: &str, v: Option<&Value>) -> Result<i64> {
    let pid = pid_arg(builtin, v)?;
    #[cfg(unix)]
    let fits = libc::pid_t::try_from(pid).is_ok();
    #[cfg(not(unix))]
    let fits = u32::try_from(pid).is_ok();
    if !fits {
        return Err(crate::safety::bad_arg(
            builtin,
            "a process id that fits the operating system's pid type",
            &pid.to_string(),
        ));
    }
    Ok(pid)
}

/// Runs a host tool for a reader. A tool that cannot start is E_TOOL_MISSING;
/// one that runs and fails is E_TOOL_FAILED with its stderr.
fn proc_tool(
    builtin: &str,
    tool: &str,
    cmd: std::process::Command,
    deadline_secs: u64,
) -> Result<std::process::Output> {
    let out = bounded_cmd_output(builtin, tool, cmd, deadline_secs)?;
    if out.status.success() {
        return Ok(out);
    }
    Err(crate::safety::tool_failed(
        builtin,
        tool,
        out.status.code(),
        &String::from_utf8_lossy(&out.stderr),
    ))
}

/// Reads one value a host tool printed. Text that is not the value is a
/// coded failure, never a zero.
fn proc_parse<T: std::str::FromStr>(builtin: &str, tool: &str, text: &str) -> Result<T> {
    text.trim().parse::<T>().map_err(|_| {
        crate::safety::tool_failed(
            builtin,
            tool,
            Some(0),
            &format!(
                "its output was not a value this builtin reads: {:?}",
                text.trim()
            ),
        )
    })
}

/// A refused priority change or signal: a permission refusal is E_POLICY_DENY,
/// anything else E_TOOL_FAILED with the tool's own words.
fn proc_refused(
    builtin: &str,
    tool: &str,
    pid: i64,
    stderr: &[u8],
    status: Option<i32>,
) -> anyhow::Error {
    let said = String::from_utf8_lossy(stderr).trim().to_string();
    let lower = said.to_ascii_lowercase();
    if [
        "permission",
        "not permitted",
        "access is denied",
        "access denied",
    ]
    .iter()
    .any(|w| lower.contains(w))
    {
        return crate::safety::os_denied(
            builtin,
            format!("{builtin}: the operating system refused to change process {pid}: {said}"),
            "the process belongs to another user, or this change needs elevated rights; change a process this user owns",
        );
    }
    crate::safety::tool_failed(builtin, tool, status, &said)
}

/// A /proc entry that could not be read, coded by the reason: a missing entry
/// is E_NOT_FOUND and a refused one E_POLICY_DENY.
#[cfg(target_os = "linux")]
fn proc_read_failed(builtin: &str, pid: i64, what: &str, e: &std::io::Error) -> anyhow::Error {
    match e.kind() {
        std::io::ErrorKind::NotFound => {
            crate::safety::not_found(builtin, "process", &pid.to_string())
        }
        std::io::ErrorKind::PermissionDenied => crate::safety::os_denied(
            builtin,
            format!("{builtin}: the operating system denied reading {what} of process {pid}"),
            "the process belongs to another user; read processes this user owns",
        ),
        _ => crate::safety::tool_failed(
            builtin,
            &format!("reading {what} of process {pid}"),
            Some(0),
            &e.to_string(),
        ),
    }
}

/// A Windows process image name without its ".exe" suffix. The suffix is
/// matched without regard to case, so the name reads as Get-Process's
/// ProcessName did.
#[cfg(windows)]
fn proc_strip_exe(name: &str) -> &str {
    match name.len().checked_sub(4) {
        Some(cut) if name.is_char_boundary(cut) && name[cut..].eq_ignore_ascii_case(".exe") => {
            &name[..cut]
        }
        _ => name,
    }
}

/// Total CPU seconds (kernel plus user time) of process `pid`, the value
/// Get-Process's CPU column reported. None when the process cannot be opened
/// or queried, which the caller turns into Null as PowerShell did.
#[cfg(windows)]
fn win_process_cpu_seconds(pid: u32) -> Option<f64> {
    use std::ffi::c_void;
    #[link(name = "kernel32")]
    extern "system" {
        fn GetProcessTimes(
            process: *mut c_void,
            creation: *mut WinFileTime,
            exit: *mut WinFileTime,
            kernel: *mut WinFileTime,
            user: *mut WinFileTime,
        ) -> i32;
    }
    win_with_process("proc_list", i64::from(pid), |h| {
        let mut creation = WinFileTime::default();
        let mut exit = WinFileTime::default();
        let mut kernel = WinFileTime::default();
        let mut user = WinFileTime::default();
        // SAFETY: `h` is the live handle win_with_process opened; each
        // out-pointer is a valid, writable FILETIME.
        if unsafe { GetProcessTimes(h, &mut creation, &mut exit, &mut kernel, &mut user) } == 0 {
            return Err(crate::safety::bad_state_with_hint(
                "proc_list",
                &format!(
                    "GetProcessTimes failed: {}",
                    std::io::Error::last_os_error()
                ),
                "a live process this user can query",
            ));
        }
        Ok((kernel.ticks() + user.ticks()) as f64 / 1e7)
    })
    .ok()
}

fn bi_proc_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_list", &args, &input, 0)?;
    // Was `Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet64` run
    // through PowerShell and parsed from its JSON; now read in process. sysinfo
    // lists the processes (image name, working set) and GetProcessTimes gives
    // the CPU seconds. Rows are sorted by pid.
    #[cfg(windows)]
    let procs = {
        let mut sys = System::new();
        sys.refresh_processes_specifics(
            sysinfo::ProcessesToUpdate::All,
            true,
            sysinfo::ProcessRefreshKind::nothing().with_memory(),
        );
        let mut rows: Vec<(u32, &sysinfo::Process)> = sys
            .processes()
            .iter()
            .map(|(pid, process)| (pid.as_u32(), process))
            .collect();
        rows.sort_unstable_by_key(|(pid, _)| *pid);
        let mut procs = Vec::new();
        for (pid, process) in rows {
            let raw = process.name().to_string_lossy().into_owned();
            let name = proc_strip_exe(&raw).to_string();
            let mut rec = BTreeMap::new();
            rec.insert("pid".to_string(), Value::Int(i64::from(pid)));
            rec.insert("name".to_string(), Value::Str(name.clone()));
            rec.insert(
                "cpu".to_string(),
                win_process_cpu_seconds(pid)
                    .map(Value::Float)
                    .unwrap_or(Value::Null),
            );
            rec.insert("mem".to_string(), Value::Int(process.memory() as i64));
            rec.insert("command".to_string(), Value::Str(name));
            procs.push(Value::Record(rec));
        }
        procs
    };
    #[cfg(not(windows))]
    let procs = {
        let out = proc_tool(
            "proc_list",
            "ps",
            {
                let mut c = crate::safety::child_command("ps");
                c.arg("aux");
                c
            },
            PROBE_DEADLINE_SECS,
        )?;
        let mut procs = Vec::new();
        for line in String::from_utf8_lossy(&out.stdout).lines().skip(1) {
            if line.trim().is_empty() {
                continue;
            }
            // USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND...
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() < 11 {
                return Err(crate::safety::tool_failed(
                    "proc_list",
                    "ps",
                    Some(0),
                    &format!("a process line had {} fields, not 11 or more", parts.len()),
                ));
            }
            let pid: i64 = proc_parse("proc_list", "ps", parts[1])?;
            let cpu: f64 = proc_parse("proc_list", "ps", parts[2])?;
            let rss_kb: i64 = proc_parse("proc_list", "ps", parts[5])?;
            let command = parts[10..].join(" ");
            let mut rec = BTreeMap::new();
            rec.insert("pid".to_string(), Value::Int(pid));
            rec.insert("name".to_string(), Value::Str(command.clone()));
            rec.insert("cpu".to_string(), Value::Float(cpu));
            rec.insert("mem".to_string(), Value::Int(rss_kb.saturating_mul(1024)));
            rec.insert("command".to_string(), Value::Str(command));
            procs.push(Value::Record(rec));
        }
        procs
    };
    Ok(Value::Array(procs))
}

/// A process id: a positive integer, or a string of one.
///
/// Four builtins parsed a string with `unwrap_or(0)`, so a process *name*
/// became pid 0, and none refused zero or a negative pid. To `kill`, 0 means
/// the caller's own process group and -1 means every process the user may
/// signal: `proc_kill("firefox")` signalled the shell's own group, and
/// `proc_kill(-1)` everything.
fn pid_arg(builtin: &str, v: Option<&Value>) -> Result<i64> {
    let pid = match v {
        Some(Value::Int(p)) => Some(*p),
        Some(Value::Str(s)) => s.trim().parse::<i64>().ok(),
        _ => None,
    };
    match pid {
        // Above u32::MAX a pid is no process; `as u32` would wrap it onto one.
        Some(p) if p > 0 && p <= i64::from(u32::MAX) => Ok(p),
        _ => Err(crate::safety::bad_arg(
            builtin,
            "a process id: a positive integer (0 and negatives address groups of processes)",
            &v.map(|v| v.to_display_string())
                .unwrap_or_else(|| "nothing".into()),
        )),
    }
}

/// A coded `E_TOOL_FAILED` for a signal the OS or `taskkill` refused.
///
/// `tool_failed` describes an exit status, which a signal has no equivalent
/// of, so this states the refusal in its own words.
fn proc_kill_failed(message: String, hint: &str, got: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::ToolFailed,
        message,
        builtin: "proc_kill".to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "the signal to be delivered".to_string(),
        got: got.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// The Record a successful `proc_kill` answers. A tree kill also names every
/// process it signalled, in the order it signalled them, as `killed`.
fn proc_kill_sent(pid: i64, signal: &str, killed: Option<&[i64]>) -> Value {
    let mut rec = BTreeMap::new();
    rec.insert("pid".to_string(), Value::Int(pid));
    rec.insert("signal".to_string(), Value::Str(signal.to_string()));
    rec.insert("sent".to_string(), Value::Bool(true));
    if let Some(killed) = killed {
        rec.insert(
            "killed".to_string(),
            Value::Array(killed.iter().map(|p| Value::Int(*p)).collect()),
        );
    }
    Value::Record(rec)
}

/// The processes under `root`, breadth-first, as sysinfo reports them now. It
/// is read before anything is signalled. A child that started before its
/// parent is a reused pid and not a child, so it is left out. More than 4096
/// descendants is E_BUDGET_EXCEEDED, raised before anything is signalled.
///
/// The per-pid checks (a pid that fits, this shell's own pid) apply to each
/// descendant at the caller. A descendant's pid is a u32 from sysinfo, so it
/// always fits the OS pid type.
fn proc_kill_descendants(root: i64) -> Result<Vec<i64>> {
    const LIMIT: usize = 4096;
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
    let mut children: std::collections::HashMap<u32, Vec<u32>> = std::collections::HashMap::new();
    for (pid, proc_) in sys.processes() {
        let Some(parent) = proc_.parent() else {
            continue;
        };
        let Some(parent_proc) = sys.process(parent) else {
            continue;
        };
        if proc_.start_time() < parent_proc.start_time() {
            continue;
        }
        children
            .entry(parent.as_u32())
            .or_default()
            .push(pid.as_u32());
    }
    for kids in children.values_mut() {
        kids.sort_unstable();
    }

    let root = u32::try_from(root).unwrap_or(u32::MAX);
    let mut seen = std::collections::HashSet::from([root]);
    let mut queue = std::collections::VecDeque::from([root]);
    let mut found: Vec<i64> = Vec::new();
    while let Some(parent) = queue.pop_front() {
        let Some(kids) = children.get(&parent) else {
            continue;
        };
        for kid in kids {
            if !seen.insert(*kid) {
                continue;
            }
            if found.len() == LIMIT {
                return Err(crate::safety::budget_exceeded(
                    "proc_kill",
                    format!(
                        "proc_kill: process {root} has more than {LIMIT} descendants; NOTHING WAS SENT"
                    ),
                    "signal a smaller subtree, or signal its children separately",
                ));
            }
            found.push(i64::from(*kid));
            queue.push_back(*kid);
        }
    }
    Ok(found)
}

/// What a failed Unix tree kill already signalled, for the error message.
#[cfg(unix)]
fn proc_kill_partial(killed: &[i64], signal: &str) -> String {
    if killed.is_empty() {
        String::new()
    } else {
        format!(
            "; {} earlier process(es) of the tree were sent {signal} before this failed",
            killed.len()
        )
    }
}

fn bi_proc_kill(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // A piped subject would be silently ignored; refuse it before anything runs.
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            "proc_kill",
            "no pipeline input",
            "pipeline input",
        ));
    }
    let pid = pid_arg("proc_kill", args.first())?;
    // Parsed once, before anything runs, on every OS. A numeric signal was
    // ignored (only strings were read) and sent as TERM, and an unknown name
    // ("SIGKILL", "USR1") became TERM too. On Windows every name did.
    let signal = match args.get(1) {
        None => "TERM".to_string(),
        Some(Value::Str(s)) => s.trim().trim_start_matches("SIG").to_ascii_uppercase(),
        Some(Value::Int(n)) => n.to_string(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "proc_kill",
                "signal: a name (TERM, KILL, ...) or number",
                other.type_name(),
            ))
        }
    };
    let (name, num) = match signal.as_str() {
        "TERM" | "15" => ("TERM", "-15"),
        "KILL" | "9" => ("KILL", "-9"),
        "HUP" | "1" => ("HUP", "-1"),
        "INT" | "2" => ("INT", "-2"),
        "QUIT" | "3" => ("QUIT", "-3"),
        "STOP" | "19" => ("STOP", "-19"),
        "CONT" | "18" => ("CONT", "-18"),
        other => {
            return Err(crate::safety::bad_arg(
                "proc_kill",
                "signal TERM, KILL, HUP, INT, QUIT, STOP or CONT (or its number)",
                other,
            ))
        }
    };
    let signal = name;
    // `num` is the kill(1) spelling; neither OS path below uses it any more.
    let _ = num;

    // The options Record, third and last. `tree` is its only key, and it is
    // read here, before any effect, so a refusal signals nothing.
    let tree = match args.get(2) {
        None => false,
        Some(Value::Record(rec)) => {
            cfg_known_keys("proc_kill", rec, &["tree"])?;
            cfg_bool("proc_kill", rec, "tree")?.unwrap_or(false)
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "proc_kill",
                "options: a Record {tree: Bool}",
                other.type_name(),
            ))
        }
    };

    // Refused before the guard: these pids address groups of processes or this
    // shell itself, and a pid that does not fit the OS's pid type is no process.
    #[cfg(unix)]
    let fits = libc::pid_t::try_from(pid).is_ok();
    #[cfg(not(unix))]
    let fits = u32::try_from(pid).is_ok();
    if !fits {
        return Err(crate::safety::bad_arg(
            "proc_kill",
            "a process id that fits the operating system's pid type",
            &pid.to_string(),
        ));
    }
    let own = i64::from(std::process::id());
    if pid == own {
        return Err(crate::safety::bad_arg(
            "proc_kill",
            "a process other than this shell",
            &format!("its own pid {pid}"),
        ));
    }

    // A tree kill reads the descendants now, before any signal, so that each
    // can be checked and the guard sees the whole set. If this shell is among
    // them (the target is one of its ancestors), the whole call is refused.
    let descendants = if tree {
        proc_kill_descendants(pid)?
    } else {
        Vec::new()
    };
    if let Some(d) = descendants.iter().find(|d| **d == own) {
        return Err(crate::safety::bad_arg(
            "proc_kill",
            "a process other than this shell, in the tree",
            &format!("its own pid {d}, a descendant of {pid}; NOTHING WAS SENT"),
        ));
    }

    let mut targets = vec![pid.to_string()];
    targets.extend(descendants.iter().map(|d| d.to_string()));
    let blast_radius = if tree {
        serde_json::json!({
            "pid": pid,
            "signal": signal,
            "tree": true,
            "descendants": descendants.len(),
        })
    } else {
        serde_json::json!({ "pid": pid, "signal": signal })
    };
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "proc_kill",
        effect: crate::safety::Effect::Process,
        what: "kill",
        targets,
        blast_radius,
        reversible: false,
        fs_paths: false,
    })?;

    // Deepest first, then the target, as the Unix path signals them. Windows
    // has taskkill walk the tree, so this is the order it is reported in.
    #[cfg(windows)]
    let order: Vec<i64> = descendants
        .iter()
        .rev()
        .copied()
        .chain(std::iter::once(pid))
        .collect();

    #[cfg(windows)]
    {
        // taskkill has a graceful close and a forced one; nothing else maps.
        let force = match signal {
            "TERM" => false,
            "KILL" => true,
            other => {
                return Err(crate::safety::unimplemented(
                    "proc_kill",
                    &format!("signal {other} has no Windows equivalent; NOTHING WAS SENT"),
                    "use TERM (graceful) or KILL (forced)",
                ))
            }
        };
        let mut cmd = crate::safety::child_command("taskkill");
        cmd.args(["/PID", &pid.to_string()]);
        if tree {
            cmd.arg("/T");
        }
        if force {
            cmd.arg("/F");
        }
        let output = bounded_cmd_output("proc_kill", "taskkill", cmd, TOOL_DEADLINE_SECS)?;
        if output.status.success() {
            return Ok(proc_kill_sent(
                pid,
                signal,
                tree.then_some(order.as_slice()),
            ));
        }
        let said = format!(
            "{} {}",
            String::from_utf8_lossy(&output.stderr),
            String::from_utf8_lossy(&output.stdout)
        );
        // taskkill's exit 128 is "no such process"; the lookup confirms it
        // where the code is not stable across Windows releases.
        let mut sys = System::new();
        let spid = sysinfo::Pid::from_u32(pid as u32);
        sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[spid]), true);
        if output.status.code() == Some(128) || sys.process(spid).is_none() {
            return Err(crate::safety::not_found(
                "proc_kill",
                "process",
                &pid.to_string(),
            ));
        }
        if said.contains("forcefully") {
            return Err(proc_kill_failed(
                format!(
                    "proc_kill: process {pid} is a console process and cannot take {signal}; NOTHING WAS SENT"
                ),
                "a console process only ends when forced: call proc_kill with signal KILL",
                "a process that refuses a graceful close",
            ));
        }
        Err(crate::safety::tool_failed(
            "proc_kill",
            &format!("taskkill /PID {pid}"),
            output.status.code(),
            &said,
        ))
    }
    #[cfg(unix)]
    {
        let sig = match signal {
            "TERM" => libc::SIGTERM,
            "KILL" => libc::SIGKILL,
            "HUP" => libc::SIGHUP,
            "INT" => libc::SIGINT,
            "QUIT" => libc::SIGQUIT,
            "STOP" => libc::SIGSTOP,
            "CONT" => libc::SIGCONT,
            other => {
                return Err(crate::safety::bad_arg(
                    "proc_kill",
                    "signal TERM, KILL, HUP, INT, QUIT, STOP or CONT (or its number)",
                    other,
                ))
            }
        };
        // The fit was checked above. kill(2) reads only its two arguments.
        let native_of = |p: i64| libc::pid_t::try_from(p).unwrap_or(libc::pid_t::MAX);
        let mut killed: Vec<i64> = Vec::new();

        // Descendants first, deepest first, so the target is still alive only
        // until its children are gone and cannot respawn one. A descendant that
        // has already exited (ESRCH) is not an error.
        for &child in descendants.iter().rev() {
            // SAFETY: kill(2) takes a pid and a signal number and touches no memory.
            if unsafe { libc::kill(native_of(child), sig) } != 0 {
                let err = std::io::Error::last_os_error();
                let partial = proc_kill_partial(&killed, signal);
                match err.raw_os_error() {
                    Some(libc::ESRCH) => continue,
                    Some(libc::EPERM) => {
                        return Err(crate::safety::os_denied(
                            "proc_kill",
                            format!(
                                "proc_kill: the operating system denied {signal} to process {child}, a descendant of {pid} (EPERM){partial}"
                            ),
                            "the process belongs to another user or is protected; signal a process this user owns",
                        ))
                    }
                    _ => {
                        return Err(proc_kill_failed(
                            format!("proc_kill: kill({child}, {signal}) failed: {err}{partial}"),
                            "the OS refused the signal; the message names the errno",
                            &err.to_string(),
                        ))
                    }
                }
            }
            killed.push(child);
        }

        // SAFETY: kill(2) takes a pid and a signal number and touches no memory.
        if unsafe { libc::kill(native_of(pid), sig) } != 0 {
            let err = std::io::Error::last_os_error();
            let partial = proc_kill_partial(&killed, signal);
            match err.raw_os_error() {
                // The tree's members were signalled and the root has since
                // gone on its own: nothing is left to fail on.
                Some(libc::ESRCH) if !killed.is_empty() => {}
                Some(libc::ESRCH) => {
                    return Err(crate::safety::not_found(
                        "proc_kill",
                        "process",
                        &pid.to_string(),
                    ))
                }
                Some(libc::EPERM) => {
                    return Err(crate::safety::os_denied(
                        "proc_kill",
                        format!(
                            "proc_kill: the operating system denied {signal} to process {pid} (EPERM){partial}"
                        ),
                        "the process belongs to another user or is protected; signal a process this user owns",
                    ))
                }
                _ => {
                    return Err(proc_kill_failed(
                        format!("proc_kill: kill({pid}, {signal}) failed: {err}{partial}"),
                        "the OS refused the signal; the message names the errno",
                        &err.to_string(),
                    ))
                }
            }
        } else {
            killed.push(pid);
        }
        Ok(proc_kill_sent(
            pid,
            signal,
            tree.then_some(killed.as_slice()),
        ))
    }
}

fn bi_proc_info(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // In-process through sysinfo, the same on every OS. It was three
    // shell-outs: on Windows it reported ppid 0 and state "running" for every
    // process, which Get-Process never said; on Linux it split /proc/<pid>/stat
    // on whitespace, so a process name containing a space shifted every field
    // after it; and a pid that did not exist answered null everywhere.
    let pid = pid_arg("proc_info", args.first())?;
    let spid = sysinfo::Pid::from_u32(pid as u32);
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[spid]), true);
    let p = sys
        .process(spid)
        .ok_or_else(|| crate::safety::not_found("proc_info", "process", &pid.to_string()))?;
    let mut rec = BTreeMap::new();
    rec.insert("pid".to_string(), Value::Int(pid));
    rec.insert(
        "name".to_string(),
        Value::Str(p.name().to_string_lossy().to_string()),
    );
    rec.insert("state".to_string(), Value::Str(p.status().to_string()));
    rec.insert(
        "ppid".to_string(),
        p.parent()
            .map(|pp| Value::Int(pp.as_u32() as i64))
            .unwrap_or(Value::Null),
    );
    rec.insert("memory_bytes".to_string(), Value::Int(p.memory() as i64));
    rec.insert("start_time".to_string(), Value::Int(p.start_time() as i64));
    rec.insert(
        "exe".to_string(),
        p.exe()
            .map(|e| Value::Str(e.to_string_lossy().to_string()))
            .unwrap_or(Value::Null),
    );
    Ok(Value::Record(rec))
}

/// Pids this shell spawned and has not yet seen end. proc_wait answers true
/// for one of them that ended before the call (a fast child is gone by the
/// time it is waited for); any other absent pid is E_NOT_FOUND. Bounded, so an
/// agent that spawns without waiting cannot grow it without limit.
static SPAWNED: std::sync::Mutex<Vec<i64>> = std::sync::Mutex::new(Vec::new());
const SPAWNED_CAP: usize = 1024;

fn spawned_note(pid: i64) {
    if let Ok(mut pids) = SPAWNED.lock() {
        if pids.len() >= SPAWNED_CAP {
            pids.remove(0);
        }
        pids.push(pid);
    }
}

/// Removes a pid from the spawned set; true when it was there.
fn spawned_take(pid: i64) -> bool {
    match SPAWNED.lock() {
        Ok(mut pids) => match pids.iter().position(|p| *p == pid) {
            Some(i) => {
                pids.remove(i);
                true
            }
            None => false,
        },
        Err(_) => false,
    }
}

/// The longest deadline `proc_spawn`'s `timeout_ms` accepts: one day.
const SPAWN_TIMEOUT_MAX_MS: i64 = 86_400_000;

/// How long a deadline stop waits for SIGTERM to empty the process group
/// before it sends SIGKILL.
#[cfg(unix)]
const SPAWN_STOP_GRACE: Duration = Duration::from_secs(2);

/// How often the deadline watcher re-reads the child. A child that ends
/// earlier is noticed within this slice.
const SPAWN_WATCH_SLICE: Duration = Duration::from_millis(100);

fn bi_proc_spawn(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // A piped subject would be silently ignored; refuse it before anything runs.
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            "proc_spawn",
            "no pipeline input",
            "pipeline input",
        ));
    }

    // The options Record is the last argument when a program comes before it.
    // A Record anywhere else stays an argument, and is refused below.
    let (words, options) = match args.split_last() {
        Some((Value::Record(rec), rest)) if !rest.is_empty() => (rest, Some(rec)),
        _ => (args.as_slice(), None),
    };
    // Read and checked here, before the program name, the guard or any spawn.
    let timeout_ms = match options {
        None => None,
        Some(rec) => {
            cfg_known_keys("proc_spawn", rec, &["timeout_ms"])?;
            cfg_int("proc_spawn", rec, "timeout_ms", 1, SPAWN_TIMEOUT_MAX_MS)?
        }
    };

    let cmd = match words.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "proc_spawn",
                "a program name (String)",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    if cmd.contains('\0') {
        return Err(crate::safety::bad_arg(
            "proc_spawn",
            "a program name with no NUL byte",
            "a NUL byte",
        ));
    }
    if cmd.len() > 4096 {
        return Err(crate::safety::bad_arg(
            "proc_spawn",
            "a program name of at most 4096 bytes",
            &format!("{} bytes", cmd.len()),
        ));
    }

    // Every argument is a string. A non-string one was dropped, and the
    // program ran with the rest.
    let mut spawn_args: Vec<String> = Vec::with_capacity(words.len().saturating_sub(1));
    for (i, v) in words.iter().enumerate().skip(1) {
        let Value::Str(s) = v else {
            return Err(crate::safety::bad_arg(
                "proc_spawn",
                "String arguments",
                &format!("{} at argument {}", v.type_name(), i + 1),
            ));
        };
        if s.contains('\0') {
            return Err(crate::safety::bad_arg(
                "proc_spawn",
                "arguments with no NUL byte",
                &format!("a NUL byte in argument {}", i + 1),
            ));
        }
        spawn_args.push(s.clone());
    }

    // Avoiding shell interpolation (below) stops argument injection, but the
    // program itself is still caller-chosen, so this is the same capability
    // `sh` grants and takes the same policy gate.
    crate::safety::guard_exec("proc_spawn", format!("{} {}", cmd, spawn_args.join(" ")))?;

    // Security: log the spawn attempt
    eprintln!(
        "[SECURITY] proc.spawn: cmd='{}', args={:?}",
        cmd, spawn_args
    );

    // Executed directly, never through a shell (CWE-78). The child is not
    // waited for here; proc_wait reaps it.
    let mut command = crate::safety::child_command(&cmd);
    crate::safety::strip_ironshell_env(&mut command);
    command.args(&spawn_args);
    // With a deadline the child leads its own process group, so the stop can
    // signal the child and the descendants that stayed in its group at once.
    #[cfg(unix)]
    if timeout_ms.is_some() {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }
    let child = command
        .spawn()
        .map_err(|e| crate::safety::spawn_error("proc_spawn", &cmd, &e))?;
    let pid = i64::from(child.id());
    spawned_note(pid);

    if let Some(ms) = timeout_ms {
        // The start time is read now, so the watcher can tell this child from
        // a later process that reuses its pid. None means it has already ended,
        // and there is nothing left to stop.
        if let Some((start, _)) = spawn_probe(pid) {
            if let Err(e) = arm_spawn_deadline(pid, start, ms) {
                stop_spawn_tree_now(pid);
                return Err(crate::safety::tool_failed(
                    "proc_spawn",
                    &cmd,
                    None,
                    &format!("could not start the deadline watcher ({e}); the child was stopped"),
                ));
            }
        }
    }
    Ok(Value::Int(pid))
}

/// The start time of a process, and whether it is still running; a zombie
/// has ended, though nothing has reaped it. It only reads the process table:
/// proc_wait is the one that reaps a child, so the watcher never takes an exit
/// status from it.
fn spawn_probe(pid: i64) -> Option<(u64, bool)> {
    let spid = sysinfo::Pid::from_u32(u32::try_from(pid).ok()?);
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[spid]), true);
    let proc_ = sys.process(spid)?;
    Some((
        proc_.start_time(),
        proc_.status() != sysinfo::ProcessStatus::Zombie,
    ))
}

/// Whether `pid` is still the process that started at `start`, and is running.
/// A pid that has ended, or now names a different process, is not.
fn spawn_is_ours(pid: i64, start: u64) -> bool {
    matches!(spawn_probe(pid), Some((s, true)) if s == start)
}

/// Starts the detached watcher for a deadline. It re-checks the child every
/// slice and returns as soon as the child has ended or its pid has changed
/// hands. At the deadline it stops the child's tree if the child is still
/// that process.
fn arm_spawn_deadline(pid: i64, start: u64, timeout_ms: i64) -> std::io::Result<()> {
    let deadline = std::time::Instant::now() + Duration::from_millis(timeout_ms as u64);
    std::thread::Builder::new()
        .name("proc_spawn-deadline".to_string())
        .spawn(move || {
            while spawn_is_ours(pid, start) {
                let left = deadline.saturating_duration_since(std::time::Instant::now());
                if left.is_zero() {
                    eprintln!(
                        "[proc.spawn] pid {pid} passed its {timeout_ms} ms deadline; its tree was stopped"
                    );
                    stop_spawn_tree(pid);
                    return;
                }
                std::thread::sleep(left.min(SPAWN_WATCH_SLICE));
            }
        })
        .map(|_| ())
}

/// Stops the child and its process group: SIGTERM to the group, up to two
/// seconds for it to empty, then SIGKILL to whatever is left. The child was
/// checked to be the same running process just before this is called.
#[cfg(unix)]
fn stop_spawn_tree(pid: i64) {
    let native = libc::pid_t::try_from(pid).unwrap_or(libc::pid_t::MAX);
    let group_live = || {
        // SAFETY: signal 0 sends nothing and touches no memory.
        let rc = unsafe { libc::kill(-native, 0) };
        rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
    };
    // SAFETY: kill(2) takes a pid and a signal number and touches no memory.
    unsafe { libc::kill(-native, libc::SIGTERM) };
    let until = std::time::Instant::now() + SPAWN_STOP_GRACE;
    while group_live() && std::time::Instant::now() < until {
        std::thread::sleep(Duration::from_millis(20));
    }
    if group_live() {
        // SAFETY: as above.
        unsafe { libc::kill(-native, libc::SIGKILL) };
    }
}

/// The Windows stop: taskkill /T /F on the tree, once.
#[cfg(windows)]
fn stop_spawn_tree(pid: i64) {
    taskkill_tree(u32::try_from(pid).unwrap_or(u32::MAX));
}

#[cfg(not(any(unix, windows)))]
fn stop_spawn_tree(_pid: i64) {}

/// The immediate stop for a child whose watcher could not be started.
#[cfg(unix)]
fn stop_spawn_tree_now(pid: i64) {
    let native = libc::pid_t::try_from(pid).unwrap_or(libc::pid_t::MAX);
    // SAFETY: kill(2) takes a pid and a signal number and touches no memory.
    unsafe { libc::kill(-native, libc::SIGKILL) };
}

#[cfg(windows)]
fn stop_spawn_tree_now(pid: i64) {
    taskkill_tree(u32::try_from(pid).unwrap_or(u32::MAX));
}

#[cfg(not(any(unix, windows)))]
fn stop_spawn_tree_now(_pid: i64) {}

/// Whether a process has ended. A child this process spawned is reaped here,
/// so a finished child is not left a zombie that `kill(pid, 0)` would still
/// find and report as running.
fn proc_has_ended(pid: i64) -> bool {
    #[cfg(unix)]
    {
        let native = libc::pid_t::try_from(pid).unwrap_or(libc::pid_t::MAX);
        let mut status: libc::c_int = 0;
        // SAFETY: waitpid writes only to `status`, which lives for the call.
        let reaped = unsafe { libc::waitpid(native, &mut status, libc::WNOHANG) };
        if reaped == native {
            return true;
        }
        if reaped == 0 {
            return false;
        }
        // Not this process's child (ECHILD): ask whether the pid is still there.
        // SAFETY: signal 0 sends nothing and touches no memory.
        let alive = unsafe { libc::kill(native, 0) } == 0
            || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM);
        !alive
    }
    #[cfg(not(unix))]
    {
        !proc_live(pid)
    }
}

fn bi_proc_wait(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_wait", &args, &input, 2)?;
    let pid = proc_pid("proc_wait", args.first())?;
    let timeout_ms: u64 = match args.get(1) {
        None => 30_000,
        Some(Value::Int(t)) if *t >= 0 => *t as u64,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "proc_wait",
                "a timeout: a non-negative Int of milliseconds",
                &other.to_display_string(),
            ))
        }
    };
    // A pid that is not running now was never waited for: E_NOT_FOUND. A
    // process that ends while waited for is true.
    if !proc_live(pid) {
        // Some hosts do not list a zombie (macOS), so a child that ended before
        // this call lands here and still has to be reaped.
        proc_has_ended(pid);
        if spawned_take(pid) {
            return Ok(Value::Bool(true));
        }
        return Err(crate::safety::not_found(
            "proc_wait",
            "process",
            &pid.to_string(),
        ));
    }

    // Checked at least once, so a zero timeout still answers for a live
    // process; the loop ends because `waited` grows every pass.
    let started = std::time::Instant::now();
    loop {
        if proc_has_ended(pid) {
            spawned_take(pid);
            return Ok(Value::Bool(true));
        }
        let waited = started.elapsed().as_millis();
        let budget = u128::from(timeout_ms);
        if waited >= budget {
            return Ok(Value::Bool(false));
        }
        let left = (budget - waited).min(100) as u64;
        std::thread::sleep(std::time::Duration::from_millis(left));
    }
}

/// Asked in-process, as every other proc reader asks. `kill -0` exits 1 with
/// EPERM for a live process this user may not signal, so on Unix it called
/// init and every other user's process gone; on Windows a PowerShell that
/// failed to start read as "no such process".
fn bi_proc_exists(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let pid = pid_arg("proc_exists", args.first())?;
    Ok(Value::Bool(proc_live(pid)))
}

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

    /// Pid 1 (init) and pid 4 (System) belong to the OS, not to the tester,
    /// which is the case `kill -0` answered false for.
    #[test]
    fn a_live_process_of_another_user_exists_and_a_free_pid_does_not() {
        let own = Value::Int(i64::from(std::process::id()));
        let os = Value::Int(if cfg!(windows) { 4 } else { 1 });
        for (pid, want) in [(own, true), (os, true), (Value::Int(999_999_999), false)] {
            let got = bi_proc_exists(vec![pid.clone()], None).unwrap();
            assert!(
                matches!(got, Value::Bool(b) if b == want),
                "{pid:?} -> {got:?}"
            );
        }
    }
}

/// The child process ids of a live process, from the host's own tree query.
// Was a PowerShell WMI query; now read in process through sysinfo.
#[cfg(windows)]
fn proc_child_pids(pid: i64) -> Result<Vec<i64>> {
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
    let parent = sysinfo::Pid::from_u32(pid as u32);
    let mut children: Vec<i64> = sys
        .processes()
        .iter()
        .filter(|(_, proc_)| proc_.parent() == Some(parent))
        .map(|(child, _)| i64::from(child.as_u32()))
        .collect();
    children.sort_unstable();
    Ok(children)
}

#[cfg(not(windows))]
fn proc_child_pids(pid: i64) -> Result<Vec<i64>> {
    let mut cmd = crate::safety::child_command("pgrep");
    cmd.args(["-P", &pid.to_string()]);
    let out = bounded_cmd_output("proc_children", "pgrep", cmd, PROBE_DEADLINE_SECS)?;
    let text = String::from_utf8_lossy(&out.stdout).into_owned();
    match out.status.code() {
        Some(0) => text
            .lines()
            .map(|l| proc_parse::<i64>("proc_children", "pgrep", l))
            .collect(),
        // pgrep's 1 means nothing matched: a live process with no children.
        Some(1) => Ok(vec![]),
        code => Err(crate::safety::tool_failed(
            "proc_children",
            "pgrep",
            code,
            &String::from_utf8_lossy(&out.stderr),
        )),
    }
}

fn bi_proc_children(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_children", &args, &input, 1)?;
    let pid = proc_pid("proc_children", args.first())?;
    proc_require("proc_children", pid)?;
    let children = proc_child_pids(pid)?;
    Ok(Value::Array(children.into_iter().map(Value::Int).collect()))
}

fn bi_proc_parent(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_parent", &args, &input, 1)?;
    let pid = proc_pid("proc_parent", args.first())?;
    let sys = proc_sys(pid);
    let process = sys
        .process(sysinfo::Pid::from_u32(pid as u32))
        .ok_or_else(|| crate::safety::not_found("proc_parent", "process", &pid.to_string()))?;
    Ok(process
        .parent()
        .map(|p| Value::Int(i64::from(p.as_u32())))
        .unwrap_or(Value::Null))
}

/// A Win32 FILETIME: 100 ns ticks split into two 32-bit halves.
#[cfg(windows)]
#[repr(C)]
#[derive(Default, Clone, Copy)]
struct WinFileTime {
    low: u32,
    high: u32,
}

#[cfg(windows)]
impl WinFileTime {
    fn ticks(self) -> u64 {
        (u64::from(self.high) << 32) | u64::from(self.low)
    }
}

/// A Win32 THREADENTRY32, as Thread32First and Thread32Next fill it.
#[cfg(windows)]
#[repr(C)]
struct WinThreadEntry32 {
    dw_size: u32,
    cnt_usage: u32,
    th32_thread_id: u32,
    th32_owner_process_id: u32,
    tp_base_pri: i32,
    tp_delta_pri: i32,
    dw_flags: u32,
}

/// Runs `f` with a handle to process `pid` opened with
/// PROCESS_QUERY_LIMITED_INFORMATION, then closes the handle exactly once,
/// whether `f` succeeds or not. A refused open is E_OS_DENIED, a pid that has
/// gone is E_NOT_FOUND, and anything else is E_BAD_STATE.
#[cfg(windows)]
fn win_with_process<T>(
    builtin: &str,
    pid: i64,
    f: impl FnOnce(*mut std::ffi::c_void) -> Result<T>,
) -> Result<T> {
    use std::ffi::c_void;
    #[link(name = "kernel32")]
    extern "system" {
        fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut c_void;
        fn CloseHandle(handle: *mut c_void) -> i32;
    }
    const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
    const ERROR_ACCESS_DENIED: i32 = 5;
    const ERROR_INVALID_PARAMETER: i32 = 87;
    // SAFETY: OpenProcess takes plain values and returns a handle or null; the
    // pid was checked to fit a u32 by proc_pid before any reader calls this.
    let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid as u32) };
    if handle.is_null() {
        let err = std::io::Error::last_os_error();
        return Err(match err.raw_os_error() {
            Some(ERROR_ACCESS_DENIED) => crate::safety::os_denied(
                builtin,
                format!("{builtin}: the operating system denied PROCESS_QUERY_LIMITED_INFORMATION to process {pid} (ERROR_ACCESS_DENIED)"),
                "the process is protected or belongs to another user; read a process this user owns",
            ),
            Some(ERROR_INVALID_PARAMETER) => {
                crate::safety::not_found(builtin, "process", &pid.to_string())
            }
            _ => crate::safety::bad_state_with_hint(
                builtin,
                &format!("OpenProcess on process {pid} failed: {err}"),
                "a live process this user can query",
            ),
        });
    }
    let result = f(handle);
    // SAFETY: `handle` came from the successful OpenProcess above and is closed
    // here and nowhere else.
    unsafe { CloseHandle(handle) };
    result
}

/// Counts the threads whose owner is `pid`, from a system thread snapshot.
#[cfg(windows)]
fn win_thread_count(builtin: &str, pid: i64) -> Result<i64> {
    use std::ffi::c_void;
    #[link(name = "kernel32")]
    extern "system" {
        fn CreateToolhelp32Snapshot(flags: u32, process: u32) -> *mut c_void;
        fn Thread32First(snapshot: *mut c_void, entry: *mut WinThreadEntry32) -> i32;
        fn Thread32Next(snapshot: *mut c_void, entry: *mut WinThreadEntry32) -> i32;
        fn CloseHandle(handle: *mut c_void) -> i32;
    }
    const TH32CS_SNAPTHREAD: u32 = 0x4;
    const ERROR_NO_MORE_FILES: i32 = 18;
    // INVALID_HANDLE_VALUE is (HANDLE)-1.
    let invalid = -1isize as *mut c_void;
    // SAFETY: CreateToolhelp32Snapshot takes two plain values and returns a
    // snapshot handle or INVALID_HANDLE_VALUE; the handle is closed below.
    let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
    if snap == invalid {
        return Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!(
                "CreateToolhelp32Snapshot failed: {}",
                std::io::Error::last_os_error()
            ),
            "a thread snapshot of this system",
        ));
    }
    let mut entry = WinThreadEntry32 {
        dw_size: std::mem::size_of::<WinThreadEntry32>() as u32,
        cnt_usage: 0,
        th32_thread_id: 0,
        th32_owner_process_id: 0,
        tp_base_pri: 0,
        tp_delta_pri: 0,
        dw_flags: 0,
    };
    let owner = pid as u32;
    let mut count: i64 = 0;
    let mut failure = None;
    // SAFETY: `entry` is a writable THREADENTRY32 whose dw_size is set, and
    // `snap` is the snapshot opened above.
    let mut more = unsafe { Thread32First(snap, &mut entry) } != 0;
    loop {
        if !more {
            // ERROR_NO_MORE_FILES is the normal end of the walk.
            let err = std::io::Error::last_os_error();
            if err.raw_os_error() != Some(ERROR_NO_MORE_FILES) {
                failure = Some(err);
            }
            break;
        }
        if entry.th32_owner_process_id == owner {
            count += 1;
        }
        // SAFETY: as for Thread32First above.
        more = unsafe { Thread32Next(snap, &mut entry) } != 0;
    }
    // SAFETY: `snap` is a handle from CreateToolhelp32Snapshot, closed once.
    unsafe { CloseHandle(snap) };
    match failure {
        Some(err) => Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!("Thread32Next failed: {err}"),
            "a thread snapshot of this system",
        )),
        None => Ok(count),
    }
}

fn bi_proc_priority(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_priority", &args, &input, 1)?;
    let pid = proc_pid("proc_priority", args.first())?;
    proc_require("proc_priority", pid)?;

    // One record on every OS: nice from -20 (highest) to 19 (lowest), and the
    // Windows priority class it corresponds to.
    // Was PowerShell's Get-Process; now read in process (GetPriorityClass).
    #[cfg(windows)]
    let (nice, class) = {
        use std::ffi::c_void;
        #[link(name = "kernel32")]
        extern "system" {
            fn GetPriorityClass(process: *mut c_void) -> u32;
        }
        let raw = win_with_process("proc_priority", pid, |h| {
            // SAFETY: `h` is the live handle win_with_process opened; the call
            // only reads it.
            let class = unsafe { GetPriorityClass(h) };
            if class == 0 {
                return Err(crate::safety::bad_state_with_hint(
                    "proc_priority",
                    &format!(
                        "GetPriorityClass failed: {}",
                        std::io::Error::last_os_error()
                    ),
                    "a live process this user can query",
                ));
            }
            Ok(class)
        })?;
        // Each Windows class maps to the nice value its PowerShell name had.
        let (nice, name): (i64, &str) = match raw {
            0x40 => (19, "Idle"),
            0x4000 => (10, "BelowNormal"),
            0x20 => (0, "Normal"),
            0x8000 => (-5, "AboveNormal"),
            0x80 => (-10, "High"),
            0x100 => (-20, "RealTime"),
            other => {
                return Err(crate::safety::tool_failed(
                    "proc_priority",
                    "GetPriorityClass",
                    None,
                    &format!("priority class 0x{other:X} is not one this builtin knows"),
                ))
            }
        };
        (nice, name.to_string())
    };
    #[cfg(not(windows))]
    let (nice, class) = {
        let out = proc_tool(
            "proc_priority",
            "ps",
            {
                let mut c = crate::safety::child_command("ps");
                c.args(["-o", "ni=", "-p", &pid.to_string()]);
                c
            },
            PROBE_DEADLINE_SECS,
        )?;
        let nice: i64 = proc_parse("proc_priority", "ps", &String::from_utf8_lossy(&out.stdout))?;
        let class = match nice {
            n if n >= 15 => "Idle",
            n if n >= 5 => "BelowNormal",
            n if n > -5 => "Normal",
            n if n > -10 => "AboveNormal",
            n if n > -15 => "High",
            _ => "RealTime",
        };
        (nice, class.to_string())
    };
    let mut rec = BTreeMap::new();
    rec.insert("nice".to_string(), Value::Int(nice));
    rec.insert("class".to_string(), Value::Str(class));
    Ok(Value::Record(rec))
}

fn bi_proc_set_priority(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_set_priority", &args, &input, 2)?;
    let pid = proc_pid("proc_set_priority", args.first())?;
    let priority = match args.get(1) {
        Some(Value::Int(p)) => *p,
        // A non-numeric string was refused, and a missing priority was 0.
        Some(Value::Str(s)) => s
            .trim()
            .parse::<i64>()
            .map_err(|_| crate::safety::bad_arg("proc_set_priority", "an integer priority", s))?,
        other => {
            return Err(crate::safety::bad_arg(
                "proc_set_priority",
                "Int or String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    // nice's range. Outside it the OS clamps the value and says nothing.
    if !(-20..=19).contains(&priority) {
        return Err(crate::safety::bad_arg(
            "proc_set_priority",
            "a priority from -20 (highest) to 19 (lowest)",
            &priority.to_string(),
        ));
    }
    proc_require("proc_set_priority", pid)?;

    #[cfg(windows)]
    {
        let class = match priority {
            p if p < -10 => "High",
            p if p < 0 => "AboveNormal",
            0 => "Normal",
            p if p < 10 => "BelowNormal",
            _ => "Idle",
        };
        let cmd = crate::ps_script!(
            "(Get-Process -Id {}).PriorityClass = {}",
            pid,
            crate::safety::ps_quote(class)
        );
        let mut bounded_cmd = crate::safety::child_command("powershell");
        bounded_cmd.args(["-Command", &cmd]);
        let out = bounded_cmd_output(
            "proc_set_priority",
            "powershell",
            bounded_cmd,
            TOOL_DEADLINE_SECS,
        )?;
        if !out.status.success() {
            return Err(proc_refused(
                "proc_set_priority",
                "powershell",
                pid,
                &out.stderr,
                out.status.code(),
            ));
        }
    }
    #[cfg(not(windows))]
    {
        let mut cmd = crate::safety::child_command("renice");
        cmd.args(["-n", &priority.to_string(), "-p", &pid.to_string()]);
        let out = bounded_cmd_output("proc_set_priority", "renice", cmd, TOOL_DEADLINE_SECS)?;
        if !out.status.success() {
            return Err(proc_refused(
                "proc_set_priority",
                "renice",
                pid,
                &out.stderr,
                out.status.code(),
            ));
        }
    }
    Ok(Value::Bool(true))
}

fn bi_proc_cpu_usage(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_cpu_usage", &args, &input, 1)?;
    let pid = proc_pid("proc_cpu_usage", args.first())?;
    proc_require("proc_cpu_usage", pid)?;
    // Units differ by OS: ps %CPU (percent of one CPU) on Unix, total CPU
    // seconds from GetProcessTimes on Windows. The builtin says so in its doc.
    // Was PowerShell's Get-Process; now read in process (GetProcessTimes).
    #[cfg(windows)]
    let cpu: f64 = win_with_process("proc_cpu_usage", pid, |h| {
        use std::ffi::c_void;
        #[link(name = "kernel32")]
        extern "system" {
            fn GetProcessTimes(
                process: *mut c_void,
                creation: *mut WinFileTime,
                exit: *mut WinFileTime,
                kernel: *mut WinFileTime,
                user: *mut WinFileTime,
            ) -> i32;
        }
        let mut creation = WinFileTime::default();
        let mut exit = WinFileTime::default();
        let mut kernel = WinFileTime::default();
        let mut user = WinFileTime::default();
        // SAFETY: `h` is the live handle win_with_process opened; each
        // out-pointer is a valid, writable FILETIME.
        if unsafe { GetProcessTimes(h, &mut creation, &mut exit, &mut kernel, &mut user) } == 0 {
            return Err(crate::safety::bad_state_with_hint(
                "proc_cpu_usage",
                &format!(
                    "GetProcessTimes failed: {}",
                    std::io::Error::last_os_error()
                ),
                "a live process this user can query",
            ));
        }
        // Kernel plus user time in 100 ns ticks: the total Get-Process reported.
        Ok((kernel.ticks() + user.ticks()) as f64 / 1e7)
    })?;
    #[cfg(not(windows))]
    let cpu: f64 = {
        let out = proc_tool(
            "proc_cpu_usage",
            "ps", // LC_ALL=C: a decimal comma would not parse.
            {
                let mut c = crate::safety::child_command("ps");
                c.env("LC_ALL", "C")
                    .args(["-o", "%cpu=", "-p", &pid.to_string()]);
                c
            },
            PROBE_DEADLINE_SECS,
        )?;
        proc_parse(
            "proc_cpu_usage",
            "ps",
            &String::from_utf8_lossy(&out.stdout),
        )?
    };
    Ok(Value::Float(cpu))
}

fn bi_proc_mem_usage(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_mem_usage", &args, &input, 1)?;
    let pid = proc_pid("proc_mem_usage", args.first())?;
    proc_require("proc_mem_usage", pid)?;
    // Was PowerShell's Get-Process; now read in process through sysinfo.
    #[cfg(windows)]
    let bytes: i64 = {
        let sys = proc_sys(pid);
        let process = sys
            .process(sysinfo::Pid::from_u32(pid as u32))
            .ok_or_else(|| {
                crate::safety::not_found("proc_mem_usage", "process", &pid.to_string())
            })?;
        i64::try_from(process.memory()).unwrap_or(i64::MAX)
    };
    #[cfg(not(windows))]
    let bytes: i64 = {
        let out = proc_tool(
            "proc_mem_usage",
            "ps",
            {
                let mut c = crate::safety::child_command("ps");
                c.args(["-o", "rss=", "-p", &pid.to_string()]);
                c
            },
            PROBE_DEADLINE_SECS,
        )?;
        // ps reports resident kilobytes.
        proc_parse::<i64>(
            "proc_mem_usage",
            "ps",
            &String::from_utf8_lossy(&out.stdout),
        )?
        .saturating_mul(1024)
    };
    Ok(Value::Int(bytes))
}

fn bi_proc_threads(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_threads", &args, &input, 1)?;
    let pid = proc_pid("proc_threads", args.first())?;
    proc_require("proc_threads", pid)?;
    // Was PowerShell's Get-Process; now counted in process from a thread snapshot.
    #[cfg(windows)]
    let threads: i64 = win_thread_count("proc_threads", pid)?;
    #[cfg(target_os = "linux")]
    let threads: i64 = {
        let entries = std::fs::read_dir(format!("/proc/{pid}/task"))
            .map_err(|e| proc_read_failed("proc_threads", pid, "its threads", &e))?;
        let mut n: i64 = 0;
        for entry in entries {
            entry.map_err(|e| proc_read_failed("proc_threads", pid, "its threads", &e))?;
            n += 1;
        }
        n
    };
    #[cfg(all(not(windows), not(target_os = "linux")))]
    let threads: i64 = {
        let out = proc_tool(
            "proc_threads",
            "ps",
            {
                let mut c = crate::safety::child_command("ps");
                c.args(["-M", "-p", &pid.to_string()]);
                c
            },
            PROBE_DEADLINE_SECS,
        )?;
        // ps -M prints a header, then one line per thread.
        let lines = String::from_utf8_lossy(&out.stdout).lines().count();
        i64::try_from(lines.saturating_sub(1)).unwrap_or(i64::MAX)
    };
    Ok(Value::Int(threads))
}

#[cfg(target_os = "linux")]
fn proc_env_of(pid: i64) -> Result<BTreeMap<String, Value>> {
    let data = std::fs::read(format!("/proc/{pid}/environ"))
        .map_err(|e| proc_read_failed("proc_env", pid, "its environment", &e))?;
    Ok(data
        .split(|&b| b == 0)
        .filter(|entry| !entry.is_empty())
        .filter_map(|entry| {
            let text = String::from_utf8_lossy(entry);
            let (k, v) = text.split_once('=')?;
            Some((k.to_string(), Value::Str(v.to_string())))
        })
        .collect())
}

/// A process's `sysinfo` record with its environment and working directory
/// refreshed, for one pid. Windows reads both through the process handle and
/// macOS through sysctl KERN_PROCARGS2, so a protected or another user's
/// process comes back with an empty environment (and, on Windows, no
/// directory); the readers turn that into E_OS_DENIED.
#[cfg(any(windows, target_os = "macos"))]
fn proc_sys_env_cwd(pid: i64) -> System {
    let spid = sysinfo::Pid::from_u32(pid as u32);
    let mut sys = System::new();
    let kind = sysinfo::ProcessRefreshKind::nothing()
        .with_environ(sysinfo::UpdateKind::Always)
        .with_cwd(sysinfo::UpdateKind::Always);
    sys.refresh_processes_specifics(sysinfo::ProcessesToUpdate::Some(&[spid]), true, kind);
    sys
}

/// E_OS_DENIED for a live process whose environment or directory the OS
/// would not give us.
#[cfg(any(windows, target_os = "macos"))]
fn proc_access_denied(builtin: &str, what: &str, pid: i64) -> anyhow::Error {
    crate::safety::os_denied(
        builtin,
        format!("{builtin}: {what} of process {pid} is not readable"),
        "the process is protected or belongs to another user; read a process this user owns",
    )
}

#[cfg(any(windows, target_os = "macos"))]
fn proc_env_of(pid: i64) -> Result<BTreeMap<String, Value>> {
    let sys = proc_sys_env_cwd(pid);
    let process = sys
        .process(sysinfo::Pid::from_u32(pid as u32))
        .ok_or_else(|| crate::safety::not_found("proc_env", "process", &pid.to_string()))?;
    if process.environ().is_empty() {
        return Err(proc_access_denied("proc_env", "the environment", pid));
    }
    Ok(process
        .environ()
        .iter()
        .filter_map(|entry| {
            let text = entry.to_string_lossy();
            let (k, v) = text.split_once('=')?;
            // cmd keeps hidden per-drive entries named "=C:"; they are not variables.
            if k.is_empty() {
                return None;
            }
            Some((k.to_string(), Value::Str(v.to_string())))
        })
        .collect())
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
fn proc_env_of(pid: i64) -> Result<BTreeMap<String, Value>> {
    Err(crate::safety::unimplemented(
        "proc_env",
        &format!("reading the environment of process {pid} on this OS"),
        "this shell's own environment is available from env() and sys_env_all(); other processes' environments are readable on Linux, macOS and Windows",
    ))
}

fn bi_proc_env(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_env", &args, &input, 1)?;
    let pid = proc_pid("proc_env", args.first())?;
    // Both branches answer through `gate_env_secret`, as `env()` and `env_vars()`
    // do: a secret-named variable of another process is a credential as well.
    let rec: BTreeMap<String, Value> = if proc_is_self(pid) {
        // This shell's own environment, answered in-process on every OS.
        std::env::vars_os()
            .map(|(k, v)| {
                let k = k.to_string_lossy().into_owned();
                let gated = gate_env_secret(&k, v.to_string_lossy().into_owned());
                (k, gated)
            })
            .collect()
    } else {
        proc_require("proc_env", pid)?;
        proc_env_of(pid)?
            .into_iter()
            .map(|(k, v)| {
                let gated = match v {
                    Value::Str(s) => gate_env_secret(&k, s),
                    other => other,
                };
                (k, gated)
            })
            .collect()
    };
    Ok(Value::Record(rec))
}

#[cfg(target_os = "linux")]
fn proc_cwd_of(pid: i64) -> Result<String> {
    let path = std::fs::read_link(format!("/proc/{pid}/cwd"))
        .map_err(|e| proc_read_failed("proc_cwd", pid, "its working directory", &e))?;
    Ok(path.to_string_lossy().into_owned())
}

#[cfg(target_os = "macos")]
fn proc_cwd_of(pid: i64) -> Result<String> {
    let out = proc_tool(
        "proc_cwd",
        "lsof",
        {
            let mut c = crate::safety::child_command("lsof");
            c.args(["-p", &pid.to_string(), "-Fn", "-d", "cwd"]);
            c
        },
        PROBE_DEADLINE_SECS,
    )?;
    let text = String::from_utf8_lossy(&out.stdout).into_owned();
    let named = text
        .lines()
        .find_map(|l| l.strip_prefix('n').map(str::to_string));
    named.ok_or_else(|| {
        crate::safety::tool_failed(
            "proc_cwd",
            "lsof",
            Some(0),
            "its output named no working directory",
        )
    })
}

#[cfg(windows)]
fn proc_cwd_of(pid: i64) -> Result<String> {
    let sys = proc_sys_env_cwd(pid);
    let process = sys
        .process(sysinfo::Pid::from_u32(pid as u32))
        .ok_or_else(|| crate::safety::not_found("proc_cwd", "process", &pid.to_string()))?;
    match process.cwd() {
        Some(dir) if !dir.as_os_str().is_empty() => Ok(dir.to_string_lossy().into_owned()),
        _ => Err(proc_access_denied("proc_cwd", "the working directory", pid)),
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
fn proc_cwd_of(pid: i64) -> Result<String> {
    Err(crate::safety::unimplemented(
        "proc_cwd",
        &format!("the working directory of process {pid} on this OS"),
        "this shell's own working directory is pwd()",
    ))
}

fn bi_proc_cwd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_cwd", &args, &input, 1)?;
    let pid = proc_pid("proc_cwd", args.first())?;
    if proc_is_self(pid) {
        let dir = std::env::current_dir().map_err(|e| {
            crate::safety::tool_failed("proc_cwd", "current_dir", Some(0), &e.to_string())
        })?;
        return Ok(Value::Str(dir.to_string_lossy().into_owned()));
    }
    proc_require("proc_cwd", pid)?;
    Ok(Value::Str(proc_cwd_of(pid)?))
}

// Was PowerShell's Get-Process; now read in process through sysinfo.
#[cfg(windows)]
fn proc_exe_of(pid: i64) -> Result<String> {
    let sys = proc_sys(pid);
    let path = sys
        .process(sysinfo::Pid::from_u32(pid as u32))
        .and_then(|process| process.exe())
        .map(|exe| exe.to_string_lossy().trim().to_string())
        .unwrap_or_default();
    if path.is_empty() {
        return Err(crate::safety::os_denied(
            "proc_exe",
            format!("proc_exe: the path of process {pid} is not readable"),
            "the process is protected or belongs to another user; read the path of a process this user owns",
        ));
    }
    Ok(path)
}

#[cfg(target_os = "linux")]
fn proc_exe_of(pid: i64) -> Result<String> {
    let path = std::fs::read_link(format!("/proc/{pid}/exe"))
        .map_err(|e| proc_read_failed("proc_exe", pid, "its executable", &e))?;
    Ok(path.to_string_lossy().into_owned())
}

#[cfg(all(not(windows), not(target_os = "linux")))]
fn proc_exe_of(pid: i64) -> Result<String> {
    let out = proc_tool(
        "proc_exe",
        "ps",
        {
            let mut c = crate::safety::child_command("ps");
            c.args(["-p", &pid.to_string(), "-o", "comm="]);
            c
        },
        PROBE_DEADLINE_SECS,
    )?;
    let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if path.is_empty() {
        return Err(crate::safety::tool_failed(
            "proc_exe",
            "ps",
            Some(0),
            "its output named no executable",
        ));
    }
    Ok(path)
}

fn bi_proc_exe(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_exe", &args, &input, 1)?;
    let pid = proc_pid("proc_exe", args.first())?;
    proc_require("proc_exe", pid)?;
    Ok(Value::Str(proc_exe_of(pid)?))
}

// Was `(Get-CimInstance Win32_Process -Filter ProcessId=N).CommandLine` run
// through PowerShell and split on whitespace here; now read in process.
// sysinfo's cmd() is the command line as CommandLineToArgvW splits it, so each
// element is one argument.
#[cfg(windows)]
fn proc_cmdline_of(pid: i64) -> Result<Vec<String>> {
    let spid = sysinfo::Pid::from_u32(pid as u32);
    let mut sys = System::new();
    sys.refresh_processes_specifics(
        sysinfo::ProcessesToUpdate::Some(&[spid]),
        true,
        sysinfo::ProcessRefreshKind::nothing().with_cmd(sysinfo::UpdateKind::Always),
    );
    let argv: Vec<String> = sys
        .process(spid)
        .map(|process| {
            process
                .cmd()
                .iter()
                .map(|arg| arg.to_string_lossy().into_owned())
                .collect()
        })
        .unwrap_or_default();
    if argv.is_empty() {
        return Err(crate::safety::os_denied(
            "proc_cmdline",
            format!("proc_cmdline: the command line of process {pid} is not readable"),
            "the process is protected or belongs to another user; read the command line of a process this user owns",
        ));
    }
    Ok(argv)
}

#[cfg(target_os = "linux")]
fn proc_cmdline_of(pid: i64) -> Result<Vec<String>> {
    let data = std::fs::read(format!("/proc/{pid}/cmdline"))
        .map_err(|e| proc_read_failed("proc_cmdline", pid, "its command line", &e))?;
    // A zombie or kernel thread has no arguments at all.
    if data.is_empty() {
        return Ok(vec![]);
    }
    // Every argument ends in a NUL, so drop the one trailing terminator and
    // split on the rest. An empty argument is a real argument, not noise.
    let body: &[u8] = data.strip_suffix(&[0u8][..]).unwrap_or(&data[..]);
    Ok(body
        .split(|&b| b == 0)
        .map(|arg| String::from_utf8_lossy(arg).into_owned())
        .collect())
}

#[cfg(all(not(windows), not(target_os = "linux")))]
fn proc_cmdline_of(pid: i64) -> Result<Vec<String>> {
    let out = proc_tool(
        "proc_cmdline",
        "ps",
        {
            let mut c = crate::safety::child_command("ps");
            c.args(["-p", &pid.to_string(), "-o", "args="]);
            c
        },
        PROBE_DEADLINE_SECS,
    )?;
    let line = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if line.is_empty() {
        return Err(crate::safety::tool_failed(
            "proc_cmdline",
            "ps",
            Some(0),
            "its output named no command line",
        ));
    }
    // ps does not quote its output, so an argument with a space is split.
    let argv: Vec<String> = line.split_whitespace().map(str::to_string).collect();
    Ok(argv)
}

fn bi_proc_cmdline(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_cmdline", &args, &input, 1)?;
    let pid = proc_pid("proc_cmdline", args.first())?;
    proc_require("proc_cmdline", pid)?;
    let argv = proc_cmdline_of(pid)?;
    Ok(Value::Array(argv.into_iter().map(Value::Str).collect()))
}

/// The earliest epoch second `from_epoch` and `to_epoch` take: 0001-01-01T00:00:00Z.
const EPOCH_MIN: i64 = -62_135_596_800;
/// The latest: 9999-12-31T23:59:59Z. Years 0001 to 9999 only.
const EPOCH_MAX: i64 = 253_402_300_799;

/// The refusal for an epoch second outside the years 0001 to 9999.
fn epoch_range(builtin: &str, shown: &str) -> anyhow::Error {
    crate::safety::value_not_representable(
        builtin,
        format!("{builtin}: {shown} is outside the years 0001 to 9999"),
        "epoch seconds run from -62135596800 (0001-01-01T00:00:00Z) to 253402300799 (9999-12-31T23:59:59Z)",
    )
}

/// from_epoch(seconds) - The UTC ISO 8601 text of an instant, given as seconds
/// since 1970-01-01T00:00:00Z.
/// Args:
///   - seconds: Int, or Float for a fractional second (the fraction is dropped:
///     -0.5 is 1969-12-31T23:59:59Z, the second that contains the instant)
/// Returns: String, to the second, ending in Z
///
/// Years 0001 to 9999 only; outside them is E_BAD_VALUE.
///
/// Example:
///   from_epoch(0)              # "1970-01-01T00:00:00Z"
///   from_epoch(86400.5)        # "1970-01-02T00:00:00Z"
fn bi_from_epoch(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (subject, rest) = subject_and_rest("from_epoch", args, input)?;
    if !rest.is_empty() {
        return Err(arity_error(
            "from_epoch",
            "one number of seconds",
            rest.len(),
        ));
    }
    let secs: i64 = match subject {
        Value::Int(n) => n,
        Value::Float(f) => {
            // The bounds are checked before the cast, so the cast cannot saturate.
            if !f.is_finite() || f < EPOCH_MIN as f64 || f >= (EPOCH_MAX + 1) as f64 {
                return Err(epoch_range("from_epoch", &float_for_message(f)));
            }
            f.floor() as i64
        }
        other => {
            return Err(crate::safety::bad_arg(
                "from_epoch",
                "a number of seconds",
                other.type_name(),
            ))
        }
    };
    if !(EPOCH_MIN..=EPOCH_MAX).contains(&secs) {
        return Err(epoch_range("from_epoch", &secs.to_string()));
    }
    let at = chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0)
        .ok_or_else(|| epoch_range("from_epoch", &secs.to_string()))?;
    Ok(Value::Str(at.format("%Y-%m-%dT%H:%M:%SZ").to_string()))
}

/// to_epoch(date) - The whole seconds since 1970-01-01T00:00:00Z of an ISO 8601
/// UTC date or datetime.
/// Args:
///   - date: String (or the piped text): a datetime with a Z or an offset, such
///     as 1970-01-02T00:00:00Z, or a date such as 1970-01-02 (midnight UTC)
/// Returns: Int
///
/// A datetime's offset is applied, and a fraction of a second is dropped. Years
/// 0001 to 9999 only; text that is not such a date is E_BAD_VALUE.
///
/// Example:
///   to_epoch("1970-01-02T00:00:00Z")   # 86400
///   "1970-01-01" | to_epoch()          # 0
fn bi_to_epoch(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (text, rest) = text_subject("to_epoch", args, input)?;
    if !rest.is_empty() {
        return Err(arity_error("to_epoch", "one date", rest.len()));
    }
    let at = if let Ok(datetime) = chrono::DateTime::parse_from_rfc3339(&text) {
        datetime.timestamp()
    } else if let Some(midnight) = chrono::NaiveDate::parse_from_str(&text, "%Y-%m-%d")
        .ok()
        .and_then(|date| date.and_hms_opt(0, 0, 0))
    {
        midnight.and_utc().timestamp()
    } else {
        return Err(crate::safety::value_not_representable(
            "to_epoch",
            format!("to_epoch: {text:?} is not an ISO 8601 UTC date or datetime"),
            "write 1970-01-02T00:00:00Z, or a date such as 1970-01-02 for midnight UTC",
        ));
    };
    if !(EPOCH_MIN..=EPOCH_MAX).contains(&at) {
        return Err(epoch_range("to_epoch", &format!("{text:?}")));
    }
    Ok(Value::Int(at))
}

/// Seconds since the Unix epoch, as UTC ISO 8601 to the second, or None when
/// the value is out of chrono's range. The one date form the shell answers in:
/// `ps lstart` and `ToString('o')` gave three different spellings, and the
/// Unix one changed with the locale.
fn utc_iso_seconds(secs: i64) -> Option<String> {
    chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0)
        .map(|at| at.format("%Y-%m-%dT%H:%M:%SZ").to_string())
}

/// Seconds since the Unix epoch, as UTC ISO 8601 to the second. One form on
/// every OS: see `utc_iso_seconds`.
fn proc_utc_iso(pid: i64, secs: u64) -> Result<String> {
    i64::try_from(secs)
        .ok()
        .and_then(utc_iso_seconds)
        .ok_or_else(|| {
            crate::safety::tool_failed(
                "proc_start_time",
                "sysinfo",
                Some(0),
                &format!("the start time of process {pid} is out of range"),
            )
        })
}

fn bi_proc_start_time(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_start_time", &args, &input, 1)?;
    let pid = proc_pid("proc_start_time", args.first())?;
    let sys = proc_sys(pid);
    let secs = sys
        .process(sysinfo::Pid::from_u32(pid as u32))
        .ok_or_else(|| crate::safety::not_found("proc_start_time", "process", &pid.to_string()))?
        .start_time();
    Ok(Value::Str(proc_utc_iso(pid, secs)?))
}

/// Sends a stop or continue signal. Unix sends it with kill(2), as proc_kill
/// does. Windows opens the process with PROCESS_SUSPEND_RESUME and calls
/// ntdll's NtSuspendProcess or NtResumeProcess: see the Windows definition.
#[cfg(unix)]
fn proc_signal(builtin: &str, pid: i64, name: &str) -> Result<Value> {
    let sig = if name == "STOP" {
        libc::SIGSTOP
    } else {
        libc::SIGCONT
    };
    let native = libc::pid_t::try_from(pid).map_err(|_| {
        crate::safety::bad_arg(
            builtin,
            "a process id that fits the operating system's pid type",
            &pid.to_string(),
        )
    })?;
    // SAFETY: kill(2) takes a pid and a signal number and touches no memory.
    if unsafe { libc::kill(native, sig) } == 0 {
        return Ok(Value::Bool(true));
    }
    let err = std::io::Error::last_os_error();
    Err(match err.raw_os_error() {
        Some(libc::ESRCH) => crate::safety::not_found(builtin, "process", &pid.to_string()),
        Some(libc::EPERM) => crate::safety::os_denied(
            builtin,
            format!("{builtin}: the operating system denied SIG{name} to process {pid} (EPERM)"),
            "the process belongs to another user or is protected; signal a process this user owns",
        ),
        _ => crate::safety::tool_failed(
            builtin,
            &format!("kill({pid}, SIG{name})"),
            None,
            &err.to_string(),
        ),
    })
}

/// The Windows half of [`proc_signal`]. A PowerShell script, built with
/// `ps_script!` so no caller text reaches it, opens the process with
/// PROCESS_SUSPEND_RESUME (0x0800), calls NtSuspendProcess or NtResumeProcess
/// through Add-Type P/Invoke, and closes the handle. It prints one coded line:
/// `ok`, `err:open:<GetLastError>` or `err:nt:<NTSTATUS in hex>`. That line is
/// the only thing read back; prose from PowerShell is never parsed.
#[cfg(windows)]
fn proc_signal(builtin: &str, pid: i64, name: &str) -> Result<Value> {
    const PRELUDE: &str = "$ErrorActionPreference = 'Stop'; Add-Type -Namespace IronShellProc -Name Native -MemberDefinition '[DllImport(\"kernel32.dll\", SetLastError=true)] public static extern IntPtr OpenProcess(uint access, bool inherit, uint pid); [DllImport(\"kernel32.dll\", SetLastError=true)] public static extern bool CloseHandle(IntPtr handle); [DllImport(\"ntdll.dll\")] public static extern int NtSuspendProcess(IntPtr handle); [DllImport(\"ntdll.dll\")] public static extern int NtResumeProcess(IntPtr handle);'; ";
    let nt: &'static str = if name == "STOP" {
        "NtSuspendProcess"
    } else {
        "NtResumeProcess"
    };
    let cmd = crate::ps_script!(
        "{}$h = [IronShellProc.Native]::OpenProcess(0x0800, $false, {}); if ($h -eq [IntPtr]::Zero) {{ 'err:open:' + [Runtime.InteropServices.Marshal]::GetLastWin32Error() }} else {{ $s = [IronShellProc.Native]::{}($h); [void][IronShellProc.Native]::CloseHandle($h); if ($s -eq 0) {{ 'ok' }} else {{ 'err:nt:' + $s.ToString('X8') }} }}",
        PRELUDE,
        pid,
        nt
    );
    let mut c = crate::safety::child_command("powershell");
    c.args(["-NoProfile", "-NonInteractive", "-Command", &cmd]);
    let out = bounded_cmd_output(builtin, "powershell", c, TOOL_DEADLINE_SECS)?;
    let stdout = String::from_utf8_lossy(&out.stdout);
    let verdict = stdout
        .lines()
        .map(str::trim)
        .find(|l| *l == "ok" || l.starts_with("err:"));
    match verdict {
        Some("ok") => Ok(Value::Bool(true)),
        Some("err:open:5") => Err(crate::safety::os_denied(
            builtin,
            format!("{builtin}: the operating system denied PROCESS_SUSPEND_RESUME to process {pid} (ERROR_ACCESS_DENIED)"),
            "the process is protected or belongs to another user; act on a process this user owns",
        )),
        Some("err:open:87") => Err(crate::safety::not_found(
            builtin,
            "process",
            &pid.to_string(),
        )),
        Some(line) if line.starts_with("err:open:") => Err(crate::safety::tool_failed(
            builtin,
            "OpenProcess",
            None,
            &format!("OpenProcess on process {pid} failed: {line}"),
        )),
        Some(line) if line.starts_with("err:nt:") => Err(crate::safety::tool_failed(
            builtin,
            nt,
            None,
            &format!(
                "{nt} on process {pid} returned NTSTATUS 0x{}",
                &line["err:nt:".len()..]
            ),
        )),
        _ => Err(crate::safety::tool_failed(
            builtin,
            "powershell",
            out.status.code(),
            &String::from_utf8_lossy(&out.stderr),
        )),
    }
}

#[cfg(not(any(unix, windows)))]
fn proc_signal(builtin: &str, pid: i64, name: &str) -> Result<Value> {
    Err(crate::safety::unimplemented(
        builtin,
        &format!("sending the {name} signal to process {pid}: this platform has no suspend or resume call in this shell"),
        "use proc_kill to end the process",
    ))
}

fn bi_proc_suspend(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_suspend", &args, &input, 1)?;
    let pid = proc_pid("proc_suspend", args.first())?;
    proc_refuse_self("proc_suspend", pid)?;
    proc_require("proc_suspend", pid)?;
    proc_signal("proc_suspend", pid, "STOP")
}

fn bi_proc_resume(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    proc_check("proc_resume", &args, &input, 1)?;
    let pid = proc_pid("proc_resume", args.first())?;
    proc_refuse_self("proc_resume", pid)?;
    proc_require("proc_resume", pid)?;
    proc_signal("proc_resume", pid, "CONT")
}

// ============================================================================
// 250-269: Filesystem Extended
// ============================================================================

fn bi_fs_stat(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "fs_stat",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    crate::security::check_read_jail("fs_stat", &path)?;
    // A missing path is the documented Null. The old code returned Null for
    // any metadata error, so a permission or I/O failure read as absence.
    let meta = match std::fs::metadata(&path) {
        Ok(meta) => meta,
        Err(e) if path_is_absent(&e) => return Ok(Value::Null),
        Err(e) => return Err(crate::safety::fs_error("fs_stat", &path, &e)),
    };
    let mut rec = std::collections::BTreeMap::new();
    rec.insert("size".to_string(), Value::Int(meta.len() as i64));
    rec.insert("is_file".to_string(), Value::Bool(meta.is_file()));
    rec.insert("is_dir".to_string(), Value::Bool(meta.is_dir()));
    rec.insert(
        "is_symlink".to_string(),
        Value::Bool(meta.file_type().is_symlink()),
    );
    rec.insert(
        "readonly".to_string(),
        Value::Bool(meta.permissions().readonly()),
    );

    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        rec.insert("mode".to_string(), Value::Int(meta.mode() as i64));
        rec.insert("uid".to_string(), Value::Int(meta.uid() as i64));
        rec.insert("gid".to_string(), Value::Int(meta.gid() as i64));
        rec.insert("inode".to_string(), Value::Int(meta.ino() as i64));
        rec.insert("nlink".to_string(), Value::Int(meta.nlink() as i64));
        rec.insert("blocks".to_string(), Value::Int(meta.blocks() as i64));
        rec.insert("blksize".to_string(), Value::Int(meta.blksize() as i64));
    }

    if let Ok(modified) = meta.modified() {
        if let Ok(duration) = modified.duration_since(std::time::UNIX_EPOCH) {
            rec.insert(
                "modified".to_string(),
                Value::Int(duration.as_secs() as i64),
            );
        }
    }
    if let Ok(accessed) = meta.accessed() {
        if let Ok(duration) = accessed.duration_since(std::time::UNIX_EPOCH) {
            rec.insert(
                "accessed".to_string(),
                Value::Int(duration.as_secs() as i64),
            );
        }
    }
    if let Ok(created) = meta.created() {
        if let Ok(duration) = created.duration_since(std::time::UNIX_EPOCH) {
            rec.insert("created".to_string(), Value::Int(duration.as_secs() as i64));
        }
    }

    Ok(Value::Record(rec))
}

fn bi_fs_lstat(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "fs_lstat",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // Same rule as fs_stat: only a missing path is Null.
    let meta = match std::fs::symlink_metadata(&path) {
        Ok(meta) => meta,
        Err(e) if path_is_absent(&e) => return Ok(Value::Null),
        Err(e) => return Err(crate::safety::fs_error("fs_lstat", &path, &e)),
    };
    let mut rec = std::collections::BTreeMap::new();
    rec.insert("size".to_string(), Value::Int(meta.len() as i64));
    rec.insert("is_file".to_string(), Value::Bool(meta.is_file()));
    rec.insert("is_dir".to_string(), Value::Bool(meta.is_dir()));
    rec.insert(
        "is_symlink".to_string(),
        Value::Bool(meta.file_type().is_symlink()),
    );
    Ok(Value::Record(rec))
}

fn bi_fs_chmod(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    guard_and_set_permission_mode("fs_chmod", args, input)
}

fn guard_and_set_permission_mode(
    builtin: &'static str,
    args: Vec<Value>,
    input: Option<Value>,
) -> Result<Value> {
    if args.len() != 2 || input.is_some() {
        return Err(crate::safety::arg_err(format!(
            "{builtin} requires exactly path and mode, without pipeline input"
        )));
    }
    let mut args = args.into_iter();
    let Some(Value::Str(path)) = args.next() else {
        return Err(crate::safety::arg_err(format!(
            "{builtin} path must be String"
        )));
    };
    let mode = match args.next() {
        Some(Value::Int(n)) if (0..=0o7777).contains(&n) => n as u32,
        Some(Value::Str(text)) => {
            let digits = text.strip_prefix("0o").unwrap_or(&text);
            if digits.is_empty() || !digits.bytes().all(|b| (b'0'..=b'7').contains(&b)) {
                return Err(crate::safety::arg_err(format!(
                    "{builtin} mode must contain octal digits, optionally prefixed by 0o"
                )));
            }
            let mode = u32::from_str_radix(digits, 8)
                .map_err(|_| crate::safety::arg_err(format!("{builtin} mode is too large")))?;
            if mode > 0o7777 {
                return Err(crate::safety::arg_err(format!(
                    "{builtin} mode must be in 0..=07777"
                )));
            }
            mode
        }
        _ => {
            return Err(crate::safety::arg_err(format!(
                "{builtin} mode must be Int in 0..=07777 or octal String"
            )))
        }
    };
    let path = guard_local_write(builtin, &path)?;
    crate::tx::snapshot_metadata(&path);
    let metadata = fs::metadata(&path).map_err(|e| crate::safety::fs_error(builtin, &path, &e))?;
    let mut permissions = metadata.permissions();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        permissions.set_mode(mode);
    }
    #[cfg(not(unix))]
    {
        // The Windows contract changes the read-only attribute only.
        permissions.set_readonly(mode & 0o200 == 0);
    }
    fs::set_permissions(&path, permissions)
        .map_err(|e| crate::safety::fs_error(builtin, &path, &e))?;
    Ok(Value::Bool(true))
}

fn bi_fs_chown(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if !(2..=3).contains(&args.len()) || input.is_some() {
        return Err(crate::safety::arg_err(
            "fs_chown requires path, owner ID and optional group ID, without pipeline input",
        ));
    }
    // The two platforms' bodies are inline so the guard each calls is in this
    // function's body, where the SELF_GUARDED check reads it.
    #[cfg(windows)]
    {
        // Windows: set the owner of one file to a named account through the
        // native security API. The owner is an account name String, because a
        // numeric ID has no Windows meaning; there is no group argument (chgrp
        // sets the group). A call inside a transaction is refused, because the
        // prior owner is not journaled.
        let mut args = args.into_iter();
        let Some(Value::Str(path)) = args.next() else {
            return Err(crate::safety::arg_err("fs_chown path must be String"));
        };
        let owner = match args.next() {
            Some(Value::Str(name)) => name,
            Some(other) => {
                return Err(crate::safety::bad_arg(
                    "fs_chown",
                    "owner: an account or group name, as a String",
                    other.type_name(),
                ))
            }
            None => {
                return Err(crate::safety::arg_err(
                    "fs_chown requires an owner account name",
                ))
            }
        };
        if args.next().is_some() {
            return Err(crate::safety::bad_arg(
                "fs_chown",
                "path and owner only (Windows sets no group here; use chgrp)",
                "a third argument",
            ));
        }
        windows_account_arg("fs_chown", &owner)?;
        let path = crate::safety::resolve_path_str(&path);
        let path = guard_local_write("fs_chown", &path)?;
        std::fs::symlink_metadata(&path)
            .map_err(|e| crate::safety::fs_error("fs_chown", &path, &e))?;
        windows_refuse_untracked_change("fs_chown")?;
        let mut sid = windows_account_sid("fs_chown", &owner)?;
        windows_set_file_principal("fs_chown", &path, &mut sid, false)?;
        Ok(Value::Bool(true))
    }
    #[cfg(not(windows))]
    {
        fn id(value: Value) -> Result<u32> {
            match value {
                Value::Int(n) if (0..i64::from(u32::MAX)).contains(&n) => Ok(n as u32),
                _ => Err(crate::safety::arg_err("fs_chown IDs must be Int in 0..4294967295, excluding the reserved unchanged sentinel")),
            }
        }
        let mut args = args.into_iter();
        let Some(Value::Str(path)) = args.next() else {
            return Err(crate::safety::arg_err("fs_chown path must be String"));
        };
        let owner = args
            .next()
            .map(id)
            .transpose()?
            .ok_or_else(|| crate::safety::arg_err("fs_chown requires owner ID"))?;
        let group = args.next().map(id).transpose()?;
        let path = crate::safety::resolve_path_str(&path);
        #[cfg(unix)]
        let path = fs::canonicalize(&path)
            .map_err(|e| crate::safety::fs_error("fs_chown", &path, &e))?
            .into_os_string()
            .into_string()
            .map_err(|_| crate::safety::arg_err("fs_chown resolved target must be valid UTF-8"))?;
        let path = guard_local_write("fs_chown", &path)?;
        crate::tx::snapshot_metadata(&path);
        #[cfg(unix)]
        {
            std::os::unix::fs::chown(&path, Some(owner), group)
                .map_err(|e| crate::safety::fs_error("fs_chown", &path, &e))?;
            Ok(Value::Bool(true))
        }
        #[cfg(not(unix))]
        {
            let _ = (path, owner, group);
            Err(crate::safety::unimplemented(
                "fs_chown",
                "Unix numeric ownership is unavailable on this platform",
                "use the platform's ownership and access-control tools",
            ))
        }
    }
}

/// chgrp on Windows: set the primary group of one file to a named account or
/// group. Same guard, existence and transaction checks as fs_chown; the record
/// is {group, path} with the path as the caller wrote it, as on Unix.
#[cfg(windows)]
fn chgrp_windows(group: String, path: String) -> Result<Value> {
    windows_account_arg("chgrp", &group)?;
    let target = guard_local_write("chgrp", &path)?;
    std::fs::symlink_metadata(&target)
        .map_err(|e| crate::safety::fs_error("chgrp", &target, &e))?;
    windows_refuse_untracked_change("chgrp")?;
    let mut sid = windows_account_sid("chgrp", &group)?;
    windows_set_file_principal("chgrp", &target, &mut sid, true)?;
    let mut rec = BTreeMap::new();
    rec.insert("group".to_string(), Value::Str(group));
    rec.insert("path".to_string(), Value::Str(path));
    Ok(Value::Record(rec))
}

/// Windows owner and group arguments are account names. A numeric ID has no
/// Windows meaning, so it is refused rather than looked up as a name.
#[cfg(windows)]
fn windows_account_arg(builtin: &str, name: &str) -> Result<()> {
    if name.trim().is_empty() || name.contains('\0') {
        return Err(crate::safety::bad_arg(
            builtin,
            "an account or group name, not empty",
            "an empty or NUL-containing String",
        ));
    }
    if name.bytes().all(|b| b.is_ascii_digit()) {
        return Err(crate::safety::bad_arg(
            builtin,
            "an account or group name",
            "a numeric ID, which Windows does not use",
        ));
    }
    Ok(())
}

/// A Windows owner or group change is not journaled, so rollback could not
/// undo it. Inside a transaction it is refused before anything changes.
#[cfg(windows)]
fn windows_refuse_untracked_change(builtin: &str) -> Result<()> {
    if crate::tx::is_active() {
        return Err(crate::safety::unimplemented(
            builtin,
            "a Windows owner or group change cannot be rolled back; nothing was changed",
            "finish the transaction first",
        ));
    }
    Ok(())
}

/// The SID of a named account, through LookupAccountNameW's two-call pattern:
/// a sizing call with no buffers, then the call with owned buffers. The SID is
/// returned as a Vec<u32> so that it is 4-byte aligned, as a SID is.
#[cfg(windows)]
pub(crate) fn windows_account_sid(builtin: &str, name: &str) -> Result<Vec<u32>> {
    use std::ffi::c_void;
    #[link(name = "advapi32")]
    extern "system" {
        fn LookupAccountNameW(
            system: *const u16,
            account: *const u16,
            sid: *mut c_void,
            sid_len: *mut u32,
            domain: *mut u16,
            domain_len: *mut u32,
            kind: *mut i32,
        ) -> i32;
    }
    const ERROR_INSUFFICIENT_BUFFER: i32 = 122;
    const ERROR_NONE_MAPPED: i32 = 1332;
    let account: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
    let mut sid_len: u32 = 0;
    let mut domain_len: u32 = 0;
    let mut kind: i32 = 0;
    // SAFETY: `account` is NUL-terminated. With no buffers the call only
    // reports the sizes it needs, and fails with ERROR_INSUFFICIENT_BUFFER, or
    // ERROR_NONE_MAPPED for an account it does not know.
    unsafe {
        LookupAccountNameW(
            std::ptr::null(),
            account.as_ptr(),
            std::ptr::null_mut(),
            &mut sid_len,
            std::ptr::null_mut(),
            &mut domain_len,
            &mut kind,
        )
    };
    let sizing = std::io::Error::last_os_error();
    match sizing.raw_os_error() {
        Some(ERROR_INSUFFICIENT_BUFFER) => {}
        Some(ERROR_NONE_MAPPED) => return Err(crate::safety::not_found(builtin, "account", name)),
        _ => {
            return Err(crate::safety::bad_state_with_hint(
                builtin,
                &format!("LookupAccountNameW failed: {sizing}"),
                "an account name this machine or its domain knows",
            ))
        }
    }
    let mut sid = vec![0u32; (sid_len as usize).div_ceil(4).max(1)];
    let mut domain = vec![0u16; (domain_len as usize).max(1)];
    let mut domain_cch = domain.len() as u32;
    // SAFETY: the SID buffer holds at least `sid_len` bytes, the domain buffer
    // holds `domain_cch` UTF-16 units, and both lengths are passed by reference.
    let ok = unsafe {
        LookupAccountNameW(
            std::ptr::null(),
            account.as_ptr(),
            sid.as_mut_ptr().cast(),
            &mut sid_len,
            domain.as_mut_ptr(),
            &mut domain_cch,
            &mut kind,
        )
    };
    if ok == 0 {
        return Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!(
                "LookupAccountNameW failed: {}",
                std::io::Error::last_os_error()
            ),
            "an account name this machine or its domain knows",
        ));
    }
    Ok(sid)
}

/// Set the owner (or the primary group) of one file to `sid` through
/// SetNamedSecurityInfoW. Only the requested part of the security descriptor
/// changes; the DACL and SACL are passed as null and left alone.
#[cfg(windows)]
fn windows_set_file_principal(
    builtin: &str,
    path: &str,
    sid: &mut [u32],
    group: bool,
) -> Result<()> {
    use std::ffi::c_void;
    #[link(name = "advapi32")]
    extern "system" {
        fn SetNamedSecurityInfoW(
            object: *mut u16,
            object_type: i32,
            info: u32,
            owner: *mut c_void,
            primary_group: *mut c_void,
            dacl: *mut c_void,
            sacl: *mut c_void,
        ) -> u32;
    }
    const SE_FILE_OBJECT: i32 = 1;
    const OWNER_SECURITY_INFORMATION: u32 = 0x0000_0001;
    const GROUP_SECURITY_INFORMATION: u32 = 0x0000_0002;
    const ERROR_FILE_NOT_FOUND: u32 = 2;
    const ERROR_PATH_NOT_FOUND: u32 = 3;
    const ERROR_ACCESS_DENIED: u32 = 5;
    const ERROR_INVALID_OWNER: u32 = 1307;
    const ERROR_PRIVILEGE_NOT_HELD: u32 = 1314;
    let mut object: Vec<u16> = path.encode_utf16().chain(std::iter::once(0)).collect();
    let (info, owner, primary_group): (u32, *mut c_void, *mut c_void) = if group {
        (
            GROUP_SECURITY_INFORMATION,
            std::ptr::null_mut(),
            sid.as_mut_ptr().cast(),
        )
    } else {
        (
            OWNER_SECURITY_INFORMATION,
            sid.as_mut_ptr().cast(),
            std::ptr::null_mut(),
        )
    };
    // SAFETY: `object` is NUL-terminated and outlives the call; `sid` is a
    // SID the lookup just filled, and exactly one of owner/primary_group is
    // non-null, matching `info`.
    let status = unsafe {
        SetNamedSecurityInfoW(
            object.as_mut_ptr(),
            SE_FILE_OBJECT,
            info,
            owner,
            primary_group,
            std::ptr::null_mut(),
            std::ptr::null_mut(),
        )
    };
    let what = if group { "group" } else { "owner" };
    match status {
        0 => Ok(()),
        ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => {
            Err(crate::safety::not_found(builtin, "file", path))
        }
        ERROR_ACCESS_DENIED | ERROR_PRIVILEGE_NOT_HELD | ERROR_INVALID_OWNER => {
            Err(crate::safety::os_denied(
                builtin,
                format!(
                    "{builtin}: the operating system refused to set the {what} of '{path}' (Win32 error {status})"
                ),
                "setting yourself as owner needs no privilege; setting another account as owner needs SeRestorePrivilege, and any change needs WRITE_OWNER on the file",
            ))
        }
        other => Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!("SetNamedSecurityInfoW failed with Win32 error {other}"),
            "a file this process can name and change",
        )),
    }
}

#[cfg(all(test, windows))]
mod win_chown_tests {
    use super::*;

    /// A temp file with a name this run makes up; the caller removes it.
    fn temp_file(tag: &str) -> String {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let path =
            std::env::temp_dir().join(format!("ae-{tag}-{}-{nanos}.txt", std::process::id()));
        std::fs::write(&path, "x").expect("create temp file");
        path.to_string_lossy().into_owned()
    }

    /// `MACHINE\user`, which LookupAccountNameW resolves on this machine.
    fn current_account() -> String {
        let user = std::env::var("USERNAME").expect("USERNAME is set on Windows");
        match std::env::var("COMPUTERNAME") {
            Ok(machine) if !machine.is_empty() => format!("{machine}\\{user}"),
            _ => user,
        }
    }

    #[test]
    fn fs_chown_sets_the_owner_to_the_current_account() {
        // The workspace jail and the mode are process-wide, and other tests in
        // this binary set them; without the shared lock a jail set elsewhere
        // refuses these temp files.
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let path = temp_file("chown-self");
        let result = bi_fs_chown(
            vec![Value::Str(path.clone()), Value::Str(current_account())],
            None,
        );
        let _ = std::fs::remove_file(&path);
        assert_eq!(
            result.expect("naming yourself as owner needs no privilege"),
            Value::Bool(true)
        );
    }

    #[test]
    fn fs_chown_refuses_a_numeric_owner_as_bad_arg() {
        // The workspace jail and the mode are process-wide, and other tests in
        // this binary set them; without the shared lock a jail set elsewhere
        // refuses these temp files.
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let path = temp_file("chown-num");
        let result = bi_fs_chown(vec![Value::Str(path.clone()), Value::Int(0)], None);
        let _ = std::fs::remove_file(&path);
        let err = result.expect_err("a numeric owner has no Windows meaning");
        assert!(err.to_string().contains("E_BAD_ARG"), "{err}");
    }

    #[test]
    fn fs_chown_reports_an_unknown_account_as_not_found() {
        // The workspace jail and the mode are process-wide, and other tests in
        // this binary set them; without the shared lock a jail set elsewhere
        // refuses these temp files.
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let path = temp_file("chown-unknown");
        let result = bi_fs_chown(
            vec![
                Value::Str(path.clone()),
                Value::Str("ae-no-such-account-zz".to_string()),
            ],
            None,
        );
        let _ = std::fs::remove_file(&path);
        let err = result.expect_err("no such account exists");
        assert!(err.to_string().contains("E_NOT_FOUND"), "{err}");
    }
}

fn bi_fs_link(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.len() != 2 || input.is_some() {
        return Err(crate::safety::arg_err(
            "fs_link requires exactly source and destination paths, without pipeline input",
        ));
    }
    let mut args = args.into_iter();
    let Some(Value::Str(source)) = args.next() else {
        return Err(crate::safety::arg_err("fs_link source must be String"));
    };
    let Some(Value::Str(destination)) = args.next() else {
        return Err(crate::safety::arg_err("fs_link destination must be String"));
    };
    let source = crate::safety::resolve_path_str(&source);
    let destination = crate::safety::resolve_path_str(&destination);
    // A hard link exposes the same underlying file through another writable
    // name. Guard both paths; outside sources can instead be imported by copy.
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "fs_link",
        effect: crate::safety::Effect::WriteLocal,
        what: "create hard link",
        targets: vec![source.clone(), destination.clone()],
        blast_radius: serde_json::json!({"paths":2}),
        reversible: true,
        fs_paths: true,
    })?;
    let metadata = fs::symlink_metadata(&source)
        .map_err(|e| crate::safety::fs_error("fs_link", &source, &e))?;
    if !metadata.is_file() {
        return Err(crate::safety::arg_err(
            "fs_link source must be a regular file, without a symlink",
        ));
    }
    match fs::symlink_metadata(&destination) {
        Ok(_) => {
            return Err(crate::safety::arg_err(
                "fs_link destination must not already exist",
            ))
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(crate::safety::fs_error("fs_link", &destination, &e)),
    }
    crate::tx::snapshot(&destination);
    fs::hard_link(&source, &destination)
        .map_err(|e| crate::safety::fs_error("fs_link", &destination, &e))?;
    Ok(Value::Bool(true))
}

fn bi_fs_symlink(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.len() != 2 || input.is_some() {
        return Err(crate::safety::arg_err(
            "fs_symlink requires exactly target and destination strings, without pipeline input",
        ));
    }
    let mut args = args.into_iter();
    let Some(Value::Str(target)) = args.next() else {
        return Err(crate::safety::arg_err("fs_symlink target must be String"));
    };
    let Some(Value::Str(destination)) = args.next() else {
        return Err(crate::safety::arg_err(
            "fs_symlink destination must be String",
        ));
    };
    if target.is_empty() || destination.is_empty() {
        return Err(crate::safety::arg_err("fs_symlink paths must not be empty"));
    }
    #[cfg(windows)]
    if !std::path::Path::new(&target).is_absolute()
        && (std::path::Path::new(&target).has_root()
            || matches!(
                std::path::Path::new(&target).components().next(),
                Some(std::path::Component::Prefix(_))
            ))
    {
        return Err(crate::safety::arg_err(
            "fs_symlink Windows target must be fully absolute or relative without a drive prefix",
        ));
    }
    let destination = crate::safety::resolve_path_str(&destination);
    // Preserve the stored target: relative links refer to the destination's
    // parent, rather than the process working directory.
    let referred = if std::path::Path::new(&target).is_absolute() {
        std::path::PathBuf::from(&target)
    } else {
        std::path::Path::new(&destination)
            .parent()
            .unwrap_or_else(|| std::path::Path::new("."))
            .join(&target)
    };
    // Canonical existing targets also expose audit artifacts through aliases.
    // Missing targets remain useful dangling links on Unix.
    let referred = match fs::canonicalize(&referred) {
        Ok(path) => path,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => referred,
        Err(e) => return Err(crate::safety::fs_error("fs_symlink", &target, &e)),
    };
    let referred = referred
        .into_os_string()
        .into_string()
        .map_err(|_| crate::safety::arg_err("fs_symlink resolved target must be valid UTF-8"))?;
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "fs_symlink",
        effect: crate::safety::Effect::WriteLocal,
        what: "create symbolic link",
        targets: vec![referred.clone(), destination.clone()],
        blast_radius: serde_json::json!({"paths":2}),
        reversible: false,
        fs_paths: true,
    })?;
    match fs::symlink_metadata(&destination) {
        Ok(_) => {
            return Err(crate::safety::arg_err(
                "fs_symlink destination must not already exist",
            ))
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(crate::safety::fs_error("fs_symlink", &destination, &e)),
    }
    crate::tx::snapshot(&destination);
    #[cfg(unix)]
    std::os::unix::fs::symlink(&target, &destination)
        .map_err(|e| crate::safety::fs_error("fs_symlink", &destination, &e))?;
    #[cfg(windows)]
    {
        // Windows requires a link kind. Refuse a missing target instead of
        // guessing file and creating a broken directory link.
        let metadata = fs::metadata(&referred)
            .map_err(|e| crate::safety::fs_error("fs_symlink", &referred, &e))?;
        let result = if metadata.is_dir() {
            std::os::windows::fs::symlink_dir(&target, &destination)
        } else {
            std::os::windows::fs::symlink_file(&target, &destination)
        };
        result.map_err(|e| crate::safety::fs_error("fs_symlink", &destination, &e))?;
    }
    #[cfg(not(any(unix, windows)))]
    return Err(crate::safety::unimplemented(
        "fs_symlink",
        "symbolic links are unsupported on this platform",
        "use file_copy",
    ));
    #[cfg(any(unix, windows))]
    Ok(Value::Bool(true))
}

fn bi_fs_readlink(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "fs_readlink",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // A missing path and a path that is not a symlink were both null.
    let target =
        std::fs::read_link(&path).map_err(|e| crate::safety::fs_error("fs_readlink", &path, &e))?;
    Ok(Value::Str(target.to_string_lossy().to_string()))
}

/// Whether a `..` in `path` climbs out of a component that does not exist, or
/// is not a directory. Windows resolves `..` lexically before the OS sees the
/// path, so `nope/../a.txt` would canonicalize to `a.txt` even with `nope`
/// absent. Each component a `..` climbs out of must be an existing directory.
fn climbs_through_missing(path: &str) -> bool {
    use std::path::Component;
    let mut so_far = std::path::PathBuf::new();
    for component in std::path::Path::new(path).components() {
        match component {
            // Out of the working directory itself: that exists.
            Component::ParentDir if so_far.as_os_str().is_empty() => {}
            Component::ParentDir => {
                if !so_far.is_dir() {
                    return true;
                }
                so_far.pop();
            }
            Component::CurDir => {}
            other => so_far.push(other.as_os_str()),
        }
    }
    false
}

fn bi_fs_realpath(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "fs_realpath",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // Only a missing path is Null; the old code made every failure Null.
    if climbs_through_missing(&path) {
        return Ok(Value::Null);
    }
    match std::fs::canonicalize(&path) {
        Ok(real) => Ok(Value::Str(
            crate::safety::strip_verbatim_prefix(&real)
                .to_string_lossy()
                .to_string(),
        )),
        Err(e) if path_is_absent(&e) => Ok(Value::Null),
        Err(e) => Err(crate::safety::fs_error("fs_realpath", &path, &e)),
    }
}

/// Where fs_tempfile and fs_tempdir create things: the system temp directory,
/// except in agent mode, where it is `<workspace>/.ironshell/tmp/` so that
/// nothing is created outside the workspace.
fn temp_parent(builtin: &str) -> Result<std::path::PathBuf> {
    if crate::safety::current_mode() != crate::safety::Mode::Agent {
        return Ok(std::env::temp_dir());
    }
    let dir = crate::safety::workspace_root()
        .join(".ironshell")
        .join("tmp");
    std::fs::create_dir_all(&dir).map_err(|e| crate::safety::fs_error(builtin, &dir, &e))?;
    Ok(dir)
}

fn bi_fs_tempfile(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let prefix = args
        .first()
        .map(|v| expect_string("fs_tempfile", v))
        .transpose()?
        .unwrap_or("ironshell_");

    if prefix.contains(['/', '\\', ':']) {
        return Err(crate::safety::arg_err(
            "fs_tempfile: prefix must not contain path separators",
        ));
    }

    let temp_dir = temp_parent("fs_tempfile")?;
    let filename = format!("{}_{}", prefix, uuid::Uuid::new_v4());
    let path = temp_dir.join(&filename);

    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
        .map_err(|e| crate::safety::fs_error("fs_tempfile", &path, &e))?;
    Ok(Value::Str(path.to_string_lossy().to_string()))
}

fn bi_fs_tempdir(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let prefix = args
        .first()
        .map(|v| expect_string("fs_tempdir", v))
        .transpose()?
        .unwrap_or("ironshell_");

    if prefix.contains(['/', '\\', ':']) {
        return Err(crate::safety::arg_err(
            "fs_tempdir: prefix must not contain path separators",
        ));
    }

    let temp_dir = temp_parent("fs_tempdir")?;
    let dirname = format!("{}_{}", prefix, uuid::Uuid::new_v4());
    let path = temp_dir.join(&dirname);

    // A failure was null, which reads as "no directory" rather than "could not".
    std::fs::create_dir(&path).map_err(|e| crate::safety::fs_error("fs_tempdir", &path, &e))?;
    Ok(Value::Str(path.to_string_lossy().to_string()))
}

#[path = "fs_watch.rs"]
mod fs_watch;
fn bi_fs_watch(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    fs_watch::watch(args, input)
}

fn bi_fs_unwatch(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    fs_watch::unwatch(args, input)
}

/// The directory a glob's literal prefix names: everything before the first
/// component with a metacharacter. Empty means the working directory.
fn glob_literal_dir(pattern: &str) -> String {
    let mut parts = Vec::new();
    for c in pattern.split('/') {
        if crate::posix::has_glob_meta(c) {
            break;
        }
        parts.push(c);
    }
    if parts.len() == pattern.split('/').count() {
        // No metacharacter at all: the pattern is a path; its parent must exist.
        parts.pop();
    }
    let dir = parts.join("/");
    if dir.is_empty() && pattern.starts_with('/') {
        "/".to_string()
    } else {
        dir
    }
}

/// `pattern` with each letter in its wildcard components matched in either case:
/// `*.txt` becomes `*.[tT][xX][tT]`. Only components with a wildcard are changed,
/// so a literal directory prefix is still checked as the path it names, and the
/// letters inside a `[...]` class are left alone.
#[cfg(windows)]
fn fold_glob_case(pattern: &str) -> String {
    pattern
        .split('/')
        .map(|component| {
            if !crate::posix::has_glob_meta(component) {
                return component.to_string();
            }
            let mut out = String::with_capacity(component.len() * 4);
            let mut in_class = false;
            for ch in component.chars() {
                if in_class {
                    in_class = ch != ']';
                    out.push(ch);
                } else if ch == '[' {
                    in_class = true;
                    out.push(ch);
                } else if ch.is_ascii_alphabetic() {
                    out.push('[');
                    out.push(ch.to_ascii_lowercase());
                    out.push(ch.to_ascii_uppercase());
                    out.push(']');
                } else {
                    out.push(ch);
                }
            }
            out
        })
        .collect::<Vec<_>>()
        .join("/")
}

/// Expand a glob for a typed builtin: `**` is recursive, results sort by
/// bytes, and a literal directory prefix that does not exist is E_NOT_FOUND
/// rather than an empty answer that reads like "no files".
fn expand_glob_for(builtin: &str, pattern: &str) -> Result<Vec<String>> {
    crate::security::check_share_egress(builtin, pattern)?;
    // Windows callers may write either separator; globbing is done on `/`.
    let pattern = pattern.replace(char::from(92), "/");
    // NTFS names are case-insensitive, so `*.TXT` finds `a.txt`.
    #[cfg(windows)]
    let pattern = fold_glob_case(&pattern);
    let dir = glob_literal_dir(&pattern);
    // The jail judges the directory the pattern walks before anything is listed,
    // so `glob("../*")` is refused whether or not that directory exists.
    crate::security::check_read_jail(builtin, if dir.is_empty() { "." } else { &dir })?;
    if !dir.is_empty() && !std::path::Path::new(&dir).is_dir() {
        return Err(crate::safety::not_found(builtin, "directory", &dir));
    }
    // The cap is applied while gathering, so an over-large glob stops early
    // and is refused, not built in full and counted afterwards.
    let (paths, over) = crate::posix::glob_paths_capped(&pattern, WALK_MAX_ENTRIES);
    if over {
        return Err(walk_over(builtin, WALK_MAX_ENTRIES));
    }
    // A match that resolves outside the workspace (through a link, say) is not
    // returned.
    Ok(paths
        .into_iter()
        .filter(|p| !crate::security::outside_read_jail(p))
        .collect())
}

fn bi_fs_glob(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // This matched `*.rs` against any name *containing* ".rs" -- `main.rsx`
    // and `x.rs.bak` included -- had no `**`, returned directory order, and
    // answered [] for a directory that does not exist. `glob("src/**/*.rs")`
    // said 0.
    let pattern = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "fs_glob",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    Ok(Value::Array(
        expand_glob_for("glob", &pattern)?
            .into_iter()
            .map(Value::Str)
            .collect(),
    ))
}

/// lines(text): split text into lines, without their terminators; a final
/// newline does not add an empty line, and a CR before LF is dropped.
fn bi_lines(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let text = match (input, args.first()) {
        (Some(Value::Str(s)), _) => s,
        (None, Some(Value::Str(s))) => s.clone(),
        (Some(other), _) => {
            return Err(crate::safety::bad_arg("lines", "String", other.type_name()))
        }
        (None, Some(other)) => {
            return Err(crate::safety::bad_arg("lines", "String", other.type_name()))
        }
        (None, None) => return Err(crate::safety::bad_arg("lines", "String", "nothing")),
    };
    let cr = char::from(13);
    let nl = char::from(10);
    let mut out: Vec<Value> = text
        .split(nl)
        .map(|l| Value::Str(l.strip_suffix(cr).unwrap_or(l).to_string()))
        .collect();
    if text.is_empty() || text.ends_with(nl) {
        out.pop();
    }
    Ok(Value::Array(out))
}

/// open(path): read a file and parse it by its extension -- .json, .jsonl,
/// .toml, .yaml/.yml, .csv -- or return its text. Borrowed from nushell,
/// where `open Cargo.toml | get package.version` is the whole task.
/// The line and column (both from 1) of a byte offset in a text.
fn line_column(text: &str, byte: usize) -> (usize, usize) {
    let before = text.get(..byte).unwrap_or(text);
    let line = before.matches('\n').count() + 1;
    let column = before.rsplit('\n').next().map_or(0, |s| s.chars().count()) + 1;
    (line, column)
}

/// The first integer line of a TOML text whose value is past the 64-bit range.
/// Returns its line (from 1) and its literal.
fn oversized_toml_integer(text: &str) -> Option<(usize, String)> {
    for (index, line) in text.lines().enumerate() {
        let Some((_, value)) = line.split_once('=') else {
            continue;
        };
        let token = value
            .trim()
            .split(|c: char| c.is_whitespace() || c == '#')
            .next()
            .unwrap_or("");
        let unsigned = token.trim_start_matches(['+', '-']);
        let integer_shaped = unsigned.starts_with(|c: char| c.is_ascii_digit())
            && unsigned.chars().all(|c| c.is_ascii_digit() || c == '_');
        if integer_shaped && token.replace('_', "").parse::<i64>().is_err() {
            return Some((index + 1, token.to_string()));
        }
    }
    None
}

/// Why a TOML text will not read, as a refusal gives it. For an integer past 64
/// bits the parser says only "number too large to fit in target type", which
/// names no value, so the literal and its line are given instead. Some errors
/// come with no message (`a = ` is one): the reason for those is named here.
fn toml_reason(text: &str, err: &toml::de::Error) -> String {
    if err.message().contains("too large") {
        if let Some((line, literal)) = oversized_toml_integer(text) {
            return format!("the integer {literal} at line {line} is out of the 64-bit Int range");
        }
    }
    let message = err.message().trim();
    if !message.is_empty() {
        return message.to_string();
    }
    match text
        .lines()
        .enumerate()
        .find(|(_, line)| line.trim_end().ends_with('='))
    {
        Some((index, _)) => format!("a value is missing after '=' on line {}", index + 1),
        None => "the text ends before a complete TOML value".to_string(),
    }
}

/// The hint for a TOML text that will not read. An integer past the 64-bit
/// range is named as such, since the parser's own message does not say which
/// value it is; otherwise the hint gives the line and column of the error.
fn toml_failure_hint(text: &str, err: &toml::de::Error) -> String {
    if let Some((line, literal)) = oversized_toml_integer(text) {
        return format!(
            "the integer {literal} at line {line} is out of the 64-bit range (-9223372036854775808 to 9223372036854775807); write it as a float or a string"
        );
    }
    match err.span() {
        Some(span) => {
            let (line, column) = line_column(text, span.start);
            format!(
                "fix the TOML at line {line}, column {column}: {}",
                toml_reason(text, err)
            )
        }
        None => format!("fix the TOML: {}", toml_reason(text, err)),
    }
}

/// The refusal for a data file that will not parse. The file is the input, so
/// the same call fails again until the file changes: not retryable. It is the
/// E_BAD_VALUE that from_toml gives for the same text, not E_BAD_ARG.
fn unparsed_data(path: &str, kind: &str, message: &str, hint: String) -> anyhow::Error {
    crate::safety::value_not_representable(
        "open",
        format!("open: {path} is not valid {kind}: {message}"),
        &hint,
    )
}

/// A serde_json error's message without its position, which the hint states
/// as a line and a column.
fn json_message(e: &serde_json::Error) -> String {
    let text = e.to_string();
    text.split(" at line ")
        .next()
        .unwrap_or_default()
        .to_string()
}

/// The detail and the hint for JSON text that will not read. serde_json's
/// recursion limit (128 levels of nesting) is not a position in the text: a
/// document that nests deeper is well formed, so it is named as such, and the
/// hint says what to do about it.
fn json_failure(e: &serde_json::Error, text: &str) -> (String, String) {
    if e.to_string().starts_with("recursion limit exceeded") {
        return (
            "JSON nested deeper than 128 levels is not read".to_string(),
            "flatten the document, or read it as text".to_string(),
        );
    }
    let hint = format!(
        "fix the JSON at line {}, column {}: {}",
        e.line(),
        e.column(),
        json_message(e)
    );
    // serde's "unexpected end of hex escape" is the only word for a surrogate
    // escape that does not pair up; name the escape instead.
    let message = e.to_string();
    if message.contains("hex escape") || message.contains("unicode code point") {
        if let Some(escape) = lone_surrogate_escape(text) {
            return (
                format!(
                    "a lone UTF-16 surrogate {escape} is not a character; write the pair (\\uD83D\\uDE00) or \\u{{1F600}}"
                ),
                hint,
            );
        }
    }
    (message, hint)
}

/// The first `\uD800`-`\uDFFF` escape in `text` that does not pair up into a
/// character (a high surrogate with no low one right after it, or a low one
/// with no high one before it), as written in the text. None if all pair.
fn lone_surrogate_escape(text: &str) -> Option<&str> {
    let bytes = text.as_bytes();
    let unit_at = |i: usize| -> Option<u32> {
        if bytes.get(i) != Some(&b'\\') || bytes.get(i + 1) != Some(&b'u') {
            return None;
        }
        let hex = text.get(i + 2..i + 6)?;
        if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            return None;
        }
        u32::from_str_radix(hex, 16).ok()
    };
    let mut i = 0;
    while i < bytes.len() {
        // An escaped backslash (`\\`) is two bytes and never starts an escape.
        if bytes[i] == b'\\' && bytes.get(i + 1) == Some(&b'\\') {
            i += 2;
            continue;
        }
        match unit_at(i) {
            Some(unit) if (0xD800..=0xDBFF).contains(&unit) => match unit_at(i + 6) {
                Some(low) if (0xDC00..=0xDFFF).contains(&low) => i += 12,
                _ => return text.get(i..i + 6),
            },
            Some(unit) if (0xDC00..=0xDFFF).contains(&unit) => return text.get(i..i + 6),
            Some(_) => i += 6,
            None => i += 1,
        }
    }
    None
}

fn bi_open(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "open",
                "path: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    if !std::path::Path::new(&path).is_file() {
        // A directory exists but is not a file: named as one, not as missing.
        if !crate::safety::names_a_remote_share(&path) && std::path::Path::new(&path).is_dir() {
            return Err(crate::safety::bad_arg_in(
                "open",
                format!("open: `{path}` is a directory, not a file"),
                &format!(
                    "pass a file; to read a directory's files, name them with a glob such as '{path}/**/*'"
                ),
            ));
        }
        return Err(crate::safety::not_found("open", "file", &path));
    }
    let validated = validate_read_path(&path)?;
    let md =
        fs::metadata(&validated).map_err(|e| crate::safety::fs_error("open", &validated, &e))?;
    check_file_size_limit(md.len()).context("open: file too large")?;
    let bytes =
        fs::read(&validated).map_err(|e| crate::safety::fs_error("open", &validated, &e))?;
    let text = decode_text("open", &validated, bytes).map(without_bom)?;
    let ext = std::path::Path::new(&path)
        .extension()
        .map(|e| e.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default();
    match ext.as_str() {
        "json" => {
            let j: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
                let (detail, hint) = json_failure(&e, &text);
                unparsed_data(&path, "JSON", &detail, hint)
            })?;
            if let Some(refusal) = wide_integer_refusal("open", &text) {
                return Err(refusal);
            }
            Ok(Value::from_json(&with_integer_negative_zeros(j, &text)))
        }
        "jsonl" | "ndjson" => {
            let mut rows = Vec::new();
            // The line is the file's, counting blank lines, and the column is within
            // that line: serde_json's own position is of the record alone.
            for (index, line) in text.lines().enumerate() {
                if line.trim().is_empty() {
                    continue;
                }
                let j: serde_json::Value = serde_json::from_str(line).map_err(|e| {
                    let (number, column) = (index + 1, e.column());
                    unparsed_data(
                        &path,
                        "JSON lines",
                        &format!("line {number}, column {column}: {}", json_message(&e)),
                        format!(
                            "fix the JSON at line {number}, column {column}: {}",
                            json_message(&e)
                        ),
                    )
                })?;
                if let Some(refusal) = wide_integer_refusal("open", line) {
                    return Err(refusal);
                }
                rows.push(Value::from_json(&with_integer_negative_zeros(j, line)));
            }
            Ok(Value::Array(rows))
        }
        "toml" => {
            let t: toml::Value = toml::from_str(&text).map_err(|e| {
                unparsed_data(
                    &path,
                    "TOML",
                    &toml_reason(&text, &e),
                    toml_failure_hint(&text, &e),
                )
            })?;
            if let Some(refusal) = toml_nonfinite_refusal("open", &t) {
                return Err(refusal);
            }
            Ok(crate::plugins::toml_to_value(t))
        }
        "yaml" | "yml" => crate::yaml::parse(&text).map_err(|e| {
            // A refusal the parser coded (an integer past 64 bits, a non-finite
            // number) is already structured: re-raise it under `open` with its
            // own hint, not stringified into another error's message.
            if let Some(se) = e.downcast_ref::<crate::safety::SafetyError>() {
                let detail = se
                    .message
                    .strip_prefix("from_yaml: ")
                    .unwrap_or(&se.message);
                return crate::safety::value_not_representable(
                    "open",
                    format!("open: {path}: {detail}"),
                    &se.hint,
                );
            }
            // The YAML parser's messages already start with `line N:`.
            unparsed_data(
                &path,
                "YAML",
                &e.to_string(),
                format!("fix the YAML at {e}"),
            )
        }),
        "csv" => bi_from_csv(vec![], Some(Value::Str(text))),
        // Tab-separated: the same header row and type inference as CSV.
        "tsv" => parse_delimited(
            "open",
            &text,
            csv::ReaderBuilder::new().delimiter(b'\t').quoting(false),
        ),
        _ => Ok(Value::Str(text)),
    }
}

/// Whether `path` is a directory. `is_dir()` answers false when it cannot
/// stat the entry, so a directory it could not read looked like a file and
/// was skipped. A dangling symlink, or an entry removed since it was listed,
/// is `false`; any other failure to stat it is an error.
fn entry_is_dir(builtin: &str, path: &std::path::Path) -> Result<bool> {
    match std::fs::metadata(path) {
        Ok(meta) => Ok(meta.is_dir()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(crate::safety::fs_error(builtin, path, &e)),
    }
}

/// Whether a failed stat means the path does not exist. A component that is a
/// regular file (`plain/x`) is ENOTDIR, which `test -e` also reads as absent.
fn path_is_absent(e: &std::io::Error) -> bool {
    matches!(
        e.kind(),
        std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
    )
}

/// Whether `path` is a regular file. Same rule as `entry_is_dir`: only a
/// missing entry answers `false`; any other failure to stat it is an error.
fn entry_is_file(builtin: &str, path: &std::path::Path) -> Result<bool> {
    match std::fs::metadata(path) {
        Ok(meta) => Ok(meta.is_file()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(crate::safety::fs_error(builtin, path, &e)),
    }
}

/// Reads a project text file. `Ok(None)` only when the file does not exist;
/// any other failure is an error, and so is a file over the read limit.
/// Non-UTF-8 bytes are replaced rather than treated as absence, so a Latin-1
/// README still returns its text.
fn read_text_lossy(builtin: &str, path: &std::path::Path) -> Result<Option<String>> {
    // The capped reader codes its errors, so the io kind is gone by the time
    // it fails; a path under a regular file (NotADirectory) is absent, as
    // `path_is_absent` says, and is told apart here first.
    if let Err(e) = std::fs::metadata(path) {
        if path_is_absent(&e) {
            return Ok(None);
        }
    }
    match read_bytes_capped(builtin, path) {
        Ok(bytes) => Ok(Some(String::from_utf8_lossy(&bytes).into_owned())),
        Err(e) if capped_read_not_found(&e) => Ok(None),
        Err(e) => Err(e),
    }
}

/// The first of `names` that exists in the working directory, as text, or
/// Null when none of them exists.
fn first_project_text(builtin: &str, names: &[&str]) -> Result<Value> {
    for name in names {
        if let Some(text) = read_text_lossy(builtin, std::path::Path::new(name))? {
            return Ok(Value::Str(text));
        }
    }
    Ok(Value::Null)
}

/// The entries under `dir` down to `max_depth`, depth first, refused past `max`.
///
/// A directory that cannot be listed is an error, not an empty subtree. The
/// walk used to skip it, and an unreadable root returned []: a shorter listing
/// that looked complete.
fn walk_entries_capped(dir: &std::path::Path, max_depth: usize, max: usize) -> Result<Vec<Value>> {
    fn walk_recursive(
        dir: &std::path::Path,
        depth: usize,
        max_depth: usize,
        max: usize,
        results: &mut Vec<Value>,
    ) -> Result<()> {
        if depth > max_depth {
            return Ok(());
        }
        let entries =
            std::fs::read_dir(dir).map_err(|e| crate::safety::fs_error("fs_walk", dir, &e))?;
        for entry in entries {
            let entry = entry.map_err(|e| crate::safety::fs_error("fs_walk", dir, &e))?;
            let path = entry.path();
            let shown = Value::Str(path.to_string_lossy().to_string());
            push_capped("fs_walk", results, shown, max)?;
            // Only a directory the walk would descend into needs its type
            // checked; one at the depth limit is listed and not opened.
            if depth < max_depth && entry_is_dir("fs_walk", &path)? {
                walk_recursive(&path, depth + 1, max_depth, max, results)?;
            }
        }
        Ok(())
    }

    let mut results = Vec::new();
    walk_recursive(dir, 0, max_depth, max, &mut results)?;
    Ok(results)
}

fn bi_fs_walk(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let dir = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => ".".to_string(),
    };
    let max_depth = args
        .get(1)
        .and_then(|v| match v {
            Value::Int(d) => Some(*d as usize),
            _ => None,
        })
        .unwrap_or(100);

    let results = walk_entries_capped(std::path::Path::new(&dir), max_depth, WALK_MAX_ENTRIES)?;
    Ok(Value::Array(results))
}

fn bi_fs_tree(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let dir = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => ".".to_string(),
    };
    let max_depth = args
        .get(1)
        .and_then(|v| match v {
            Value::Int(d) => Some(*d as usize),
            _ => None,
        })
        .unwrap_or(3);

    // An unreadable directory used to render as a leaf, and an entry that
    // could not be read was left out of its parent's listing. Both are
    // errors now: the tree would be a shorter one presented as the whole.
    fn tree_recursive(
        dir: &std::path::Path,
        prefix: &str,
        depth: usize,
        max_depth: usize,
        max: usize,
        lines: &mut Vec<String>,
    ) -> Result<()> {
        if depth > max_depth {
            return Ok(());
        }
        let entries: Vec<_> = std::fs::read_dir(dir)
            .map_err(|e| crate::safety::fs_error("fs_tree", dir, &e))?
            .collect::<std::io::Result<Vec<_>>>()
            .map_err(|e| crate::safety::fs_error("fs_tree", dir, &e))?;
        let count = entries.len();
        for (i, entry) in entries.into_iter().enumerate() {
            let is_last = i == count - 1;
            let connector = if is_last { "└── " } else { "├── " };
            let name = entry.file_name().to_string_lossy().to_string();
            // `lines` starts with the root's own line, so the nodes so far are one fewer.
            check_walk_room("fs_tree", lines.len() - 1, max)?;
            lines.push(format!("{}{}{}", prefix, connector, name));

            let path = entry.path();
            if depth < max_depth && entry_is_dir("fs_tree", &path)? {
                let new_prefix = format!("{}{}", prefix, if is_last { "    " } else { "│   " });
                tree_recursive(&path, &new_prefix, depth + 1, max_depth, max, lines)?;
            }
        }
        Ok(())
    }

    let mut lines = vec![dir.clone()];
    tree_recursive(
        std::path::Path::new(&dir),
        "",
        0,
        max_depth,
        WALK_MAX_ENTRIES,
        &mut lines,
    )?;
    Ok(Value::Str(lines.join("\n")))
}

fn bi_fs_du(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => ".".to_string(),
    };

    crate::security::check_read_jail("fs_du", &path)?;
    // A total that leaves out an entry it could not stat or list is wrong, so
    // those are errors. The old code counted such an entry as 0 bytes, and an
    // unreadable or missing root as an empty directory.
    fn dir_size(path: &std::path::Path) -> Result<u64> {
        let meta =
            std::fs::metadata(path).map_err(|e| crate::safety::fs_error("fs_du", path, &e))?;
        if meta.is_file() {
            return Ok(meta.len());
        }
        let mut size = 0;
        let entries =
            std::fs::read_dir(path).map_err(|e| crate::safety::fs_error("fs_du", path, &e))?;
        for entry in entries {
            let entry_path = entry
                .map_err(|e| crate::safety::fs_error("fs_du", path, &e))?
                .path();
            match std::fs::metadata(&entry_path) {
                Ok(m) if m.is_file() => size += m.len(),
                Ok(m) if m.is_dir() => size += dir_size(&entry_path)?,
                Ok(_) => {}
                // A dangling symlink, or an entry removed since it was listed.
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(crate::safety::fs_error("fs_du", &entry_path, &e)),
            }
        }
        Ok(size)
    }

    let size = dir_size(std::path::Path::new(&path))?;
    let mut rec = std::collections::BTreeMap::new();
    rec.insert("path".to_string(), Value::Str(path));
    rec.insert("bytes".to_string(), Value::Int(size as i64));
    rec.insert("kb".to_string(), Value::Float(size as f64 / 1024.0));
    rec.insert(
        "mb".to_string(),
        Value::Float(size as f64 / 1024.0 / 1024.0),
    );
    rec.insert(
        "gb".to_string(),
        Value::Float(size as f64 / 1024.0 / 1024.0 / 1024.0),
    );
    Ok(Value::Record(rec))
}

fn bi_fs_df(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // This was `Get-PSDrive -PSProvider FileSystem | Select-Object Name,Used,Free`
    // through PowerShell. It now reads the same drives from kernel32 (fixed,
    // removable, network and RAM-disk roots). `size` is the true total from
    // GetDiskFreeSpaceExW; it was used + free before, which is the same number.
    // `used` is total minus free, and `available` is the free figure. A drive
    // whose sizes cannot be read keeps `filesystem` and `mounted_on`, and the
    // size fields are left out.
    #[cfg(target_os = "windows")]
    {
        let mut drives = Vec::new();
        for v in windows_volumes("fs_df")?
            .into_iter()
            .filter(|v| windows_listed_by_powershell(v.drive_type))
        {
            let mut rec = std::collections::BTreeMap::new();
            rec.insert(
                "filesystem".to_string(),
                Value::Str(format!("{}:\\", v.letter)),
            );
            if let (Some(total), Some(free)) = (v.total, v.free) {
                let used = total.saturating_sub(free);
                let use_pct = if total > 0 {
                    (used as f64 / total as f64 * 100.0) as i64
                } else {
                    0
                };
                rec.insert("size".to_string(), Value::Str(format_bytes(total as i64)));
                rec.insert("used".to_string(), Value::Str(format_bytes(used as i64)));
                rec.insert(
                    "available".to_string(),
                    Value::Str(format_bytes(free as i64)),
                );
                rec.insert(
                    "use_percent".to_string(),
                    Value::Str(format!("{}%", use_pct)),
                );
            }
            rec.insert(
                "mounted_on".to_string(),
                Value::Str(format!("{}:\\", v.letter)),
            );
            drives.push(Value::Record(rec));
        }
        return Ok(Value::Array(drives));
    }
    #[cfg(not(target_os = "windows"))]
    {
        // df -h works on both Linux and macOS
        let mut cmd = crate::safety::child_command("df");
        cmd.args(["-h"]);
        let output = bounded_cmd_output("fs_df", "df", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            let mut drives = Vec::new();
            for line in text.lines().skip(1) {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 6 {
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("filesystem".to_string(), Value::Str(parts[0].to_string()));
                    rec.insert("size".to_string(), Value::Str(parts[1].to_string()));
                    rec.insert("used".to_string(), Value::Str(parts[2].to_string()));
                    rec.insert("available".to_string(), Value::Str(parts[3].to_string()));
                    rec.insert("use_percent".to_string(), Value::Str(parts[4].to_string()));
                    rec.insert("mounted_on".to_string(), Value::Str(parts[5].to_string()));
                    drives.push(Value::Record(rec));
                }
            }
            return Ok(Value::Array(drives));
        }
    }
    #[cfg(not(target_os = "windows"))]
    {
        Ok(Value::Array(vec![]))
    }
}

fn bi_fs_mount(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    acl_mount::fs_mount(args, input)
}

fn bi_fs_unmount(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    acl_mount::fs_unmount(args, input)
}

fn bi_fs_mounts(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // This was `Get-PSDrive -PSProvider FileSystem | Select-Object Name,Root`
    // through PowerShell, with fstype hardcoded to "NTFS". It now lists the
    // same drives as fs_df (fixed, removable, network and RAM-disk roots) from
    // kernel32. `fstype` is the volume's real file system name from
    // GetVolumeInformationW, and it is left out when that call fails or the
    // volume has no name.
    #[cfg(target_os = "windows")]
    {
        let mut result = Vec::new();
        for v in windows_volumes("fs_mounts")?
            .into_iter()
            .filter(|v| windows_listed_by_powershell(v.drive_type))
        {
            let mut rec = std::collections::BTreeMap::new();
            rec.insert("device".to_string(), Value::Str(format!("{}:", v.letter)));
            rec.insert(
                "mountpoint".to_string(),
                Value::Str(format!("{}:\\", v.letter)),
            );
            if let Some(fs) = v.fs_name.filter(|s| !s.is_empty()) {
                rec.insert("fstype".to_string(), Value::Str(fs));
            }
            rec.insert("options".to_string(), Value::Str("rw".to_string()));
            result.push(Value::Record(rec));
        }
        return Ok(Value::Array(result));
    }
    #[cfg(target_os = "linux")]
    {
        if let Ok(mounts) = std::fs::read_to_string("/proc/mounts") {
            let mut result = Vec::new();
            for line in mounts.lines() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 4 {
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("device".to_string(), Value::Str(parts[0].to_string()));
                    rec.insert("mountpoint".to_string(), Value::Str(parts[1].to_string()));
                    rec.insert("fstype".to_string(), Value::Str(parts[2].to_string()));
                    rec.insert("options".to_string(), Value::Str(parts[3].to_string()));
                    result.push(Value::Record(rec));
                }
            }
            return Ok(Value::Array(result));
        }
    }
    #[cfg(target_os = "macos")]
    {
        // macOS: use mount command (no /proc/mounts)
        let cmd = crate::safety::child_command("mount");
        let output = bounded_cmd_output("fs_mounts", "mount", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            let mut result = Vec::new();
            for line in text.lines() {
                // Format: /dev/disk1s1 on / (apfs, local, journaled)
                if let Some((device_part, rest)) = line.split_once(" on ") {
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("device".to_string(), Value::Str(device_part.to_string()));
                    if let Some((mountpoint, opts)) = rest.split_once(" (") {
                        rec.insert("mountpoint".to_string(), Value::Str(mountpoint.to_string()));
                        let opts_clean = opts.trim_end_matches(')');
                        let parts: Vec<&str> = opts_clean.split(", ").collect();
                        rec.insert(
                            "fstype".to_string(),
                            Value::Str(parts.first().unwrap_or(&"").to_string()),
                        );
                        rec.insert("options".to_string(), Value::Str(parts[1..].join(",")));
                    } else {
                        rec.insert("mountpoint".to_string(), Value::Str(rest.to_string()));
                        rec.insert("fstype".to_string(), Value::Str("unknown".to_string()));
                        rec.insert("options".to_string(), Value::Str(String::new()));
                    }
                    result.push(Value::Record(rec));
                }
            }
            return Ok(Value::Array(result));
        }
    }
    // A failed query answered [], "nothing mounted".
    #[cfg(not(target_os = "windows"))]
    {
        Err(crate::safety::tool_failed(
            "fs_mounts",
            "the mount table",
            None,
            "it could not be read",
        ))
    }
}

// ============================================================================
// 270-289: Network Operations
//
// Every builtin here reads a host tool or the kernel's tables and answers with
// a typed value, or refuses with a code. Nothing runs through a shell: each
// tool gets an argument vector, and every host argument is checked to be a
// hostname or address literal that cannot be read as an option.
// ============================================================================

/// Records one net_* table may return. A longer table is refused, not cut.
const NET_MAX_RECORDS: usize = 4096;
/// Bytes of whois text kept in `raw`; a longer answer is cut and flagged in
/// `raw_truncated`, because the fields it was parsed for are near the top.
const WHOIS_RAW_MAX: usize = 64 * 1024;
/// Bytes of `netstat -s` text returned; a longer answer is refused.
const NET_STATS_MAX: usize = 1024 * 1024;
/// Ports one net_scan call may probe.
const NET_SCAN_MAX_PORTS: i64 = 1024;
/// Wall-clock bound on one whole net_scan call.
const NET_SCAN_DEADLINE_SECS: u64 = 30;
/// Bound on any single host-tool run that is not otherwise sized.
const NET_TOOL_SECS: u64 = 30;

type NetRecord = BTreeMap<String, Value>;

/// An Int argument at `idx`: `default` when absent (and given), otherwise
/// required. Anything outside `lo..=hi` is refused, never clamped.
fn net_int(
    name: &str,
    args: &[Value],
    idx: usize,
    default: Option<i64>,
    lo: i64,
    hi: i64,
) -> Result<i64> {
    let n = match args.get(idx) {
        None => match default {
            Some(d) => return Ok(d),
            None => {
                return Err(crate::safety::bad_arg(
                    name,
                    "a required Int argument",
                    "nothing",
                ))
            }
        },
        Some(Value::Int(n)) => *n,
        Some(other) => return Err(crate::safety::bad_arg(name, "an Int", other.type_name())),
    };
    if !(lo..=hi).contains(&n) {
        return Err(crate::safety::bad_arg(
            name,
            &format!("an Int in {lo}..={hi}"),
            &n.to_string(),
        ));
    }
    Ok(n)
}

/// A hostname or IP address argument at `idx`. Option-like text (a leading
/// `-` or `+`) is refused before anything else, and the rest must pass the
/// hostname validator, so no host can reach a tool as a flag.
fn net_host(name: &str, args: &[Value], idx: usize) -> Result<String> {
    let Some(value) = args.get(idx) else {
        return Err(crate::safety::bad_arg(
            name,
            "a hostname or IP address String",
            "nothing",
        ));
    };
    let Value::Str(host) = value else {
        return Err(crate::safety::bad_arg(
            name,
            "a hostname or IP address String",
            value.type_name(),
        ));
    };
    crate::safety::reject_option_like(name, std::slice::from_ref(host))?;
    validate_hostname_or_ip(host).map_err(|e| {
        crate::safety::bad_arg(name, "a hostname or IP address", &format!("{host}: {e}"))
    })
}

/// An IPv4 or IPv6 literal argument at `idx`. Names are not accepted here, so
/// a reverse lookup cannot be asked for a host it was not given an address for.
fn net_ip_literal(name: &str, args: &[Value], idx: usize) -> Result<std::net::IpAddr> {
    let Some(value) = args.get(idx) else {
        return Err(crate::safety::bad_arg(
            name,
            "an IPv4 or IPv6 address String",
            "nothing",
        ));
    };
    let Value::Str(text) = value else {
        return Err(crate::safety::bad_arg(
            name,
            "an IPv4 or IPv6 address String",
            value.type_name(),
        ));
    };
    text.parse::<std::net::IpAddr>()
        .map_err(|_| crate::safety::bad_arg(name, "an IPv4 or IPv6 address literal", text))
}

/// Refuse a call inside a transaction when the files it writes cannot be named
/// before it runs (an archive's members, say), so the journal cannot snapshot
/// them. The refusal is coded the same way as the scheduler's and the network
/// builtins', so an agent sees why, not a silent unrolled change.
fn refuse_in_transaction(builtin: &str, why: &str) -> Result<()> {
    if crate::tx::is_active() {
        return Err(crate::safety::unimplemented(
            builtin,
            why,
            "finish the transaction first",
        ));
    }
    Ok(())
}

/// Refuse a network-effect call inside a transaction, which cannot roll back
/// traffic that has already left the machine.
fn net_refuse_in_transaction(name: &str) -> Result<()> {
    if crate::tx::is_active() {
        return Err(crate::safety::unimplemented(
            name,
            "network traffic cannot be rolled back",
            "finish the transaction first",
        ));
    }
    Ok(())
}

/// Run a host tool with an argument vector (never through a shell) under a
/// wall-clock bound. A missing tool is E_TOOL_MISSING; no answer in time is a
/// coded budget stop.
fn net_run(name: &str, tool: &str, argv: &[&str], secs: u64) -> Result<std::process::Output> {
    let mut cmd = crate::safety::child_command(tool);
    cmd.args(argv);
    crate::safety::output_with_timeout(cmd, secs).map_err(|e| {
        if e.kind() == std::io::ErrorKind::TimedOut {
            crate::safety::budget_exceeded(
                name,
                format!("`{tool}` gave no result within {secs} s"),
                "retry with less work, or check the host",
            )
        } else {
            crate::safety::spawn_error(name, tool, &e)
        }
    })
}

fn tail_chars(text: &str, n: usize) -> String {
    let count = text.chars().count();
    if count <= n {
        text.to_string()
    } else {
        text.chars().skip(count - n).collect()
    }
}

/// What a failed tool said: its stderr, or else its last non-empty stdout line.
fn net_diag(out: &std::process::Output) -> String {
    let err = String::from_utf8_lossy(&out.stderr).trim().to_string();
    let text = if err.is_empty() {
        String::from_utf8_lossy(&out.stdout)
            .lines()
            .rev()
            .find(|l| !l.trim().is_empty())
            .unwrap_or("")
            .trim()
            .to_string()
    } else {
        err
    };
    tail_chars(&text, 400)
}

/// A nonzero exit is a coded tool failure carrying the tool's own words.
fn net_checked(name: &str, tool: &str, out: &std::process::Output) -> Result<()> {
    if out.status.success() {
        return Ok(());
    }
    Err(crate::safety::tool_failed(
        name,
        tool,
        out.status.code(),
        &net_diag(out),
    ))
}

/// The tool ran and exited cleanly, but its output is not in a form this
/// builtin reads. Coded, so the caller learns the answer is unavailable here
/// rather than receiving an empty one.
fn net_unparsed(name: &str, tool: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::ToolFailed,
        message: format!("{name}: the output of `{tool}` is not in a form this builtin reads"),
        builtin: name.to_string(),
        hint: format!(
            "`{tool}` ran, but this host prints its output in a form this builtin does not parse"
        ),
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("`{tool}` output this builtin reads"),
        got: "unreadable output".to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Refuse a table longer than the record bound. A table is never cut silently.
fn net_cap(name: &str, rows: Vec<Value>) -> Result<Value> {
    if rows.len() > NET_MAX_RECORDS {
        return Err(crate::safety::budget_exceeded(
            name,
            format!(
                "{} records exceed the {NET_MAX_RECORDS}-record limit",
                rows.len()
            ),
            "the table is too large to return whole; use a narrower reader",
        ));
    }
    Ok(Value::Array(rows))
}

/// The items of a `ConvertTo-Json` result. Empty output is a real empty answer
/// (PowerShell prints nothing for an empty pipeline); other non-JSON output is
/// unreadable and is refused.
#[cfg(windows)]
fn net_ps_items(name: &str, stdout: &[u8]) -> Result<Vec<serde_json::Value>> {
    let text = String::from_utf8_lossy(stdout);
    let text = text.trim();
    if text.is_empty() {
        return Ok(Vec::new());
    }
    match serde_json::from_str::<serde_json::Value>(text) {
        Ok(serde_json::Value::Array(items)) => Ok(items),
        Ok(obj @ serde_json::Value::Object(_)) => Ok(vec![obj]),
        _ => Err(net_unparsed(name, "powershell")),
    }
}

fn net_float(rec: &Value, key: &str) -> Option<f64> {
    match rec {
        Value::Record(r) => match r.get(key) {
            Some(Value::Float(f)) => Some(*f),
            _ => None,
        },
        _ => None,
    }
}

fn net_has(rec: &Value, key: &str) -> bool {
    matches!(rec, Value::Record(r) if r.contains_key(key))
}

/// A string field the tool must report. A missing key or a non-string value
/// is refused: an identity field read as "" would make the record lie.
#[cfg(any(windows, target_os = "linux", test))]
fn net_req_str(
    name: &str,
    tool: &str,
    obj: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> Result<String> {
    obj.get(key)
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .ok_or_else(|| net_unparsed(name, tool))
}

/// A string field that may legitimately be absent or empty. When the tool
/// leaves it out, the field is left out of the record too; it is not "".
#[cfg(any(windows, target_os = "linux", test))]
fn net_opt_field(
    out_key: &'static str,
    obj: &serde_json::Map<String, serde_json::Value>,
    json_key: &str,
) -> Option<(&'static str, Value)> {
    obj.get(json_key)
        .and_then(|v| v.as_str())
        .map(|s| (out_key, Value::Str(s.to_string())))
}

fn net_record(pairs: Vec<(&str, Value)>) -> Value {
    let mut rec = NetRecord::new();
    for (key, value) in pairs {
        rec.insert(key.to_string(), value);
    }
    Value::Record(rec)
}

fn bi_net_interfaces(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_interfaces";
    no_args_or_input(NAME, &args, &input)?;
    net_cap(NAME, net_interface_rows(NAME)?)
}

#[cfg(windows)]
fn net_interface_rows(name: &str) -> Result<Vec<Value>> {
    let script = "Get-NetAdapter | Select-Object Name,InterfaceDescription,MacAddress,Status,LinkSpeed | ConvertTo-Json";
    let out = net_run(
        name,
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script],
        NET_TOOL_SECS,
    )?;
    net_checked(name, "powershell", &out)?;
    let mut rows = Vec::new();
    for item in net_ps_items(name, &out.stdout)? {
        let Some(o) = item.as_object() else {
            return Err(net_unparsed(name, "powershell"));
        };
        rows.push(net_interface_record(name, o)?);
    }
    Ok(rows)
}

/// One adapter record from `Get-NetAdapter`. The name is required. The
/// description, MAC, status and speed are left out when the adapter does not
/// report them: a virtual adapter has an empty MacAddress.
#[cfg(any(windows, test))]
fn net_interface_record(
    name: &str,
    o: &serde_json::Map<String, serde_json::Value>,
) -> Result<Value> {
    let mut pairs = vec![(
        "name",
        Value::Str(net_req_str(name, "powershell", o, "Name")?),
    )];
    pairs.extend(net_opt_field("description", o, "InterfaceDescription"));
    pairs.extend(net_opt_field("mac", o, "MacAddress"));
    pairs.extend(net_opt_field("status", o, "Status"));
    pairs.extend(net_opt_field("speed", o, "LinkSpeed"));
    Ok(net_record(pairs))
}

#[cfg(target_os = "linux")]
fn net_interface_rows(name: &str) -> Result<Vec<Value>> {
    let out = net_run(name, "ip", &["-j", "addr", "show"], NET_TOOL_SECS)?;
    net_checked(name, "ip", &out)?;
    let json: serde_json::Value =
        serde_json::from_slice(&out.stdout).map_err(|_| net_unparsed(name, "ip"))?;
    let serde_json::Value::Array(links) = json else {
        return Err(net_unparsed(name, "ip"));
    };
    let mut rows = Vec::new();
    for link in &links {
        let Some(o) = link.as_object() else {
            return Err(net_unparsed(name, "ip"));
        };
        let addresses: Vec<Value> = o
            .get("addr_info")
            .and_then(|v| v.as_array())
            .map(|infos| {
                infos
                    .iter()
                    .filter_map(|i| i.get("local").and_then(|v| v.as_str()))
                    .map(|s| Value::Str(s.to_string()))
                    .collect()
            })
            .unwrap_or_default();
        let mut pairs = vec![("name", Value::Str(net_req_str(name, "ip", o, "ifname")?))];
        // `address` is absent on some tunnel links; the field is then left out.
        pairs.extend(net_opt_field("mac", o, "address"));
        pairs.extend(net_opt_field("status", o, "operstate"));
        // A link that reports no mtu gets no `mtu` field. It used to read as
        // an mtu of 0, which no interface has.
        if let Some(mtu) = o.get("mtu").and_then(|v| v.as_i64()) {
            pairs.push(("mtu", Value::Int(mtu)));
        }
        pairs.push(("addresses", Value::Array(addresses)));
        rows.push(net_record(pairs));
    }
    Ok(rows)
}

#[cfg(target_os = "macos")]
fn net_interface_rows(name: &str) -> Result<Vec<Value>> {
    let out = net_run(name, "ifconfig", &[], NET_TOOL_SECS)?;
    net_checked(name, "ifconfig", &out)?;
    let text = String::from_utf8_lossy(&out.stdout);
    let mut rows: Vec<NetRecord> = Vec::new();
    for line in text.lines() {
        if !line.starts_with(['\t', ' ']) && line.contains(':') {
            // A header such as `en0: flags=8863<UP,BROADCAST,...> mtu 1500`.
            let mut rec = NetRecord::new();
            let iface = line.split(':').next().unwrap_or("").to_string();
            rec.insert("name".to_string(), Value::Str(iface));
            // An interface with no `ether` line (lo0, utun) gets no mac field,
            // as on Windows and Linux; it used to read as "".
            let status = if line.contains("UP") { "Up" } else { "Down" };
            rec.insert("status".to_string(), Value::Str(status.to_string()));
            rows.push(rec);
        } else if let Some(mac) = line.trim().strip_prefix("ether ") {
            if let Some(last) = rows.last_mut() {
                last.insert("mac".to_string(), Value::Str(mac.trim().to_string()));
            }
        }
    }
    Ok(rows.into_iter().map(Value::Record).collect())
}

#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
fn net_interface_rows(name: &str) -> Result<Vec<Value>> {
    Err(crate::safety::unimplemented(
        name,
        "interfaces are not read on this platform",
        "run on Windows, Linux or macOS",
    ))
}

fn bi_net_ip(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_ip";
    no_args_or_input(NAME, &args, &input)?;
    net_address(NAME)
}

/// One network adapter as GetAdaptersAddresses reports it.
#[cfg(windows)]
struct WinAdapter {
    /// The friendly name, `Ethernet` or `Wi-Fi`: Get-NetIPAddress's
    /// InterfaceAlias.
    name: String,
    /// `aa:bb:cc:dd:ee:ff`, or `None` for an adapter with no hardware address
    /// (loopback, most VPN tunnels).
    mac: Option<String>,
    up: bool,
    addresses: Vec<std::net::IpAddr>,
}

/// Every adapter with its unicast addresses, from iphlpapi.
///
/// This is the table Get-NetIPAddress and ipconfig read. sysinfo's interface
/// list is not: on one host it left out the loopback interface, a VPN tunnel
/// carrying the host's traffic and every disconnected Wi-Fi adapter.
#[cfg(windows)]
fn windows_adapters(builtin: &str) -> Result<Vec<WinAdapter>> {
    use std::ffi::c_void;
    // The leading fields of IP_ADAPTER_ADDRESSES_LH, up to OperStatus. The
    // buffer is the OS's, so a prefix is all that has to match.
    #[repr(C)]
    struct AdapterAddresses {
        length: u32,
        if_index: u32,
        next: *const AdapterAddresses,
        adapter_name: *const u8,
        first_unicast: *const UnicastAddress,
        first_anycast: *const c_void,
        first_multicast: *const c_void,
        first_dns_server: *const c_void,
        dns_suffix: *const u16,
        description: *const u16,
        friendly_name: *const u16,
        physical_address: [u8; 8],
        physical_address_length: u32,
        flags: u32,
        mtu: u32,
        if_type: u32,
        oper_status: u32,
    }
    // The leading fields of IP_ADAPTER_UNICAST_ADDRESS_LH.
    #[repr(C)]
    struct UnicastAddress {
        length: u32,
        flags: u32,
        next: *const UnicastAddress,
        sockaddr: *const u16,
        sockaddr_length: i32,
    }
    #[link(name = "iphlpapi")]
    extern "system" {
        fn GetAdaptersAddresses(
            family: u32,
            flags: u32,
            reserved: *mut c_void,
            addresses: *mut c_void,
            size: *mut u32,
        ) -> u32;
    }
    const AF_UNSPEC: u32 = 0;
    const AF_INET: u16 = 2;
    const AF_INET6: u16 = 23;
    const GAA_FLAG_SKIP_ANYCAST: u32 = 0x2;
    const GAA_FLAG_SKIP_MULTICAST: u32 = 0x4;
    const GAA_FLAG_SKIP_DNS_SERVER: u32 = 0x8;
    const ERROR_BUFFER_OVERFLOW: u32 = 111;
    const ERROR_NO_DATA: u32 = 232;
    const IF_OPER_STATUS_UP: u32 = 1;

    // u64 elements, so the buffer is aligned for the structures in it.
    let mut buf: Vec<u64> = vec![0; 16 * 1024 / 8];
    let status = loop {
        let mut size = (buf.len() * 8) as u32;
        // SAFETY: `buf` holds `size` writable bytes.
        let status = unsafe {
            GetAdaptersAddresses(
                AF_UNSPEC,
                GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
                std::ptr::null_mut(),
                buf.as_mut_ptr().cast(),
                &mut size,
            )
        };
        if status == ERROR_BUFFER_OVERFLOW && size as usize > buf.len() * 8 {
            buf = vec![0; (size as usize).div_ceil(8)];
            continue;
        }
        break status;
    };
    if status == ERROR_NO_DATA {
        return Ok(Vec::new());
    }
    if status != 0 {
        return Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!(
                "GetAdaptersAddresses failed: {}",
                std::io::Error::from_raw_os_error(status as i32)
            ),
            "a readable network adapter table",
        ));
    }
    // A NUL-terminated UTF-16 string the OS owns.
    let wide = |p: *const u16| {
        if p.is_null() {
            return String::new();
        }
        let mut n = 0;
        // SAFETY: the OS terminates every string in the table.
        while unsafe { *p.add(n) } != 0 {
            n += 1;
        }
        // SAFETY: `n` units were just read.
        String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(p, n) })
    };
    let mut adapters = Vec::new();
    let mut node = buf.as_ptr() as *const AdapterAddresses;
    while !node.is_null() {
        // SAFETY: `node` is the head of, or a `next` link in, the list the OS
        // wrote into `buf`, which outlives this loop.
        let adapter = unsafe { &*node };
        let mac_len = (adapter.physical_address_length as usize).min(8);
        let mac = (mac_len > 0).then(|| {
            adapter.physical_address[..mac_len]
                .iter()
                .map(|b| format!("{b:02x}"))
                .collect::<Vec<_>>()
                .join(":")
        });
        let mut addresses = Vec::new();
        let mut unicast = adapter.first_unicast;
        while !unicast.is_null() {
            // SAFETY: a link in the same OS-written list.
            let u = unsafe { &*unicast };
            if !u.sockaddr.is_null() {
                // SAFETY: a SOCKADDR starts with its u16 family; the length
                // is checked before the address bytes are read.
                let family = unsafe { *u.sockaddr };
                let bytes = u.sockaddr.cast::<u8>();
                if family == AF_INET && u.sockaddr_length >= 8 {
                    let mut octets = [0u8; 4];
                    // SAFETY: sockaddr_in: family, port, then 4 address bytes.
                    unsafe { std::ptr::copy_nonoverlapping(bytes.add(4), octets.as_mut_ptr(), 4) };
                    addresses.push(std::net::IpAddr::from(octets));
                } else if family == AF_INET6 && u.sockaddr_length >= 24 {
                    let mut octets = [0u8; 16];
                    // SAFETY: sockaddr_in6: family, port, flowinfo, then 16
                    // address bytes.
                    unsafe { std::ptr::copy_nonoverlapping(bytes.add(8), octets.as_mut_ptr(), 16) };
                    addresses.push(std::net::IpAddr::from(octets));
                }
            }
            unicast = u.next;
        }
        adapters.push(WinAdapter {
            name: wide(adapter.friendly_name),
            mac,
            up: adapter.oper_status == IF_OPER_STATUS_UP,
            addresses,
        });
        node = adapter.next;
    }
    Ok(adapters)
}

#[cfg(windows)]
fn net_address(name: &str) -> Result<Value> {
    // Get-NetIPAddress -AddressFamily IPv4's rows, from the adapter table
    // instead of PowerShell.
    let mut rows = Vec::new();
    for adapter in windows_adapters(name)? {
        for ip in &adapter.addresses {
            if ip.is_ipv4() {
                rows.push(net_record(vec![
                    ("ip", Value::Str(ip.to_string())),
                    ("interface", Value::Str(adapter.name.clone())),
                ]));
            }
        }
    }
    if rows.is_empty() {
        return Err(crate::safety::not_found(
            name,
            "IPv4 address",
            "on this host",
        ));
    }
    // One address is the address itself, as on the other platforms; several
    // are listed with the interface each belongs to.
    if let [Value::Record(rec)] = rows.as_slice() {
        return Ok(rec.get("ip").cloned().unwrap_or(Value::Null));
    }
    Ok(Value::Array(rows))
}

#[cfg(target_os = "linux")]
fn net_address(name: &str) -> Result<Value> {
    net_address_text(name, "hostname", &["-I"])
}

#[cfg(target_os = "macos")]
fn net_address(name: &str) -> Result<Value> {
    net_address_text(name, "ipconfig", &["getifaddr", "en0"])
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn net_address_text(name: &str, tool: &str, argv: &[&str]) -> Result<Value> {
    let out = net_run(name, tool, argv, NET_TOOL_SECS)?;
    net_checked(name, tool, &out)?;
    let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if text.is_empty() {
        return Err(crate::safety::not_found(
            name,
            "IPv4 address",
            "on this host",
        ));
    }
    Ok(Value::Str(text))
}

#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
fn net_address(name: &str) -> Result<Value> {
    Err(crate::safety::unimplemented(
        name,
        "the address is not read on this platform",
        "run on Windows, Linux or macOS",
    ))
}

fn bi_net_dns_lookup(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_dns_lookup";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "no pipeline input",
            "piped input",
        ));
    }
    let host = net_host(NAME, &args, 0)?;
    net_refuse_in_transaction(NAME)?;
    net_cap(NAME, net_resolve(NAME, &host)?)
}

#[cfg(windows)]
fn net_resolve(name: &str, host: &str) -> Result<Vec<Value>> {
    let script = crate::ps_script!(
        "Resolve-DnsName {} | Select-Object IPAddress | ConvertTo-Json",
        crate::safety::ps_quote(host)
    );
    let out = net_run(
        name,
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script.as_str()],
        NET_TOOL_SECS,
    )?;
    net_checked(name, "powershell", &out)?;
    // A name can answer with CNAME records, which carry no address.
    Ok(net_ps_items(name, &out.stdout)?
        .iter()
        .filter_map(|item| item.get("IPAddress").and_then(|v| v.as_str()))
        .map(|ip| Value::Str(ip.to_string()))
        .collect())
}

#[cfg(not(windows))]
fn net_resolve(name: &str, host: &str) -> Result<Vec<Value>> {
    let out = net_run(name, "dig", &["+short", host], NET_TOOL_SECS)?;
    net_checked(name, "dig", &out)?;
    Ok(String::from_utf8_lossy(&out.stdout)
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(|l| Value::Str(l.to_string()))
        .collect())
}

fn bi_net_dns_reverse(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_dns_reverse";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "no pipeline input",
            "piped input",
        ));
    }
    let ip = net_ip_literal(NAME, &args, 0)?;
    net_refuse_in_transaction(NAME)?;
    match net_reverse(NAME, &ip)?.into_iter().next() {
        Some(name) => Ok(Value::Str(name)),
        None => Err(crate::safety::not_found(
            NAME,
            "PTR record",
            &ip.to_string(),
        )),
    }
}

#[cfg(windows)]
fn net_reverse(name: &str, ip: &std::net::IpAddr) -> Result<Vec<String>> {
    let script = crate::ps_script!(
        "Resolve-DnsName {} | Select-Object NameHost | ConvertTo-Json",
        crate::safety::ps_quote(&ip.to_string())
    );
    let out = net_run(
        name,
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script.as_str()],
        NET_TOOL_SECS,
    )?;
    net_checked(name, "powershell", &out)?;
    Ok(net_ps_items(name, &out.stdout)?
        .iter()
        .filter_map(|item| item.get("NameHost").and_then(|v| v.as_str()))
        .map(str::to_string)
        .collect())
}

#[cfg(not(windows))]
fn net_reverse(name: &str, ip: &std::net::IpAddr) -> Result<Vec<String>> {
    let target = ip.to_string();
    let out = net_run(
        name,
        "dig",
        &["+short", "-x", target.as_str()],
        NET_TOOL_SECS,
    )?;
    net_checked(name, "dig", &out)?;
    Ok(String::from_utf8_lossy(&out.stdout)
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(str::to_string)
        .collect())
}

/// Parse ping output into a structured Record with host, packets_sent, packets_received,
/// packet_loss_pct, min_rtt, avg_rtt, max_rtt. Works for both Windows and Unix ping output.
fn parse_ping_output(text: &str, host: &str) -> Value {
    let mut rec = std::collections::BTreeMap::new();
    rec.insert("host".to_string(), Value::Str(host.to_string()));

    // Parse packet statistics: "X packets transmitted, Y received" (Unix)
    // or "Packets: Sent = X, Received = Y, Lost = Z" (Windows)
    for line in text.lines() {
        let line = line.trim();
        if line.contains("packets transmitted") || line.contains("Packets:") {
            // Unix: "4 packets transmitted, 4 received, 0% packet loss"
            // Windows: "Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)"
            let nums: Vec<i64> = line
                .split(|c: char| !c.is_ascii_digit())
                .filter(|s| !s.is_empty())
                .filter_map(|s| s.parse().ok())
                .collect();
            if nums.len() >= 2 {
                rec.insert("packets_sent".to_string(), Value::Int(nums[0]));
                rec.insert("packets_received".to_string(), Value::Int(nums[1]));
            }
            // Extract loss percentage
            if let Some(pct_pos) = line.find('%') {
                let before = &line[..pct_pos];
                let loss_str = before
                    .rsplit(|c: char| !c.is_ascii_digit() && c != '.')
                    .next()
                    .unwrap_or("0");
                if let Ok(loss) = loss_str.parse::<f64>() {
                    rec.insert("packet_loss_pct".to_string(), Value::Float(loss));
                }
            }
        }
        // Parse RTT: "rtt min/avg/max/mdev = 1.234/5.678/9.012/3.456 ms" (Unix)
        // or "Minimum = 1ms, Maximum = 9ms, Average = 5ms" (Windows)
        if line.contains("min/avg/max") || line.contains("rtt ") {
            if let Some(eq_pos) = line.find('=') {
                let values_str = &line[eq_pos + 1..];
                let values: Vec<f64> = values_str
                    .split('/')
                    .filter_map(|s| s.trim().trim_end_matches("ms").trim().parse().ok())
                    .collect();
                if values.len() >= 3 {
                    rec.insert("min_rtt".to_string(), Value::Float(values[0]));
                    rec.insert("avg_rtt".to_string(), Value::Float(values[1]));
                    rec.insert("max_rtt".to_string(), Value::Float(values[2]));
                }
            }
        }
        if line.contains("Minimum") && line.contains("Maximum") && line.contains("Average") {
            // Windows: "Minimum = 1ms, Maximum = 9ms, Average = 5ms"
            let nums: Vec<f64> = line
                .split(|c: char| !c.is_ascii_digit() && c != '.')
                .filter(|s| !s.is_empty())
                .filter_map(|s| s.parse().ok())
                .collect();
            if nums.len() >= 3 {
                rec.insert("min_rtt".to_string(), Value::Float(nums[0]));
                rec.insert("max_rtt".to_string(), Value::Float(nums[1]));
                rec.insert("avg_rtt".to_string(), Value::Float(nums[2]));
            }
        }
    }

    // Include raw output as fallback
    rec.insert("raw".to_string(), Value::Str(text.to_string()));
    Value::Record(rec)
}

#[cfg(any(windows, target_os = "linux"))]
fn net_str_field_value(obj: &serde_json::Map<String, serde_json::Value>, key: &str) -> Value {
    obj.get(key).cloned().map_or(Value::Null, json_to_value)
}

fn bi_net_ping(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_ping";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "no pipeline input",
            "piped input",
        ));
    }
    let host = net_host(NAME, &args, 0)?;
    let count = net_int(NAME, &args, 1, Some(4), 1, 100)?;
    net_refuse_in_transaction(NAME)?;
    let flag = if cfg!(windows) { "-n" } else { "-c" };
    let count_text = count.to_string();
    // One probe per second on Unix, so the bound grows with the count.
    let secs = NET_TOOL_SECS + 2 * count as u64;
    let out = net_run(
        NAME,
        "ping",
        &[flag, count_text.as_str(), host.as_str()],
        secs,
    )?;
    let rec = parse_ping_output(&String::from_utf8_lossy(&out.stdout), &host);
    // A host that does not answer exits nonzero yet still reports its loss, so
    // that report is the answer. Only a run with no statistics is a failure.
    if !out.status.success() && !net_has(&rec, "packets_received") {
        return Err(crate::safety::tool_failed(
            NAME,
            "ping",
            out.status.code(),
            &net_diag(&out),
        ));
    }
    Ok(rec)
}

fn bi_net_latency(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_latency";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "no pipeline input",
            "piped input",
        ));
    }
    let host = net_host(NAME, &args, 0)?;
    net_refuse_in_transaction(NAME)?;
    let flag = if cfg!(windows) { "-n" } else { "-c" };
    let out = net_run(NAME, "ping", &[flag, "1", host.as_str()], NET_TOOL_SECS)?;
    if !out.status.success() {
        return Err(crate::safety::tool_failed(
            NAME,
            "ping",
            out.status.code(),
            &net_diag(&out),
        ));
    }
    // The round-trip time the probe reported, in milliseconds. Timing the
    // ping process itself would measure process start-up as well.
    let rec = parse_ping_output(&String::from_utf8_lossy(&out.stdout), &host);
    match net_float(&rec, "avg_rtt") {
        Some(ms) => Ok(Value::Float(ms)),
        None => Err(net_unparsed(NAME, "ping")),
    }
}

/// One traceroute or tracert line: the hop number, the address that answered
/// (`*` when none did) and the round-trip times in milliseconds. Lines that
/// do not begin with a hop number, such as the header, are not hops.
fn net_hop(line: &str) -> Option<Value> {
    let parts: Vec<&str> = line.split_whitespace().collect();
    let hop = parts.first()?.parse::<i64>().ok()?;
    let is_addr = |t: &str| t.parse::<std::net::IpAddr>().is_ok();
    // tracert -d prints the address last; traceroute -n prints it after the hop.
    let addr = if cfg!(windows) {
        parts.last().copied().filter(|t| is_addr(t))
    } else {
        parts.iter().skip(1).copied().find(|t| is_addr(t))
    };
    let rtts: Vec<Value> = parts
        .iter()
        .skip(1)
        .copied()
        .filter(|t| Some(*t) != addr)
        .filter_map(|t| t.trim_end_matches("ms").parse::<f64>().ok())
        .map(Value::Float)
        .collect();
    let mut rec = NetRecord::new();
    rec.insert("hop".to_string(), Value::Int(hop));
    rec.insert(
        "ip".to_string(),
        Value::Str(addr.unwrap_or("*").to_string()),
    );
    rec.insert("rtt_ms".to_string(), Value::Array(rtts));
    Some(Value::Record(rec))
}

fn bi_net_traceroute(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_traceroute";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "no pipeline input",
            "piped input",
        ));
    }
    let host = net_host(NAME, &args, 0)?;
    // Thirty is the usual ceiling for a route; a larger request is refused.
    let max_hops = net_int(NAME, &args, 1, Some(30), 1, 30)?;
    net_refuse_in_transaction(NAME)?;
    let hops_text = max_hops.to_string();
    let (tool, argv): (&str, [&str; 4]) = if cfg!(windows) {
        ("tracert", ["-d", "-h", hops_text.as_str(), host.as_str()])
    } else {
        (
            "traceroute",
            ["-n", "-m", hops_text.as_str(), host.as_str()],
        )
    };
    let out = net_run(NAME, tool, &argv, 120)?;
    net_checked(NAME, tool, &out)?;
    let text = String::from_utf8_lossy(&out.stdout);
    let hops: Vec<Value> = text
        .lines()
        .filter_map(net_hop)
        .take(max_hops as usize)
        .collect();
    Ok(Value::Array(hops))
}

// ---- socket tables -------------------------------------------------------

#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
fn net_socket_record(protocol: &str, state: &str, local: String, peer: String) -> Value {
    net_record(vec![
        ("protocol", Value::Str(protocol.to_string())),
        ("state", Value::Str(state.to_string())),
        ("local", Value::Str(local)),
        ("peer", Value::Str(peer)),
    ])
}

/// The state names of the TCP table, as `Get-NetTCPConnection` reports them by
/// number. Every platform reports states in upper case, as `ss` and `netstat` do.
#[cfg(any(windows, test))]
fn windows_state_name(code: i64) -> String {
    let name = match code {
        1 => "CLOSED",
        2 => "LISTEN",
        3 => "SYN_SENT",
        4 => "SYN_RECEIVED",
        5 => "ESTABLISHED",
        6 => "FIN_WAIT_1",
        7 => "FIN_WAIT_2",
        8 => "CLOSE_WAIT",
        9 => "CLOSING",
        10 => "LAST_ACK",
        11 => "TIME_WAIT",
        12 => "DELETE_TCB",
        // MSFT_NetTCPConnection's Bound: a socket bound to a port with no
        // listen and no peer, which netstat does not show at all.
        100 => "BOUND",
        _ => "UNKNOWN",
    };
    name.to_string()
}

/// A remote port from `Get-NetTCPConnection`. 0 is the table's word for "no
/// peer" (a listener or a bound socket), so it is read as 0 and rendered by the
/// caller. Any other value outside 1..=65535, or a missing one, is refused.
#[cfg(any(windows, test))]
fn net_remote_port(
    name: &str,
    o: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> Result<i64> {
    o.get(key)
        .and_then(|v| v.as_i64())
        .filter(|p| (0..=65535).contains(p))
        .ok_or_else(|| net_unparsed(name, "powershell"))
}

/// A local port from `Get-NetTCPConnection`. Missing, non-integer or 0 is
/// refused: the old `unwrap_or(0)` listed the socket as port 0, which no socket
/// has.
#[cfg(any(windows, test))]
fn net_socket_port(
    name: &str,
    o: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> Result<i64> {
    o.get(key)
        .and_then(|v| v.as_i64())
        .filter(|p| (1..=65535).contains(p))
        .ok_or_else(|| net_unparsed(name, "powershell"))
}

/// One row of the Windows TCP table, with the process that owns the socket.
/// `remote_port` is 0 when the socket has no peer: a listener or a bound socket.
#[cfg(windows)]
struct WinTcpRow {
    owner: i64,
    state: String,
    local_addr: String,
    local_port: i64,
    peer_addr: String,
    remote_port: i64,
}

/// The TCP table, read once through `Get-NetTCPConnection`. net_connections,
/// net_ports and lsof all read sockets here, so the table is read one way.
#[cfg(windows)]
fn win_tcp_table(name: &str) -> Result<Vec<WinTcpRow>> {
    let script = "Get-NetTCPConnection | Select-Object LocalAddress,LocalPort,RemoteAddress,RemotePort,State,OwningProcess | ConvertTo-Json";
    let out = net_run(
        name,
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script],
        NET_TOOL_SECS,
    )?;
    net_checked(name, "powershell", &out)?;
    let mut rows = Vec::new();
    for item in net_ps_items(name, &out.stdout)? {
        let Some(o) = item.as_object() else {
            return Err(net_unparsed(name, "powershell"));
        };
        // A missing, non-integer or non-string state is refused. A numeric code
        // outside the named range is a real state with no name: UNKNOWN.
        let state = match o.get("State") {
            Some(serde_json::Value::Number(n)) => {
                let code = n.as_i64().ok_or_else(|| net_unparsed(name, "powershell"))?;
                windows_state_name(code)
            }
            Some(serde_json::Value::String(s)) if !s.trim().is_empty() => {
                s.to_ascii_uppercase().replace('-', "_")
            }
            _ => return Err(net_unparsed(name, "powershell")),
        };
        // The owning pid is 0 for a socket that no process holds.
        let owner = o
            .get("OwningProcess")
            .and_then(|v| v.as_i64())
            .filter(|p| *p >= 0)
            .ok_or_else(|| net_unparsed(name, "powershell"))?;
        rows.push(WinTcpRow {
            owner,
            state,
            local_addr: net_req_str(name, "powershell", o, "LocalAddress")?,
            local_port: net_socket_port(name, o, "LocalPort")?,
            peer_addr: net_req_str(name, "powershell", o, "RemoteAddress")?,
            remote_port: net_remote_port(name, o, "RemotePort")?,
        });
    }
    Ok(rows)
}

#[cfg(windows)]
fn net_socket_rows(name: &str) -> Result<Vec<Value>> {
    Ok(win_tcp_table(name)?
        .iter()
        .map(|r| {
            let local = format!("{}:{}", r.local_addr, r.local_port);
            let peer = if r.remote_port == 0 {
                "*:*".to_string()
            } else {
                format!("{}:{}", r.peer_addr, r.remote_port)
            };
            net_socket_record("tcp", &r.state, local, peer)
        })
        .collect())
}

/// lsof with no path on Windows: the TCP sockets a process holds, as `lsof -i`
/// reports them, from the table net_connections reads. A socket that no process
/// holds (owner 0) is left out, and so is one whose owner exited between the
/// two reads: lsof lists only the sockets it can attribute to a process.
#[cfg(windows)]
fn lsof_windows_sockets() -> Result<Value> {
    const NAME: &str = "lsof";
    let table = win_tcp_table(NAME)?;
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
    let mut rows = Vec::new();
    for row in table.iter().filter(|r| r.owner > 0) {
        let pid = u32::try_from(row.owner).map_err(|_| net_unparsed(NAME, "powershell"))?;
        let Some(process) = sys.process(sysinfo::Pid::from_u32(pid)) else {
            continue;
        };
        // lsof names the command, not the image: `svchost.exe` is `svchost`.
        let raw = process.name().to_string_lossy().into_owned();
        let command = if raw.to_ascii_lowercase().ends_with(".exe") {
            raw[..raw.len() - 4].to_string()
        } else {
            raw
        };
        let local = lsof_endpoint(&row.local_addr, row.local_port);
        let name = if row.remote_port == 0 {
            format!("{local} ({})", row.state)
        } else {
            let peer = lsof_endpoint(&row.peer_addr, row.remote_port);
            format!("{local}->{peer} ({})", row.state)
        };
        let kind = if row.local_addr.contains(':') {
            "IPv6"
        } else {
            "IPv4"
        };
        rows.push(net_record(vec![
            ("command", Value::Str(command)),
            ("pid", Value::Str(pid.to_string())),
            ("type", Value::Str(kind.to_string())),
            ("node", Value::Str("TCP".to_string())),
            ("name", Value::Str(name)),
        ]));
    }
    net_cap(NAME, rows)
}

/// An endpoint as lsof prints it with -n: a wildcard address is `*`, and an
/// IPv6 address is bracketed.
#[cfg(windows)]
fn lsof_endpoint(addr: &str, port: i64) -> String {
    let host = if addr == "0.0.0.0" || addr == "::" {
        "*".to_string()
    } else if addr.contains(':') {
        format!("[{addr}]")
    } else {
        addr.to_string()
    };
    format!("{host}:{port}")
}

// Restart Manager, as `rstrtmgr.dll` exports it. The session is a list of
// resources (files) that the Restart Manager maps to the processes holding
// them open. Declared by hand, as the other Windows backends are, so no crate
// is added for four functions.
#[cfg(windows)]
#[link(name = "rstrtmgr")]
extern "system" {
    fn RmStartSession(session: *mut u32, flags: u32, key: *mut u16) -> u32;
    fn RmRegisterResources(
        session: u32,
        files: u32,
        file_names: *const *const u16,
        applications: u32,
        application_list: *const std::ffi::c_void,
        services: u32,
        service_names: *const *const u16,
    ) -> u32;
    fn RmGetList(
        session: u32,
        needed: *mut u32,
        count: *mut u32,
        affected: *mut RmProcessInfo,
        reboot_reasons: *mut u32,
    ) -> u32;
    fn RmEndSession(session: u32) -> u32;
}

/// RM_PROCESS_INFO from `rmnoti.h`, laid out as C does: a RM_UNIQUE_PROCESS
/// (pid and FILETIME start time), then the application name (CCH_RM_MAX_APP_NAME
/// + 1 = 256 wide characters), the service short name (CCH_RM_MAX_SVC_NAME + 1 =
/// 64), and four 32-bit fields.
#[cfg(windows)]
#[repr(C)]
#[derive(Clone, Copy)]
struct RmProcessInfo {
    process_id: u32,
    start_low: u32,
    start_high: u32,
    app_name: [u16; 256],
    service_name: [u16; 64],
    app_type: i32,
    app_status: u32,
    ts_session_id: u32,
    restartable: i32,
}

/// The Restart Manager session, ended on every path out of the lookup, including
/// an early error return or a panic.
#[cfg(windows)]
struct RmSession(u32);

#[cfg(windows)]
impl Drop for RmSession {
    fn drop(&mut self) {
        // SAFETY: the handle came from a successful RmStartSession and is ended
        // here and nowhere else; the return code has no recovery to act on.
        unsafe { RmEndSession(self.0) };
    }
}

/// The most processes `lsof PATH` reports on Windows; more is refused.
#[cfg(windows)]
const RM_MAX_HOLDERS: u32 = 1024;

/// lsof with a path on Windows: the processes holding that file open, from the
/// Restart Manager (RmStartSession, RmRegisterResources, RmGetList, RmEndSession).
/// A directory is refused with E_BAD_ARG, because the Restart Manager takes files
/// only. A path that does not exist is E_NOT_FOUND. A UNC or device path, and a
/// drive that resolves to a network share, are refused and never probed.
///
/// Row shape matches the Linux and macOS `lsof -P -n` rows: a record with the
/// same lowercase keys. Only `command`, `pid` and `name` have a value here. `command`
/// is the image name without `.exe`, as on the socket arm (the Restart Manager's
/// application name only when the process is not visible to this user); `pid`
/// is the process id as a String, as on the other arms; `name` is the file's
/// canonical path. `user`, `fd`, `type`, `device`, `size/off` and `node` are Null,
/// because the Restart Manager does not report them.
#[cfg(windows)]
fn lsof_windows_path(path: &str) -> Result<Value> {
    const NAME: &str = "lsof";
    use std::os::windows::ffi::OsStrExt;
    // exists() on a UNC or device string opens an SMB session, so the string is
    // refused before the filesystem is asked anything.
    if crate::safety::names_a_remote_share(path) {
        return Err(crate::safety::bad_arg(
            NAME,
            "a local file path, not a UNC or device path",
            "a path that begins with a drive letter",
        ));
    }
    let meta = match std::fs::metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(crate::safety::not_found(NAME, "file", path));
        }
        Err(e) => {
            return Err(crate::safety::bad_state_with_hint(
                NAME,
                &format!("cannot read '{path}': {e}"),
                "a file this user can read",
            ));
        }
    };
    if meta.is_dir() {
        return Err(crate::safety::bad_arg(
            NAME,
            "a file, not a directory: the Restart Manager lists the holders of files only",
            "a file path",
        ));
    }
    let canonical = std::fs::canonicalize(path).map_err(|e| {
        crate::safety::bad_state_with_hint(
            NAME,
            &format!("cannot resolve '{path}': {e}"),
            "a file this user can read",
        )
    })?;
    // canonicalize returns the verbatim form (\\?\C:\...). The Restart Manager is
    // given the plain drive path, so the four-character prefix is dropped without
    // a lossy conversion. A verbatim UNC form means a share, which is refused.
    let mut wide: Vec<u16> = canonical.as_os_str().encode_wide().collect();
    let verbatim: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16];
    if wide.starts_with(&verbatim) {
        wide.drain(..verbatim.len());
    }
    let unc: Vec<u16> = "UNC"
        .encode_utf16()
        .chain(std::iter::once(b'\\' as u16))
        .collect();
    if wide.starts_with(&unc) {
        return Err(crate::safety::bad_arg(
            NAME,
            "a file on a network share, which the Restart Manager does not list",
            "a file on a local drive",
        ));
    }
    wide.push(0);
    let holders = lsof_rm_holders(NAME, &wide)?;
    let file = String::from_utf16_lossy(&wide[..wide.len() - 1]);
    // lsof names the command, as the socket arm above does: the image name
    // without `.exe`. The Restart Manager's application name is a description
    // ("Windows Command Processor"), used only for a process sysinfo cannot see.
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
    let rows: Vec<Value> = holders
        .iter()
        .map(|p| {
            let image = sys
                .process(sysinfo::Pid::from_u32(p.process_id))
                .map(|proc_| proc_.name().to_string_lossy().into_owned())
                .map(|raw| {
                    if raw.to_ascii_lowercase().ends_with(".exe") {
                        raw[..raw.len() - 4].to_string()
                    } else {
                        raw
                    }
                })
                .filter(|n| !n.is_empty());
            let app_len = p
                .app_name
                .iter()
                .position(|&c| c == 0)
                .unwrap_or(p.app_name.len());
            let app = String::from_utf16_lossy(&p.app_name[..app_len]);
            let command = image.or_else(|| (!app.is_empty()).then_some(app));
            let mut rec = BTreeMap::new();
            rec.insert(
                "command".to_string(),
                command.map_or(Value::Null, Value::Str),
            );
            rec.insert("pid".to_string(), Value::Str(p.process_id.to_string()));
            for key in ["user", "fd", "type", "device", "size/off", "node"] {
                rec.insert(key.to_string(), Value::Null);
            }
            rec.insert("name".to_string(), Value::Str(file.clone()));
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(rows))
}

/// The processes holding one file open, by the Restart Manager. `path` is a
/// NUL-terminated wide string. The count is read first, then the list is read
/// into an array of that size; if the process set grew between the two calls
/// (ERROR_MORE_DATA), the count is read again, a bounded number of times.
#[cfg(windows)]
fn lsof_rm_holders(name: &str, path: &[u16]) -> Result<Vec<RmProcessInfo>> {
    const ERROR_SUCCESS: u32 = 0;
    const ERROR_ACCESS_DENIED: u32 = 5;
    const ERROR_MORE_DATA: u32 = 234;
    const ATTEMPTS: usize = 3;
    let rm_error = |call: &str, code: u32| -> anyhow::Error {
        let err = std::io::Error::from_raw_os_error(code as i32);
        let detail = format!("{call} failed: {err} (Win32 {code})");
        if code == ERROR_ACCESS_DENIED {
            crate::safety::os_denied(
                name,
                format!("{name}: {detail}"),
                "the file is not visible to this user; read a file this user owns",
            )
        } else {
            crate::safety::bad_state_with_hint(
                name,
                &detail,
                "a file this user can read, and the Restart Manager service running",
            )
        }
    };
    let mut session = 0u32;
    let mut key = [0u16; 33];
    // SAFETY: the out-pointer and the 33-element key buffer (CCH_RM_SESSION_KEY + 1)
    // are valid for the duration of the call.
    let rc = unsafe { RmStartSession(&mut session, 0, key.as_mut_ptr()) };
    if rc != ERROR_SUCCESS {
        return Err(rm_error("RmStartSession", rc));
    }
    let session = RmSession(session);
    let files = [path.as_ptr()];
    // SAFETY: one resource, a NUL-terminated wide path that outlives the call; no
    // applications or services are registered, so their pointers are not read.
    let rc = unsafe {
        RmRegisterResources(
            session.0,
            1,
            files.as_ptr(),
            0,
            std::ptr::null(),
            0,
            std::ptr::null(),
        )
    };
    if rc != ERROR_SUCCESS {
        return Err(rm_error("RmRegisterResources", rc));
    }
    for _ in 0..ATTEMPTS {
        // First call: no buffer, so the answer is the count alone.
        let mut needed = 0u32;
        let mut written = 0u32;
        let mut reasons = 0u32;
        // SAFETY: a null buffer with a zero capacity is the documented count query.
        let rc = unsafe {
            RmGetList(
                session.0,
                &mut needed,
                &mut written,
                std::ptr::null_mut(),
                &mut reasons,
            )
        };
        if rc == ERROR_SUCCESS && needed == 0 {
            return Ok(Vec::new());
        }
        if rc != ERROR_MORE_DATA {
            return Err(rm_error("RmGetList", rc));
        }
        if needed > RM_MAX_HOLDERS {
            return Err(crate::safety::budget_exceeded(
                name,
                format!("{needed} processes hold this file open; the limit is {RM_MAX_HOLDERS}"),
                "a file fewer processes hold open",
            ));
        }
        // Second call: the buffer holds the count just read.
        let mut infos = vec![
            // SAFETY: RmProcessInfo is plain integers and u16 arrays, all valid as zero.
            unsafe { std::mem::zeroed::<RmProcessInfo>() }; needed as usize
        ];
        let mut capacity = needed;
        let mut needed_now = needed;
        // SAFETY: `infos` has `capacity` elements, which the call is told; the
        // out-counts are valid locals.
        let rc = unsafe {
            RmGetList(
                session.0,
                &mut needed_now,
                &mut capacity,
                infos.as_mut_ptr(),
                &mut reasons,
            )
        };
        if rc == ERROR_SUCCESS {
            infos.truncate(capacity as usize);
            return Ok(infos);
        }
        if rc != ERROR_MORE_DATA {
            return Err(rm_error("RmGetList", rc));
        }
        if needed_now > RM_MAX_HOLDERS {
            return Err(crate::safety::budget_exceeded(
                name,
                format!(
                    "{needed_now} processes hold this file open; the limit is {RM_MAX_HOLDERS}"
                ),
                "a file fewer processes hold open",
            ));
        }
    }
    Err(crate::safety::bad_state_with_hint(
        name,
        "the processes holding this file kept changing while they were listed",
        "a file whose holders are stable; try again",
    ))
}

#[cfg(target_os = "linux")]
fn net_socket_rows(name: &str) -> Result<Vec<Value>> {
    // All TCP and UDP sockets, numeric; `ss` prints one header line first.
    let out = net_run(name, "ss", &["-tuan"], NET_TOOL_SECS)?;
    net_checked(name, "ss", &out)?;
    let text = String::from_utf8_lossy(&out.stdout);
    let mut rows = Vec::new();
    for line in text.lines().skip(1).filter(|l| !l.trim().is_empty()) {
        // Netid State Recv-Q Send-Q Local:Port Peer:Port [Process]
        let p: Vec<&str> = line.split_whitespace().collect();
        if p.len() < 6 {
            return Err(net_unparsed(name, "ss"));
        }
        rows.push(net_socket_record(
            &p[0].to_ascii_lowercase(),
            &p[1].to_ascii_uppercase(),
            p[4].to_string(),
            p[5].to_string(),
        ));
    }
    Ok(rows)
}

#[cfg(target_os = "macos")]
fn net_socket_rows(name: &str) -> Result<Vec<Value>> {
    let out = net_run(name, "netstat", &["-an", "-p", "tcp"], NET_TOOL_SECS)?;
    net_checked(name, "netstat", &out)?;
    let text = String::from_utf8_lossy(&out.stdout);
    macos_netstat_rows(name, &text)
}

/// The TCP table as macOS netstat prints it. An endpoint is written `addr.port`
/// (`127.0.0.1.49817`, `*.*`), not `addr:port`; macos_netstat_endpoint reads it
/// in the form the other platforms report.
#[cfg(any(target_os = "macos", test))]
fn macos_netstat_rows(name: &str, text: &str) -> Result<Vec<Value>> {
    let mut rows = Vec::new();
    // Two header lines: the title and the column names.
    for line in text.lines().skip(2).filter(|l| !l.trim().is_empty()) {
        // Proto Recv-Q Send-Q Local Foreign State
        let p: Vec<&str> = line.split_whitespace().collect();
        if p.len() < 6 {
            return Err(net_unparsed(name, "netstat"));
        }
        rows.push(net_socket_record(
            "tcp",
            &p[5].to_ascii_uppercase(),
            macos_netstat_endpoint(p[3]),
            macos_netstat_endpoint(p[4]),
        ));
    }
    Ok(rows)
}

/// `addr.port` as macOS netstat writes it, read as `addr:port`. The port follows
/// the last dot; an IPv6 address is bracketed, as ss prints it.
#[cfg(any(target_os = "macos", test))]
fn macos_netstat_endpoint(text: &str) -> String {
    match text.rsplit_once('.') {
        Some((addr, port)) if addr.contains(':') => format!("[{addr}]:{port}"),
        Some((addr, port)) => format!("{addr}:{port}"),
        None => text.to_string(),
    }
}

#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
fn net_socket_rows(name: &str) -> Result<Vec<Value>> {
    Err(crate::safety::unimplemented(
        name,
        "sockets are not read on this platform",
        "run on Windows, Linux or macOS",
    ))
}

fn bi_net_connections(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_connections";
    no_args_or_input(NAME, &args, &input)?;
    net_cap(NAME, net_socket_rows(NAME)?)
}

#[path = "tcp_sockets.rs"]
mod tcp_sockets;
fn bi_net_listen(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tcp_sockets::guard_and_open("net_listen", args, input, true)
}
fn bi_net_connect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tcp_sockets::guard_and_open("net_connect", args, input, false)
}
fn bi_net_send(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tcp_sockets::guard_and_send(args, input)
}
fn bi_net_recv(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tcp_sockets::guard_and_recv(args, input)
}
fn bi_net_close(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tcp_sockets::guard_and_close(args, input)
}

/// The sockets that are listening: TCP in LISTEN and UDP sockets bound and
/// waiting for datagrams (UNCONN).
fn bi_net_ports(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_ports";
    no_args_or_input(NAME, &args, &input)?;
    let listening: Vec<Value> = net_socket_rows(NAME)?
        .into_iter()
        .filter(net_is_listening)
        .collect();
    net_cap(NAME, listening)
}

fn net_is_listening(row: &Value) -> bool {
    match row {
        Value::Record(r) => matches!(
            r.get("state"),
            Some(Value::Str(s)) if s == "LISTEN" || s == "UNCONN"
        ),
        _ => false,
    }
}

// ---- neighbours, routes and counters -------------------------------------

/// The ARP table. Unix prints `host (ip) at mac ... on iface`; Windows prints
/// `ip mac type` under an `Interface:` header, which is skipped.
fn net_arp_rows(text: &str) -> Vec<Value> {
    text.lines()
        .filter_map(|l| {
            let parts: Vec<&str> = l.split_whitespace().collect();
            if parts.len() < 2 {
                return None;
            }
            let mut rec = NetRecord::new();
            if let (Some(start), Some(end)) = (l.find('('), l.find(')')) {
                if start < end {
                    rec.insert("ip".to_string(), Value::Str(l[start + 1..end].to_string()));
                }
                if let Some(at) = parts.iter().position(|&p| p == "at") {
                    if let Some(mac) = parts.get(at + 1) {
                        rec.insert("mac".to_string(), Value::Str(mac.to_string()));
                    }
                }
                if let Some(on) = parts.iter().position(|&p| p == "on") {
                    if let Some(iface) = parts.get(on + 1) {
                        rec.insert("interface".to_string(), Value::Str(iface.to_string()));
                    }
                }
            } else if parts.len() >= 3 && (parts[0].contains('.') || parts[0].contains(':')) {
                rec.insert("ip".to_string(), Value::Str(parts[0].to_string()));
                rec.insert("mac".to_string(), Value::Str(parts[1].to_string()));
                rec.insert("type".to_string(), Value::Str(parts[2].to_string()));
            }
            (!rec.is_empty()).then_some(Value::Record(rec))
        })
        .collect()
}

fn bi_net_arp(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_arp";
    no_args_or_input(NAME, &args, &input)?;
    let out = net_run(NAME, "arp", &["-a"], NET_TOOL_SECS)?;
    net_checked(NAME, "arp", &out)?;
    let text = String::from_utf8_lossy(&out.stdout);
    net_cap(NAME, net_arp_rows(&text))
}

fn bi_net_route(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_route";
    no_args_or_input(NAME, &args, &input)?;
    net_cap(NAME, net_route_rows(NAME)?)
}

#[cfg(windows)]
fn net_route_rows(name: &str) -> Result<Vec<Value>> {
    let script = "Get-NetRoute | Select-Object DestinationPrefix,NextHop,InterfaceAlias,RouteMetric | ConvertTo-Json";
    let out = net_run(
        name,
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script],
        NET_TOOL_SECS,
    )?;
    net_checked(name, "powershell", &out)?;
    let mut rows = Vec::new();
    for item in net_ps_items(name, &out.stdout)? {
        let Some(o) = item.as_object() else {
            return Err(net_unparsed(name, "powershell"));
        };
        rows.push(net_record(vec![
            ("destination", net_str_field_value(o, "DestinationPrefix")),
            ("gateway", net_str_field_value(o, "NextHop")),
            ("interface", net_str_field_value(o, "InterfaceAlias")),
            ("metric", net_str_field_value(o, "RouteMetric")),
        ]));
    }
    Ok(rows)
}

#[cfg(target_os = "linux")]
fn net_route_rows(name: &str) -> Result<Vec<Value>> {
    let out = net_run(name, "ip", &["-j", "route"], NET_TOOL_SECS)?;
    net_checked(name, "ip", &out)?;
    let json: serde_json::Value =
        serde_json::from_slice(&out.stdout).map_err(|_| net_unparsed(name, "ip"))?;
    let serde_json::Value::Array(routes) = json else {
        return Err(net_unparsed(name, "ip"));
    };
    let mut rows = Vec::new();
    for route in &routes {
        let Some(o) = route.as_object() else {
            return Err(net_unparsed(name, "ip"));
        };
        rows.push(net_record(vec![
            ("destination", net_str_field_value(o, "dst")),
            ("gateway", net_str_field_value(o, "gateway")),
            ("interface", net_str_field_value(o, "dev")),
            ("metric", net_str_field_value(o, "metric")),
        ]));
    }
    Ok(rows)
}

#[cfg(target_os = "macos")]
fn net_route_rows(name: &str) -> Result<Vec<Value>> {
    let out = net_run(name, "netstat", &["-rn"], NET_TOOL_SECS)?;
    net_checked(name, "netstat", &out)?;
    let text = String::from_utf8_lossy(&out.stdout);
    // Four header lines precede the table.
    let rows = text
        .lines()
        .skip(4)
        .filter_map(|l| {
            let parts: Vec<&str> = l.split_whitespace().collect();
            (parts.len() >= 4).then(|| {
                net_record(vec![
                    ("destination", Value::Str(parts[0].to_string())),
                    ("gateway", Value::Str(parts[1].to_string())),
                    ("flags", Value::Str(parts[2].to_string())),
                    ("interface", Value::Str(parts[parts.len() - 1].to_string())),
                ])
            })
        })
        .collect();
    Ok(rows)
}

#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
fn net_route_rows(name: &str) -> Result<Vec<Value>> {
    Err(crate::safety::unimplemented(
        name,
        "routes are not read on this platform",
        "run on Windows, Linux or macOS",
    ))
}

/// The counters in `netstat -s` text as records of `section` (the heading the
/// counter sits under, or Null), `counter` (its name) and `value` (an Int, or
/// Null). Windows prints `Name = N`; Linux and macOS print `N name` (macOS under
/// an unindented `ip:`-style heading), and `name: N` where a counter has a
/// colon. A line with no number keeps its text as the counter, with value Null,
/// rather than being dropped.
fn netstat_records(text: &str) -> Vec<Value> {
    let mut section: Option<String> = None;
    let mut rows = Vec::new();
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        if !line.starts_with(char::is_whitespace) {
            section = Some(trimmed.trim_end_matches(':').trim().to_string());
            continue;
        }
        let (counter, value) = netstat_counter(trimmed);
        rows.push(net_record(vec![
            (
                "section",
                section.clone().map(Value::Str).unwrap_or(Value::Null),
            ),
            ("counter", Value::Str(counter)),
            ("value", value.map(Value::Int).unwrap_or(Value::Null)),
        ]));
    }
    rows
}

/// The name and integer value of one indented `netstat -s` line. See
/// `netstat_records` for the spellings read.
fn netstat_counter(line: &str) -> (String, Option<i64>) {
    if let Some((name, value)) = line.split_once('=') {
        if let Ok(n) = value.trim().parse::<i64>() {
            return (name.trim().to_string(), Some(n));
        }
    }
    if let Some((first, rest)) = line.split_once(char::is_whitespace) {
        if let Ok(n) = first.parse::<i64>() {
            return (rest.trim().to_string(), Some(n));
        }
    }
    if let Some((name, value)) = line.split_once(':') {
        if let Ok(n) = value.trim().parse::<i64>() {
            return (name.trim().to_string(), Some(n));
        }
    }
    (line.to_string(), None)
}

fn bi_net_stats(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_stats";
    no_args_or_input(NAME, &args, &input)?;
    let out = net_run(NAME, "netstat", &["-s"], NET_TOOL_SECS)?;
    net_checked(NAME, "netstat", &out)?;
    if out.stdout.len() > NET_STATS_MAX {
        return Err(crate::safety::budget_exceeded(
            NAME,
            format!(
                "netstat -s wrote {} bytes, over the {NET_STATS_MAX}-byte limit",
                out.stdout.len()
            ),
            "read the counters with a narrower tool",
        ));
    }
    let text = String::from_utf8_lossy(&out.stdout);
    Ok(Value::Array(netstat_records(&text)))
}

fn bi_net_bandwidth(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_bandwidth";
    no_args_or_input(NAME, &args, &input)?;
    net_cap(NAME, net_counter_rows(NAME)?)
}

#[cfg(target_os = "linux")]
fn net_counter_rows(name: &str) -> Result<Vec<Value>> {
    let path = "/proc/net/dev";
    let text =
        std::fs::read_to_string(path).map_err(|e| crate::safety::fs_error(name, path, &e))?;
    let mut rows = Vec::new();
    // Two header lines. Each interface row is `name: ` then 16 counters, of
    // which the 1st, 2nd, 9th and 10th are the receive and transmit totals.
    for line in text.lines().skip(2) {
        let Some((iface, rest)) = line.split_once(':') else {
            return Err(net_unparsed(name, "/proc/net/dev"));
        };
        let f: Vec<&str> = rest.split_whitespace().collect();
        if f.len() < 10 {
            return Err(net_unparsed(name, "/proc/net/dev"));
        }
        let counter = |s: &str| -> Result<i64> {
            s.parse::<i64>()
                .map_err(|_| net_unparsed(name, "/proc/net/dev"))
        };
        rows.push(net_record(vec![
            ("interface", Value::Str(iface.trim().to_string())),
            ("rx_bytes", Value::Int(counter(f[0])?)),
            ("rx_packets", Value::Int(counter(f[1])?)),
            ("tx_bytes", Value::Int(counter(f[8])?)),
            ("tx_packets", Value::Int(counter(f[9])?)),
        ]));
    }
    Ok(rows)
}

#[cfg(target_os = "macos")]
fn net_counter_rows(name: &str) -> Result<Vec<Value>> {
    let out = net_run(name, "netstat", &["-ib"], NET_TOOL_SECS)?;
    net_checked(name, "netstat", &out)?;
    let text = String::from_utf8_lossy(&out.stdout);
    let mut rows = Vec::new();
    // Name Mtu Network Address Ipkts Ierrs Ibytes Opkts Oerrs Obytes
    for line in text.lines().skip(1).filter(|l| !l.trim().is_empty()) {
        let p: Vec<&str> = line.split_whitespace().collect();
        if p.len() < 10 {
            continue;
        }
        let num = |s: &str| -> Result<i64> {
            s.parse::<i64>().map_err(|_| net_unparsed(name, "netstat"))
        };
        rows.push(net_record(vec![
            ("interface", Value::Str(p[0].to_string())),
            ("rx_bytes", Value::Int(num(p[6])?)),
            ("rx_packets", Value::Int(num(p[4])?)),
            ("tx_bytes", Value::Int(num(p[9])?)),
            ("tx_packets", Value::Int(num(p[7])?)),
        ]));
    }
    Ok(rows)
}

/// One adapter row from `Get-NetAdapterStatistics`. Every counter is required:
/// a missing or non-integer one is refused. It used to be read as 0, so an
/// adapter without counters reported zero traffic.
#[cfg(any(windows, test))]
fn net_counter_record(name: &str, o: &serde_json::Map<String, serde_json::Value>) -> Result<Value> {
    let count = |key: &str| {
        o.get(key)
            .and_then(|v| v.as_i64())
            .ok_or_else(|| net_unparsed(name, "powershell"))
    };
    Ok(net_record(vec![
        (
            "interface",
            Value::Str(net_req_str(name, "powershell", o, "Name")?),
        ),
        ("rx_bytes", Value::Int(count("ReceivedBytes")?)),
        ("tx_bytes", Value::Int(count("SentBytes")?)),
        ("rx_packets", Value::Int(count("ReceivedUnicastPackets")?)),
        ("tx_packets", Value::Int(count("SentUnicastPackets")?)),
    ]))
}

#[cfg(windows)]
fn net_counter_rows(name: &str) -> Result<Vec<Value>> {
    let script = "Get-NetAdapterStatistics | Select-Object Name,ReceivedBytes,SentBytes,ReceivedUnicastPackets,SentUnicastPackets | ConvertTo-Json";
    let out = net_run(
        name,
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script],
        NET_TOOL_SECS,
    )?;
    net_checked(name, "powershell", &out)?;
    let mut rows = Vec::new();
    for item in net_ps_items(name, &out.stdout)? {
        let Some(o) = item.as_object() else {
            return Err(net_unparsed(name, "powershell"));
        };
        rows.push(net_counter_record(name, o)?);
    }
    Ok(rows)
}

#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
fn net_counter_rows(name: &str) -> Result<Vec<Value>> {
    Err(crate::safety::unimplemented(
        name,
        "interface counters are not read on this platform",
        "run on Windows, Linux or macOS",
    ))
}

fn bi_net_whois(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_whois";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "no pipeline input",
            "piped input",
        ));
    }
    let domain = net_host(NAME, &args, 0)?;
    net_refuse_in_transaction(NAME)?;
    let out = net_run(NAME, "whois", &[domain.as_str()], NET_TOOL_SECS)?;
    net_checked(NAME, "whois", &out)?;
    let full = String::from_utf8_lossy(&out.stdout).to_string();
    let truncated = full.len() > WHOIS_RAW_MAX;
    let text: &str = if truncated {
        let mut end = WHOIS_RAW_MAX;
        while !full.is_char_boundary(end) {
            end -= 1;
        }
        &full[..end]
    } else {
        &full
    };
    let mut rec = NetRecord::new();
    rec.insert("domain".to_string(), Value::Str(domain.clone()));
    for line in text.lines() {
        let Some((key, val)) = line.trim().split_once(':') else {
            continue;
        };
        let key = key.trim().to_lowercase().replace([' ', '-'], "_");
        let val = val.trim().to_string();
        if val.is_empty() {
            continue;
        }
        match key.as_str() {
            "registrar" => {
                rec.insert("registrar".to_string(), Value::Str(val));
            }
            "creation_date" | "created" => {
                rec.insert("creation_date".to_string(), Value::Str(val));
            }
            "registry_expiry_date" | "expiration_date" | "expires" => {
                rec.insert("expiration_date".to_string(), Value::Str(val));
            }
            "updated_date" => {
                rec.insert("updated_date".to_string(), Value::Str(val));
            }
            "domain_status" => {
                let statuses = rec
                    .entry("status".to_string())
                    .or_insert_with(|| Value::Array(vec![]));
                if let Value::Array(arr) = statuses {
                    arr.push(Value::Str(
                        val.split_whitespace().next().unwrap_or(&val).to_string(),
                    ));
                }
            }
            "name_server" => {
                let ns = rec
                    .entry("name_servers".to_string())
                    .or_insert_with(|| Value::Array(vec![]));
                if let Value::Array(arr) = ns {
                    arr.push(Value::Str(val.to_lowercase()));
                }
            }
            "registrant_organization" | "registrant_org" => {
                rec.insert("registrant_org".to_string(), Value::Str(val));
            }
            "registrant_country" => {
                rec.insert("registrant_country".to_string(), Value::Str(val));
            }
            "dnssec" => {
                rec.insert("dnssec".to_string(), Value::Str(val));
            }
            _ => {}
        }
    }
    rec.insert("raw".to_string(), Value::Str(text.to_string()));
    rec.insert("raw_truncated".to_string(), Value::Bool(truncated));
    Ok(Value::Record(rec))
}

/// The address a net_scan call probes. Only this machine is probed: localhost,
/// 127.0.0.1 and ::1 (brackets allowed). Any other host is refused by policy
/// with E_POLICY_DENY, whatever IRONSHELL_NET_ALLOW says, because a port scan of
/// a remote host is reconnaissance rather than a request the shell should make.
fn net_loopback(name: &str, args: &[Value]) -> Result<std::net::IpAddr> {
    let host = net_host(name, args, 0)?;
    let bare = host.trim_start_matches('[').trim_end_matches(']');
    let ip = if bare.eq_ignore_ascii_case("localhost") {
        std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
    } else {
        bare.parse::<std::net::IpAddr>().map_err(|_| {
            crate::safety::policy_deny(
                name,
                format!("{host} is not this machine; {name} only probes loopback"),
                "scan localhost, 127.0.0.1 or ::1",
            )
        })?
    };
    if !ip.is_loopback() {
        return Err(crate::safety::policy_deny(
            name,
            format!("{host} is not a loopback address; {name} only probes this machine"),
            "scan localhost, 127.0.0.1 or ::1; this builtin does not probe other hosts",
        ));
    }
    Ok(ip)
}

/// Ports probed at once. Each connect has its own thread, so a batch costs one
/// connect's wait, not one per port.
const NET_SCAN_BATCH: i64 = 128;

/// The state a connect attempt reports: open when it was accepted, closed when
/// it was refused, filtered when no answer came within the wait.
///
/// On Windows a refused loopback connect takes about two seconds to report, and
/// `connect_timeout` given less than that reports it as a timeout, so a closed
/// port reads as filtered when the wait is that short. Plain `connect` has the
/// same two-second refusal; the wait is what bounds the result either way.
fn net_state(
    name: &str,
    port: i64,
    answer: std::result::Result<
        std::io::Result<std::net::TcpStream>,
        std::sync::mpsc::RecvTimeoutError,
    >,
) -> Result<&'static str> {
    match answer {
        Ok(Ok(_accepted)) => Ok("open"),
        Ok(Err(e)) if e.kind() == std::io::ErrorKind::ConnectionRefused => Ok("closed"),
        // connect_timeout reports no answer as TimedOut; that is filtered, the
        // same as the wait running out below.
        Ok(Err(e)) if e.kind() == std::io::ErrorKind::TimedOut => Ok("filtered"),
        Ok(Err(e)) => Err(anyhow::Error::new(crate::safety::SafetyError {
            code: crate::safety::ErrorCode::Io,
            message: format!("{name}: probing port {port} failed: {e}"),
            builtin: name.to_string(),
            hint: "the loopback connect failed for a reason other than refusal; the port state is unknown".to_string(),
            approval: None,
            did_you_mean: Vec::new(),
            expected: "an accepted or refused connect".to_string(),
            got: format!("{:?}", e.kind()),
            extra: serde_json::Map::new(),
        })),
        Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Ok("filtered"),
        Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
            Err(anyhow::Error::new(crate::safety::SafetyError {
                code: crate::safety::ErrorCode::Io,
                message: format!("{name}: probing port {port} ended without an answer"),
                builtin: name.to_string(),
                hint: "the connect thread stopped before reporting; the port state is unknown"
                    .to_string(),
                approval: None,
                did_you_mean: Vec::new(),
                expected: "an accepted or refused connect".to_string(),
                got: "no answer".to_string(),
                extra: serde_json::Map::new(),
            }))
        }
    }
}

/// net_scan(host, first_port, last_port [, timeout_ms]): the state of each TCP
/// port in an inclusive range on this machine, as {port, state} records with
/// state open, closed or filtered.
///
/// Ports are probed 128 at a time; a batch waits at most one timeout, and the
/// whole call is bounded at 30 s, checked between batches. Only 1024 ports may
/// be asked for in one call. Probing another host is refused; see net_loopback.
fn bi_net_scan(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "net_scan";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "no pipeline input",
            "piped input",
        ));
    }
    let ip = net_loopback(NAME, &args)?;
    let first = net_int(NAME, &args, 1, None, 1, 65535)?;
    let last = net_int(NAME, &args, 2, None, 1, 65535)?;
    let timeout_ms = net_int(NAME, &args, 3, Some(3000), 1, 10000)?;
    if first > last {
        return Err(crate::safety::bad_arg(
            NAME,
            "first_port <= last_port",
            &format!("{first}..{last}"),
        ));
    }
    let count = last - first + 1;
    if count > NET_SCAN_MAX_PORTS {
        return Err(crate::safety::bad_arg(
            NAME,
            &format!("a range of at most {NET_SCAN_MAX_PORTS} ports"),
            &format!("{count} ports"),
        ));
    }
    net_refuse_in_transaction(NAME)?;
    let started = std::time::Instant::now();
    let deadline = std::time::Duration::from_secs(NET_SCAN_DEADLINE_SECS);
    let wait = std::time::Duration::from_millis(timeout_ms as u64);
    let mut rows = Vec::with_capacity(count as usize);
    let mut batch_start = first;
    while batch_start <= last {
        if started.elapsed() > deadline {
            return Err(crate::safety::budget_exceeded(
                NAME,
                format!(
                    "stopped after {} of {count} ports at the {NET_SCAN_DEADLINE_SECS} s limit",
                    rows.len()
                ),
                "scan a narrower port range, or a shorter timeout_ms",
            ));
        }
        let batch_end = (batch_start + NET_SCAN_BATCH - 1).min(last);
        // Every connect in the batch starts now, so they share one wait. Each
        // connect is bounded by the wait and by what is left of the call's
        // deadline, so no connect thread outlives the call by more than that.
        let per_port = wait
            .min(deadline.saturating_sub(started.elapsed()))
            .max(std::time::Duration::from_millis(1));
        let pending: Vec<_> = (batch_start..=batch_end)
            .map(|port| {
                let (sender, receiver) = std::sync::mpsc::channel();
                let addr = std::net::SocketAddr::new(ip, port as u16);
                std::thread::spawn(move || {
                    // macOS now and then fails a non-blocking loopback connect
                    // with EINVAL (seen on a CI runner, next to a listening
                    // port). One more try on a fresh socket, inside the same
                    // wait, settles it; a second EINVAL is still reported.
                    let begun = std::time::Instant::now();
                    let mut answer = std::net::TcpStream::connect_timeout(&addr, per_port);
                    if matches!(&answer, Err(e) if e.kind() == std::io::ErrorKind::InvalidInput) {
                        let left = per_port.saturating_sub(begun.elapsed());
                        if !left.is_zero() {
                            answer = std::net::TcpStream::connect_timeout(&addr, left);
                        }
                    }
                    let _ = sender.send(answer);
                });
                (port, receiver)
            })
            .collect();
        let batch_deadline = std::time::Instant::now() + wait;
        for (port, receiver) in pending {
            let remaining = batch_deadline.saturating_duration_since(std::time::Instant::now());
            let state = net_state(NAME, port, receiver.recv_timeout(remaining))?;
            rows.push(net_record(vec![
                ("port", Value::Int(port)),
                ("state", Value::Str(state.to_string())),
            ]));
        }
        batch_start = batch_end + 1;
    }
    Ok(Value::Array(rows))
}

// ============================================================================
// 290-309: System Information
// ============================================================================

/// The distribution name for `sys_info`, or None when no probe answers. A
/// probe that fails, times out or prints nothing is None, not an error: the
/// caller reports the field as null and names it in `missing`.
fn os_name_probe() -> Option<String> {
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-Command",
            "(Get-CimInstance Win32_OperatingSystem).Caption",
        ]);
        let output = bounded_cmd_output("sys_info", "powershell", cmd, PROBE_DEADLINE_SECS).ok()?;
        if !output.status.success() {
            return None;
        }
        let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
        return (!name.is_empty()).then_some(name);
    }
    #[cfg(target_os = "linux")]
    {
        let release = std::fs::read_to_string("/etc/os-release").ok()?;
        let name = release
            .lines()
            .find_map(|line| line.strip_prefix("PRETTY_NAME="))?
            .trim_matches('"')
            .to_string();
        return (!name.is_empty()).then_some(name);
    }
    #[cfg(target_os = "macos")]
    {
        let mut name_cmd = crate::safety::child_command("sw_vers");
        name_cmd.args(["-productName"]);
        let name = bounded_cmd_output("sys_info", "sw_vers", name_cmd, PROBE_DEADLINE_SECS)
            .ok()
            .filter(|o| o.status.success())
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .filter(|n| !n.is_empty())?;
        let mut ver_cmd = crate::safety::child_command("sw_vers");
        ver_cmd.args(["-productVersion"]);
        let ver = bounded_cmd_output("sys_info", "sw_vers", ver_cmd, PROBE_DEADLINE_SECS)
            .ok()
            .filter(|o| o.status.success())
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap_or_default();
        return Some(format!("{} {}", name, ver).trim().to_string());
    }
    #[allow(unreachable_code)]
    None
}

/// The host summary. Every field has its key on every OS. A field this host
/// cannot answer is null, and its name is listed in `missing`, so a caller can
/// tell an unknown value from an empty one.
fn bi_sys_info(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut rec = std::collections::BTreeMap::new();
    rec.insert(
        "os".to_string(),
        Value::Str(std::env::consts::OS.to_string()),
    );
    rec.insert(
        "arch".to_string(),
        Value::Str(std::env::consts::ARCH.to_string()),
    );
    rec.insert(
        "family".to_string(),
        Value::Str(std::env::consts::FAMILY.to_string()),
    );
    rec.insert(
        "os_name".to_string(),
        os_name_probe().map(Value::Str).unwrap_or(Value::Null),
    );

    let missing: Vec<Value> = rec
        .iter()
        .filter(|(_, v)| matches!(v, Value::Null))
        .map(|(k, _)| Value::Str(k.clone()))
        .collect();
    rec.insert("missing".to_string(), Value::Array(missing));

    Ok(Value::Record(rec))
}

fn bi_sys_hostname(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        if let Ok(name) = std::env::var("COMPUTERNAME") {
            return Ok(Value::Str(name));
        }
    }
    #[cfg(unix)]
    {
        // gethostname(2): no subprocess, and no dependency on a `hostname`
        // binary, which minimal containers do not have.
        let mut buf = [0u8; 256];
        let rc = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) };
        if rc == 0 {
            let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
            return Ok(Value::Str(
                String::from_utf8_lossy(&buf[..end]).into_owned(),
            ));
        }
    }
    // Every machine has a hostname; not finding one is a failure, and a null
    // here read as an answer.
    #[allow(unreachable_code)]
    Err(crate::safety::tool_failed(
        "sys_hostname",
        "hostname",
        None,
        "the hostname could not be read",
    ))
}

fn bi_sys_os(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Str(std::env::consts::OS.to_string()))
}

fn bi_sys_arch(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Str(std::env::consts::ARCH.to_string()))
}

/// The trimmed stdout of a probe whose exit status is part of its answer.
///
/// A non-zero exit is refused with its code and stderr. Before this, a failed
/// `uname` or `cmd /C ver` returned whatever reached stdout, usually nothing,
/// as the platform's answer.
fn probe_stdout(builtin: &str, tool: &str, output: std::process::Output) -> Result<String> {
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            builtin,
            tool,
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Run one probe under the probe deadline and return its checked stdout.
fn probe_text(builtin: &str, tool: &str, cmd: std::process::Command) -> Result<String> {
    let output = bounded_cmd_output(builtin, tool, cmd, PROBE_DEADLINE_SECS)?;
    probe_stdout(builtin, tool, output)
}

/// A probe for a tool that may not be installed at all. Absent is `Ok(None)`;
/// installed but failing, or unable to start for any other reason, is an error.
fn probe_text_if_installed(
    builtin: &str,
    tool: &str,
    cmd: std::process::Command,
) -> Result<Option<String>> {
    match bounded_cmd_output(builtin, tool, cmd, PROBE_DEADLINE_SECS) {
        Ok(output) => probe_stdout(builtin, tool, output).map(Some),
        Err(e) if is_tool_missing(&e) => Ok(None),
        Err(e) => Err(e),
    }
}

/// The Windows version from the kernel: major, minor, build and, from the
/// registry, the update revision.
///
/// Every Windows version probe ran `cmd /C ver` and parsed
/// `Microsoft Windows [Version 10.0.26200.9711]`. That started a process per
/// call and failed on a host whose display language translates "Version", so
/// platform_snapshot refused on those hosts. RtlGetVersion, unlike
/// GetVersionEx, is not capped by the application manifest; the update
/// revision is only in the registry.
#[cfg(target_os = "windows")]
struct WindowsVersion {
    major: u32,
    minor: u32,
    build: u32,
    revision: Option<u32>,
}

#[cfg(target_os = "windows")]
impl WindowsVersion {
    fn read(builtin: &str) -> Result<WindowsVersion> {
        #[repr(C)]
        struct OsVersionInfoW {
            size: u32,
            major: u32,
            minor: u32,
            build: u32,
            platform: u32,
            service_pack: [u16; 128],
        }
        #[link(name = "ntdll")]
        extern "system" {
            fn RtlGetVersion(info: *mut OsVersionInfoW) -> i32;
        }
        let mut info = OsVersionInfoW {
            size: std::mem::size_of::<OsVersionInfoW>() as u32,
            major: 0,
            minor: 0,
            build: 0,
            platform: 0,
            service_pack: [0; 128],
        };
        // SAFETY: `info` is an OSVERSIONINFOW with its size field set.
        let status = unsafe { RtlGetVersion(&mut info) };
        if status != 0 {
            return Err(crate::safety::bad_state_with_hint(
                builtin,
                &format!("RtlGetVersion returned NTSTATUS {status:#x}"),
                "a Windows kernel that reports its version",
            ));
        }
        let revision = windows_hklm_dword(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "UBR")
            .ok()
            .flatten();
        Ok(WindowsVersion {
            major: info.major,
            minor: info.minor,
            build: info.build,
            revision,
        })
    }

    /// `10.0.26200`, the kernel version `wmic os get Version` printed.
    fn kernel(&self) -> String {
        format!("{}.{}.{}", self.major, self.minor, self.build)
    }

    /// `10.0.26200.9711`, with the update revision when the registry has one.
    fn release(&self) -> String {
        match self.revision {
            Some(r) => format!("{}.{r}", self.kernel()),
            None => self.kernel(),
        }
    }

    /// The line `ver` prints on an English host, which platform_os_version
    /// and platform_snapshot have always answered. platform_snapshot's
    /// fingerprint hashes it, so it is reproduced, not reworded.
    fn ver_line(&self) -> String {
        format!("Microsoft Windows [Version {}]", self.release())
    }
}

fn bi_sys_kernel(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        // The release string, as `uname -r` gives one elsewhere. It was
        // ver's whole sentence.
        Ok(Value::Str(WindowsVersion::read("sys_kernel")?.release()))
    }
    #[cfg(not(target_os = "windows"))]
    {
        let mut cmd = crate::safety::child_command("uname");
        cmd.args(["-r"]);
        return Ok(Value::Str(probe_text("sys_kernel", "uname", cmd)?));
    }
}

/// Whole seconds from an uptime figure such as `12345.67`.
///
/// Anything else (empty, text, NaN, negative) is refused. The old code read
/// it as 0 seconds, "up 0 seconds" on a host that had been up for days.
#[cfg(any(target_os = "linux", test))]
fn uptime_seconds(builtin: &str, text: &str) -> Result<i64> {
    match text.trim().parse::<f64>() {
        Ok(secs) if secs.is_finite() && secs >= 0.0 => Ok(secs as i64),
        _ => Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!("uptime reported `{}`", text.trim()),
            "a number of seconds since boot",
        )),
    }
}

fn bi_sys_uptime(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Failure is an error. Every probe failing used to answer `Int(0)`,
    // "up 0 seconds", which a caller could not tell from a fresh boot.
    #[cfg(target_os = "windows")]
    {
        return Ok(Value::Int((windows_uptime_ms() / 1000) as i64));
    }
    #[cfg(target_os = "linux")]
    {
        const PATH: &str = "/proc/uptime";
        let uptime = std::fs::read_to_string(PATH)
            .map_err(|e| crate::safety::fs_error("sys_uptime", PATH, &e))?;
        let secs_str = uptime.split_whitespace().next().unwrap_or("");
        return uptime_seconds("sys_uptime", secs_str).map(Value::Int);
    }
    #[cfg(target_os = "macos")]
    {
        // macOS: sysctl kern.boottime returns "{ sec = 1234567890, usec = 0 }"
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "kern.boottime"]);
        let output = bounded_cmd_output("sys_uptime", "sysctl", cmd, PROBE_DEADLINE_SECS)?;
        let text = probe_stdout("sys_uptime", "sysctl -n kern.boottime", output)?;
        // Parse "{ sec = 1234567890, usec = 0 }" or "sec = 1234567890"
        let bad = || {
            crate::safety::bad_state_with_hint(
                "sys_uptime",
                &format!("kern.boottime reported `{}`", text.trim()),
                "a `sec = N` boot time",
            )
        };
        let sec_pos = text.find("sec = ").ok_or_else(|| bad())?;
        let rest = &text[sec_pos + 6..];
        let end = rest
            .find(',')
            .or_else(|| rest.find(' '))
            .or_else(|| rest.find('}'))
            .ok_or_else(|| bad())?;
        let boot_sec = rest[..end].trim().parse::<i64>().map_err(|_| bad())?;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64;
        return Ok(Value::Int(now - boot_sec));
    }
    // Any other OS has no uptime source wired up here.
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "sys_uptime",
        "uptime on this OS",
        "read the boot time with `sys_boot_time` where it is available",
    ))
}

/// Milliseconds since the Windows kernel started, sleep included.
///
/// sys_uptime and sys_boot_time had each started powershell to read WMI's
/// LastBootUpTime: about 12 s on an idle host and over the 30 s probe deadline
/// on a loaded one. The kernel's tick count answers at once. Measured on a
/// host with Fast Startup on, it put the boot 6 s before WMI did (WMI records
/// a moment later in startup); sleep and Fast Startup leave both alike.
#[cfg(target_os = "windows")]
fn windows_uptime_ms() -> u64 {
    #[link(name = "kernel32")]
    extern "system" {
        fn GetTickCount64() -> u64;
    }
    // SAFETY: no arguments, no failure mode.
    unsafe { GetTickCount64() }
}

/// The boot time as the one shape `sys_boot_time` answers in: UTC ISO 8601 to
/// the second, for example `2026-10-30T12:34:56Z`.
fn boot_time_value(epoch_secs: i64) -> Result<Value> {
    utc_iso_seconds(epoch_secs).map(Value::Str).ok_or_else(|| {
        crate::safety::bad_state_with_hint(
            "sys_boot_time",
            &format!("the boot time {epoch_secs} is out of range"),
            "a boot time within the calendar",
        )
    })
}

/// The boot time in seconds since the epoch from `sysctl -n kern.boottime`
/// text, `{ sec = 1234567890, usec = 0 }`. None when no `sec = N` is there.
#[cfg(target_os = "macos")]
fn kern_boottime_secs(text: &str) -> Option<i64> {
    let rest = &text[text.find("sec = ")? + 6..];
    let end = rest.find(|c: char| c == ',' || c == ' ' || c == '}')?;
    rest[..end].trim().parse::<i64>().ok()
}

fn bi_sys_boot_time(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Every arm answers through `boot_time_value`, so the shape is the same on
    // every OS: UTC ISO 8601 to the second.
    #[cfg(target_os = "windows")]
    {
        let now = chrono::Utc::now().timestamp();
        return boot_time_value(now - (windows_uptime_ms() / 1000) as i64);
    }
    // `uptime -s` is a procps/GNU flag. macOS `uptime` does not have it, so
    // this exited non-zero there and fell through to `Ok(Value::Null)` -- a
    // silent failure on every Mac, which nothing noticed because nothing ran
    // it. Declaring the signature made the example executable and CI failed on
    // the first try.
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "kern.boottime"]);
        let output = bounded_cmd_output("sys_boot_time", "sysctl", cmd, PROBE_DEADLINE_SECS)?;
        let text = probe_stdout("sys_boot_time", "sysctl -n kern.boottime", output)?;
        let secs = kern_boottime_secs(&text).ok_or_else(|| {
            crate::safety::bad_state_with_hint(
                "sys_boot_time",
                &format!("kern.boottime reported `{}`", text.trim()),
                "a `sec = N` boot time",
            )
        })?;
        return boot_time_value(secs);
    }
    // `uptime -s` prints the boot time in local time, to the second. It is read
    // back in the local zone and converted to UTC.
    #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
    {
        let mut cmd = crate::safety::child_command("uptime");
        cmd.args(["-s"]);
        let output = bounded_cmd_output("sys_boot_time", "uptime", cmd, PROBE_DEADLINE_SECS)?;
        let text = probe_stdout("sys_boot_time", "uptime -s", output)?;
        let bad = || {
            crate::safety::bad_state_with_hint(
                "sys_boot_time",
                &format!("uptime -s reported `{}`", text.trim()),
                "a `YYYY-MM-DD HH:MM:SS` local boot time",
            )
        };
        let naive = chrono::NaiveDateTime::parse_from_str(text.trim(), "%Y-%m-%d %H:%M:%S")
            .map_err(|_| bad())?;
        let local = chrono::TimeZone::from_local_datetime(&chrono::Local, &naive)
            .single()
            .ok_or_else(bad)?;
        return boot_time_value(local.timestamp());
    }
    // Every arm above returns. Were one to fall through, this is an error, not
    // the silent `Null` the macOS arm once answered.
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "sys_boot_time",
        "the boot time on this OS",
        "read the uptime with `sys_uptime` where it is available",
    ))
}

/// The CPU record from `/proc/cpuinfo` text.
///
/// A field the kernel does not print on this machine (ARM has no "model
/// name"; many VMs have no "cpu cores") is left out of the record. The old
/// code wrote 0 cores and 0 MHz in its place. A field that is printed but is
/// not a number is refused.
#[cfg(any(target_os = "linux", test))]
fn parse_cpuinfo(text: &str) -> Result<Value> {
    let mut rec = std::collections::BTreeMap::new();
    for line in text.lines() {
        if line.starts_with("model name") {
            if let Some(name) = line.split(':').nth(1) {
                rec.insert("name".to_string(), Value::Str(name.trim().to_string()));
            }
        } else if line.starts_with("cpu cores") {
            if let Some(cores) = line.split(':').nth(1) {
                let n = cores.trim().parse::<i64>().map_err(|_| {
                    crate::safety::bad_state_with_hint(
                        "sys_cpu_info",
                        &format!("cpu cores is `{}`", cores.trim()),
                        "a whole number of cores in /proc/cpuinfo",
                    )
                })?;
                rec.insert("cores".to_string(), Value::Int(n));
            }
        } else if line.starts_with("cpu MHz") {
            if let Some(mhz) = line.split(':').nth(1) {
                let f = mhz.trim().parse::<f64>().map_err(|_| {
                    crate::safety::bad_state_with_hint(
                        "sys_cpu_info",
                        &format!("cpu MHz is `{}`", mhz.trim()),
                        "a clock speed in /proc/cpuinfo",
                    )
                })?;
                rec.insert("mhz".to_string(), Value::Float(f));
            }
        }
    }
    Ok(Value::Record(rec))
}

fn bi_sys_cpu_info(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Returns consistent Record {name: String, cores: Int, mhz: Float} on all platforms
    // Windows: was a PowerShell Get-CimInstance Win32_Processor query (WMI),
    // parsed from its JSON. Now read in process: the name and physical core
    // count through sysinfo, the clock from the registry's ~MHz value. A value
    // that cannot be read is left out of the record.
    #[cfg(target_os = "windows")]
    {
        let mut rec = std::collections::BTreeMap::new();
        let sys = System::new_with_specifics(
            sysinfo::RefreshKind::nothing().with_cpu(sysinfo::CpuRefreshKind::nothing()),
        );
        if let Some(cpu) = sys.cpus().first() {
            let name = cpu.brand().trim();
            if !name.is_empty() {
                rec.insert("name".to_string(), Value::Str(name.to_string()));
            }
        }
        if let Some(cores) = sys.physical_core_count() {
            rec.insert("cores".to_string(), Value::Int(cores as i64));
        }
        if let Ok(Some(mhz)) = windows_cpu_mhz("sys_cpu_info") {
            rec.insert("mhz".to_string(), Value::Float(mhz as f64));
        }
        return Ok(Value::Record(rec));
    }
    #[cfg(target_os = "linux")]
    {
        const PATH: &str = "/proc/cpuinfo";
        let cpuinfo = std::fs::read_to_string(PATH)
            .map_err(|e| crate::safety::fs_error("sys_cpu_info", PATH, &e))?;
        return parse_cpuinfo(&cpuinfo);
    }
    #[cfg(target_os = "macos")]
    {
        let mut rec = std::collections::BTreeMap::new();
        // CPU brand string
        let mut brand = crate::safety::child_command("sysctl");
        brand.args(["-n", "machdep.cpu.brand_string"]);
        if let Ok(output) = bounded_cmd_output("sys_cpu_info", "sysctl", brand, PROBE_DEADLINE_SECS)
        {
            if output.status.success() {
                rec.insert(
                    "name".to_string(),
                    Value::Str(String::from_utf8_lossy(&output.stdout).trim().to_string()),
                );
            }
        }
        // Core count
        let mut physical = crate::safety::child_command("sysctl");
        physical.args(["-n", "hw.physicalcpu"]);
        if let Ok(output) =
            bounded_cmd_output("sys_cpu_info", "sysctl", physical, PROBE_DEADLINE_SECS)
        {
            if output.status.success() {
                // A count that does not parse was 0 cores before.
                let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
                let cores = text.parse::<i64>().map_err(|_| {
                    crate::safety::bad_state_with_hint(
                        "sys_cpu_info",
                        &format!("hw.physicalcpu reported `{text}`"),
                        "a whole number of physical cores",
                    )
                })?;
                rec.insert("cores".to_string(), Value::Int(cores));
            }
        }
        // CPU frequency (MHz). `hw.cpufrequency` is missing on Apple Silicon,
        // so a failed query leaves `mhz` out; a reading that is not a number
        // is refused instead of read as 0 MHz.
        let mut freq = crate::safety::child_command("sysctl");
        freq.args(["-n", "hw.cpufrequency"]);
        if let Ok(output) = bounded_cmd_output("sys_cpu_info", "sysctl", freq, PROBE_DEADLINE_SECS)
        {
            if output.status.success() {
                let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
                // Apple Silicon prints nothing for this key and exits 0: no
                // frequency is reported, so the record leaves `mhz` out.
                if !text.is_empty() {
                    let hz = text.parse::<f64>().map_err(|_| {
                        crate::safety::bad_state_with_hint(
                            "sys_cpu_info",
                            &format!("hw.cpufrequency reported `{text}`"),
                            "a clock frequency in hertz",
                        )
                    })?;
                    rec.insert("mhz".to_string(), Value::Float(hz / 1_000_000.0));
                }
            }
        }
        if !rec.is_empty() {
            return Ok(Value::Record(rec));
        }
    }
    // Every machine has a CPU; reaching here means detection failed, which a
    // null reported as an answer.
    #[allow(unreachable_code)]
    Err(crate::safety::tool_failed(
        "sys_cpu_info",
        "the platform's CPU query",
        None,
        "CPU information could not be read",
    ))
}

fn bi_sys_cpu_count(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Int(
        std::thread::available_parallelism()
            .map(|p| p.get() as i64)
            .unwrap_or(1),
    ))
}

fn bi_sys_cpu_freq(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Null means the OS does not expose a frequency: no cpufreq driver, or
    // Apple Silicon. A source that exists and fails -- a registry value or a
    // file that cannot be read, a reading that is not a number -- is a coded
    // error. It used to read as Null, the same answer as "not exposed".
    #[cfg(target_os = "windows")]
    {
        return Ok(
            windows_cpu_mhz("sys_cpu_freq")?.map_or(Value::Null, |mhz| Value::Int(mhz as i64))
        );
    }
    #[cfg(target_os = "linux")]
    {
        const PATH: &str = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";
        return match std::fs::read_to_string(PATH) {
            // kHz to MHz
            Ok(freq) => freq
                .trim()
                .parse::<i64>()
                .map(|khz| Value::Int(khz / 1000))
                .map_err(|_| {
                    crate::safety::bad_state_with_hint(
                        "sys_cpu_freq",
                        &format!("{PATH} does not hold a frequency: `{}`", freq.trim()),
                        "a cpufreq driver that reports scaling_cur_freq in kHz",
                    )
                }),
            // No cpufreq driver (many VMs): the kernel does not say.
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Value::Null),
            Err(e) => Err(crate::safety::fs_error("sys_cpu_freq", PATH, &e)),
        };
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "hw.cpufrequency"]);
        let output = bounded_cmd_output("sys_cpu_freq", "sysctl", cmd, PROBE_DEADLINE_SECS)?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            // Apple Silicon has no such OID: the OS does not expose a frequency.
            if stderr.contains("unknown oid") {
                return Ok(Value::Null);
            }
            return Err(crate::safety::tool_failed(
                "sys_cpu_freq",
                "sysctl -n hw.cpufrequency",
                output.status.code(),
                &stderr,
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout);
        let text = text.trim();
        // Exit 0 with nothing printed is how Apple Silicon answers: the OS
        // exposes no frequency, so this is a null, not a refusal.
        if text.is_empty() {
            return Ok(Value::Null);
        }
        // Hz to MHz
        return match text.parse::<i64>() {
            Ok(hz) => Ok(Value::Int(hz / 1_000_000)),
            Err(_) => Err(crate::safety::bad_state_with_hint(
                "sys_cpu_freq",
                &format!("sysctl reported no frequency: `{text}`"),
                "a Mac whose hw.cpufrequency is an integer",
            )),
        };
    }
    // Nothing was read on this OS, so this is a refusal, not a null.
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "sys_cpu_freq",
        "CPU frequency is read on Windows, Linux and macOS only; NOTHING WAS INSPECTED",
        "read the clock speed with the platform's own tools",
    ))
}

// Refresh only memory, not processes, CPUs, disks or networks.
fn memory_snapshot(builtin: &str) -> Result<System> {
    if !sysinfo::IS_SUPPORTED_SYSTEM {
        return Err(crate::safety::unimplemented(
            builtin,
            "memory queries are unsupported on this platform",
            "run on a supported system",
        ));
    }
    let mut system = System::new();
    system.refresh_memory();
    if system.total_memory() == 0 {
        return Err(crate::safety::tool_failed(
            builtin,
            "the system memory query",
            None,
            "total memory could not be read",
        ));
    }
    Ok(system)
}

fn memory_bytes(builtin: &str, bytes: u64) -> Result<Value> {
    i64::try_from(bytes).map(Value::Int).map_err(|_| {
        crate::safety::tool_failed(
            builtin,
            "the system memory query",
            None,
            "memory measurement exceeds Int",
        )
    })
}

fn bi_sys_mem_info(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let system = memory_snapshot("sys_mem_info")?;
    Ok(Value::Record(BTreeMap::from([
        (
            "total".into(),
            memory_bytes("sys_mem_info", system.total_memory())?,
        ),
        (
            "free".into(),
            memory_bytes("sys_mem_info", system.free_memory())?,
        ),
        (
            "available".into(),
            memory_bytes("sys_mem_info", system.available_memory())?,
        ),
    ])))
}

fn bi_sys_swap_info(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let system = memory_snapshot("sys_swap_info")?;
    Ok(Value::Record(BTreeMap::from([
        (
            "total".into(),
            memory_bytes("sys_swap_info", system.total_swap())?,
        ),
        (
            "used".into(),
            memory_bytes("sys_swap_info", system.used_swap())?,
        ),
        (
            "free".into(),
            memory_bytes("sys_swap_info", system.free_swap())?,
        ),
    ])))
}

fn bi_sys_disk_info(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_fs_df(vec![], None)
}

/// The `{1min, 5min, 15min}` record from the first three fields of a load
/// average reading. A short reading, or a field that is not a number, is
/// refused: the old code wrote 0.0 for it, a machine with no load.
#[cfg(any(target_os = "linux", target_os = "macos", test))]
fn load_average_record(builtin: &str, parts: &[&str]) -> Result<Value> {
    if parts.len() < 3 {
        return Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!("load average had {} fields", parts.len()),
            "three load averages (1, 5 and 15 minutes)",
        ));
    }
    let mut rec = std::collections::BTreeMap::new();
    for (key, text) in ["1min", "5min", "15min"].iter().zip(parts.iter()) {
        let load = text.trim().parse::<f64>().map_err(|_| {
            crate::safety::bad_state_with_hint(
                builtin,
                &format!("load average `{text}` is not a number"),
                "a decimal load average",
            )
        })?;
        rec.insert(key.to_string(), Value::Float(load));
    }
    Ok(Value::Record(rec))
}

/// Sets `load_1`, `load_5` and `load_15` on a system record. Windows has no
/// load average, so there they are Null. sysinfo's Windows figure is a smoothed
/// CPU queue length that reads 0.0 until its first 5 second sample, which a
/// one-shot call never reaches, so it is not used there.
fn load_fields(rec: &mut BTreeMap<String, Value>) {
    let sampled = if cfg!(windows) {
        None
    } else {
        let load = System::load_average();
        Some([load.one, load.five, load.fifteen])
    };
    for (key, value) in ["load_1", "load_5", "load_15"]
        .into_iter()
        .zip(load_field_values(sampled))
    {
        rec.insert(key.to_string(), value);
    }
}

/// The pure half of `load_fields`: a sampled `[1, 5, 15]` load average becomes
/// three Floats, and no sample (Windows) becomes three Nulls.
fn load_field_values(sampled: Option<[f64; 3]>) -> [Value; 3] {
    match sampled {
        Some(loads) => loads.map(Value::Float),
        None => [Value::Null, Value::Null, Value::Null],
    }
}

fn bi_sys_load_avg(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Record {1min: Float, 5min: Float, 15min: Float} on Linux and macOS. Windows
    // has no load average and is refused.
    #[cfg(target_os = "linux")]
    {
        const PATH: &str = "/proc/loadavg";
        let loadavg = std::fs::read_to_string(PATH)
            .map_err(|e| crate::safety::fs_error("sys_load_avg", PATH, &e))?;
        let parts: Vec<&str> = loadavg.split_whitespace().collect();
        return load_average_record("sys_load_avg", &parts);
    }
    #[cfg(target_os = "macos")]
    {
        // macOS: sysctl vm.loadavg returns "{ 1.23 4.56 7.89 }"
        let mut loadavg = crate::safety::child_command("sysctl");
        loadavg.args(["-n", "vm.loadavg"]);
        let output = bounded_cmd_output("sys_load_avg", "sysctl", loadavg, PROBE_DEADLINE_SECS)?;
        let text = probe_stdout("sys_load_avg", "sysctl -n vm.loadavg", output)?;
        let parts: Vec<&str> = text
            .trim()
            .trim_matches(|c| c == '{' || c == '}')
            .split_whitespace()
            .collect();
        return load_average_record("sys_load_avg", &parts);
    }
    #[cfg(target_os = "windows")]
    {
        // Windows has no load average. The processor load percentage is not a
        // substitute (it is not a run-queue average), so none is reported.
        return Err(crate::safety::unimplemented(
            "sys_load_avg",
            "Windows has no load average",
            "read the current processor load with `sys_cpu_info` or the busiest processes with `proc_list`",
        ));
    }
    // Any other OS has no load-average source wired up here.
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "sys_load_avg",
        "load average on this OS",
        "this OS exposes no load average to read",
    ))
}

/// A numeric uid or gid field from `/etc/passwd` or `/etc/group`. A field
/// that is not a number is refused: the old `unwrap_or(0)` read it as root.
#[cfg(any(not(target_os = "windows"), test))]
fn account_id(builtin: &str, text: &str) -> Result<i64> {
    text.trim().parse::<i64>().map_err(|_| {
        crate::safety::bad_state_with_hint(
            builtin,
            &format!("account id `{text}` is not a number"),
            "numeric uid and gid fields in the account file",
        )
    })
}

/// The account records from `/etc/passwd` text. Comment and short lines are
/// skipped, as before.
#[cfg(any(not(target_os = "windows"), test))]
fn parse_passwd(text: &str) -> Result<Vec<Value>> {
    text.lines()
        .filter(|l| !l.starts_with('#') && l.split(':').count() >= 7)
        .map(|l| -> Result<Value> {
            let parts: Vec<&str> = l.split(':').collect();
            let mut rec = std::collections::BTreeMap::new();
            rec.insert("name".to_string(), Value::Str(parts[0].to_string()));
            rec.insert(
                "uid".to_string(),
                Value::Int(account_id("sys_users", parts[2])?),
            );
            rec.insert(
                "gid".to_string(),
                Value::Int(account_id("sys_users", parts[3])?),
            );
            rec.insert("home".to_string(), Value::Str(parts[5].to_string()));
            rec.insert("shell".to_string(), Value::Str(parts[6].to_string()));
            Ok(Value::Record(rec))
        })
        .collect()
}

/// The group records from `/etc/group` text. Comment and short lines are
/// skipped, as before.
#[cfg(any(not(target_os = "windows"), test))]
fn parse_group(text: &str) -> Result<Vec<Value>> {
    text.lines()
        .filter(|l| !l.starts_with('#') && l.split(':').count() >= 4)
        .map(|l| -> Result<Value> {
            let parts: Vec<&str> = l.split(':').collect();
            let mut rec = std::collections::BTreeMap::new();
            rec.insert("name".to_string(), Value::Str(parts[0].to_string()));
            rec.insert(
                "gid".to_string(),
                Value::Int(account_id("sys_groups", parts[2])?),
            );
            rec.insert("members".to_string(), Value::Str(parts[3].to_string()));
            Ok(Value::Record(rec))
        })
        .collect()
}

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

    fn field<'a>(v: &'a Value, key: &str) -> Option<&'a Value> {
        match v {
            Value::Record(r) => r.get(key),
            _ => None,
        }
    }

    #[test]
    fn uptime_reads_whole_seconds() {
        assert_eq!(uptime_seconds("sys_uptime", "12345.67\n").unwrap(), 12345);
    }

    #[test]
    fn uptime_refuses_bad_figures() {
        assert!(uptime_seconds("sys_uptime", "").is_err());
        assert!(uptime_seconds("sys_uptime", "soon").is_err());
        assert!(uptime_seconds("sys_uptime", "NaN").is_err());
        assert!(uptime_seconds("sys_uptime", "-4").is_err());
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_boot_time_and_uptime_agree_without_a_process() {
        let Value::Str(boot) = bi_sys_boot_time(vec![], None).unwrap() else {
            panic!("sys_boot_time is not a String");
        };
        let boot = chrono::DateTime::parse_from_rfc3339(&boot).expect("an RFC 3339 time");
        let Value::Int(up) = bi_sys_uptime(vec![], None).unwrap() else {
            panic!("sys_uptime is not an Int");
        };
        let now = chrono::Local::now().fixed_offset();
        assert!(boot < now && up > 0);
        let gap = ((now - boot).num_seconds() - up).abs();
        assert!(gap <= 2, "boot time and uptime disagree by {gap} s");
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_kernel_clock_and_elevation_come_from_the_os_itself() {
        let Value::Str(release) = bi_sys_kernel(vec![], None).unwrap() else {
            panic!("sys_kernel is not a String");
        };
        let parts: Vec<&str> = release.split('.').collect();
        assert!(
            (3..=4).contains(&parts.len()) && parts.iter().all(|p| p.parse::<u32>().is_ok()),
            "not a version: {release}"
        );
        assert!(matches!(
            bi_sys_cpu_freq(vec![], None).unwrap(),
            Value::Null | Value::Int(1..)
        ));
        // Either answer is right; the token must be readable.
        windows_is_admin("sudo_check").unwrap();
        // An absent value is None, not an error.
        assert_eq!(
            windows_hklm_dword(
                r"SOFTWARE\Microsoft\Windows NT\CurrentVersion",
                "NoSuchValue"
            ),
            Ok(None)
        );
        // A REG_SZ reads whole, and an absent one is None.
        let zone = windows_hklm_string(
            r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation",
            "TimeZoneKeyName",
        );
        assert!(matches!(&zone, Ok(Some(z)) if !z.is_empty()), "{zone:?}");
        // A buffer too small for it grows rather than truncating.
        assert_eq!(
            windows_hklm_string_from(
                r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation",
                "TimeZoneKeyName",
                1,
            ),
            zone
        );
        assert_eq!(
            windows_hklm_string(
                r"SOFTWARE\Microsoft\Windows NT\CurrentVersion",
                "NoSuchValue"
            ),
            Ok(None)
        );
        assert!(matches!(bi_sys_locale(vec![], None).unwrap(), Value::Str(l) if !l.is_empty()));
        // The adapter table has loopback, which sysinfo's interface list left
        // out, with its IPv4 address.
        let adapters = windows_adapters("net_ip").unwrap();
        assert!(adapters.iter().any(|a| a.up
            && a.addresses
                .contains(&std::net::IpAddr::from([127, 0, 0, 1]))));
        // The system drive answers with sizes and a file system.
        let system = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into());
        let volumes = windows_volumes("fs_df").unwrap();
        let sys = volumes
            .iter()
            .find(|v| system.starts_with(v.letter))
            .expect("the system drive is listed");
        assert!(matches!((sys.total, sys.free), (Some(t), Some(f)) if t > 0 && f <= t));
        assert!(sys.fs_name.as_deref().is_some_and(|n| !n.is_empty()));
        // This process: its own threads, CPU time and priority, no PowerShell.
        let me = vec![Value::Int(std::process::id() as i64)];
        assert!(matches!(bi_proc_threads(me.clone(), None).unwrap(), Value::Int(n) if n >= 1));
        assert!(
            matches!(bi_proc_cpu_usage(me.clone(), None).unwrap(), Value::Float(s) if s >= 0.0)
        );
        bi_proc_priority(me, None).unwrap();
        // One record per interface, not ipconfig's text in a `raw` field.
        let Value::Array(nics) = bi_platform_network_interfaces(vec![], None).unwrap() else {
            panic!("platform_network_interfaces is not an Array");
        };
        assert!(!nics.is_empty());
        for nic in &nics {
            assert!(field(nic, "name").is_some() && field(nic, "raw").is_none());
        }
    }

    #[test]
    fn load_average_reads_three_fields() {
        let v = load_average_record("sys_load_avg", &["0.10", "0.20", "0.30", "1/200"]).unwrap();
        assert!(matches!(field(&v, "5min"), Some(Value::Float(f)) if (*f - 0.2).abs() < 1e-9));
        assert!(matches!(field(&v, "15min"), Some(Value::Float(f)) if (*f - 0.3).abs() < 1e-9));
    }

    #[test]
    fn load_average_refuses_short_or_bad_readings() {
        assert!(load_average_record("sys_load_avg", &["0.1", "0.2"]).is_err());
        assert!(load_average_record("sys_load_avg", &["0.1", "busy", "0.3"]).is_err());
    }

    #[test]
    fn cpuinfo_leaves_absent_fields_out() {
        // ARM /proc/cpuinfo: no model name, no cpu cores, no cpu MHz.
        let v = parse_cpuinfo("processor\t: 0\nBogoMIPS\t: 50.00\n").unwrap();
        assert!(field(&v, "name").is_none());
        assert!(field(&v, "cores").is_none());
        assert!(field(&v, "mhz").is_none());
    }

    #[test]
    fn cpuinfo_reads_x86_fields() {
        let v = parse_cpuinfo("model name\t: Intel Xeon\ncpu cores\t: 4\ncpu MHz\t\t: 2394.2\n")
            .unwrap();
        assert!(matches!(field(&v, "cores"), Some(Value::Int(4))));
        assert!(matches!(field(&v, "mhz"), Some(Value::Float(f)) if (*f - 2394.2).abs() < 1e-6));
    }

    #[test]
    fn cpuinfo_refuses_non_numeric_fields() {
        assert!(parse_cpuinfo("cpu cores\t: many\n").is_err());
        assert!(parse_cpuinfo("cpu MHz\t: fast\n").is_err());
    }

    #[test]
    fn passwd_reads_records_and_skips_comments() {
        let users = parse_passwd("# comment\nroot:x:0:0:root:/root:/bin/bash\nshort:x\n").unwrap();
        assert_eq!(users.len(), 1);
        assert!(matches!(field(&users[0], "uid"), Some(Value::Int(0))));
        assert!(matches!(field(&users[0], "gid"), Some(Value::Int(0))));
    }

    #[test]
    fn passwd_refuses_non_numeric_ids() {
        assert!(parse_passwd("bad:x:abc:0:::/bin/sh\n").is_err());
        assert!(parse_passwd("bad:x:1000:,:::/bin/sh\n").is_err());
    }

    #[test]
    fn group_reads_records() {
        let groups = parse_group("root:x:0:\nusers:x:100:alice,bob\n").unwrap();
        assert_eq!(groups.len(), 2);
        assert!(matches!(field(&groups[1], "gid"), Some(Value::Int(100))));
    }

    #[test]
    fn group_refuses_non_numeric_gid() {
        assert!(parse_group("odd:x:zz:\n").is_err());
    }
}

fn bi_sys_users(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-Command",
            "Get-LocalUser | Select-Object Name,Enabled,LastLogon | ConvertTo-Json",
        ]);
        let output = bounded_cmd_output("sys_users", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        let json_str = probe_stdout("sys_users", "powershell Get-LocalUser", output)?;
        // Output that is not a list of accounts was [] before: "no users".
        let json: serde_json::Value = serde_json::from_str(&json_str).map_err(|_| {
            crate::safety::bad_state_with_hint(
                "sys_users",
                "Get-LocalUser printed text that is not JSON",
                "the ConvertTo-Json list of local accounts",
            )
        })?;
        let items = match &json {
            serde_json::Value::Array(arr) => arr.clone(),
            obj @ serde_json::Value::Object(_) => vec![obj.clone()],
            _ => {
                return Err(crate::safety::bad_state_with_hint(
                    "sys_users",
                    "Get-LocalUser printed neither a list nor an account",
                    "the ConvertTo-Json list of local accounts",
                ))
            }
        };
        let users: Vec<Value> = items
            .iter()
            .filter_map(|obj| {
                let o = obj.as_object()?;
                let mut rec = std::collections::BTreeMap::new();
                if let Some(v) = o.get("Name") {
                    rec.insert("name".to_string(), json_to_value(v.clone()));
                }
                if let Some(v) = o.get("Enabled") {
                    rec.insert("enabled".to_string(), json_to_value(v.clone()));
                }
                if let Some(v) = o.get("LastLogon") {
                    rec.insert("last_logon".to_string(), json_to_value(v.clone()));
                }
                Some(Value::Record(rec))
            })
            .collect();
        return Ok(Value::Array(users));
    }
    #[cfg(not(target_os = "windows"))]
    {
        const PATH: &str = "/etc/passwd";
        let passwd = std::fs::read_to_string(PATH)
            .map_err(|e| crate::safety::fs_error("sys_users", PATH, &e))?;
        return Ok(Value::Array(parse_passwd(&passwd)?));
    }
    // Unreachable: each platform arm above returns.
    #[allow(unreachable_code)]
    Err(crate::safety::tool_failed(
        "sys_users",
        "the account database",
        None,
        "it could not be read",
    ))
}

fn bi_sys_groups(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-Command",
            "Get-LocalGroup | Select-Object Name,Description | ConvertTo-Json",
        ]);
        let output = bounded_cmd_output("sys_groups", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        let json_str = probe_stdout("sys_groups", "powershell Get-LocalGroup", output)?;
        let json: serde_json::Value = serde_json::from_str(&json_str).map_err(|_| {
            crate::safety::bad_state_with_hint(
                "sys_groups",
                "Get-LocalGroup printed text that is not JSON",
                "the ConvertTo-Json list of local groups",
            )
        })?;
        let items = match &json {
            serde_json::Value::Array(arr) => arr.clone(),
            obj @ serde_json::Value::Object(_) => vec![obj.clone()],
            _ => {
                return Err(crate::safety::bad_state_with_hint(
                    "sys_groups",
                    "Get-LocalGroup printed neither a list nor a group",
                    "the ConvertTo-Json list of local groups",
                ))
            }
        };
        let groups: Vec<Value> = items
            .iter()
            .filter_map(|obj| {
                let o = obj.as_object()?;
                let mut rec = std::collections::BTreeMap::new();
                if let Some(v) = o.get("Name") {
                    rec.insert("name".to_string(), json_to_value(v.clone()));
                }
                if let Some(v) = o.get("Description") {
                    rec.insert("description".to_string(), json_to_value(v.clone()));
                }
                Some(Value::Record(rec))
            })
            .collect();
        return Ok(Value::Array(groups));
    }
    #[cfg(not(target_os = "windows"))]
    {
        const PATH: &str = "/etc/group";
        let group = std::fs::read_to_string(PATH)
            .map_err(|e| crate::safety::fs_error("sys_groups", PATH, &e))?;
        return Ok(Value::Array(parse_group(&group)?));
    }
    // Unreachable: each platform arm above returns.
    #[allow(unreachable_code)]
    Err(crate::safety::tool_failed(
        "sys_groups",
        "the group database",
        None,
        "it could not be read",
    ))
}

/// `whoami()` -- the name of the user this shell runs as.
///
/// It was an alias of `sys_users`, so it returned every account on the
/// machine: root, daemon and the rest on Linux, every local user on Windows.
fn bi_whoami(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(unix)]
    {
        // The effective uid, as whoami(1) reports it. $USER can be unset
        // (cron, containers) or stale (after su).
        let uid = unsafe { libc::geteuid() };
        let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
        let mut buf = vec![0 as libc::c_char; 16 * 1024];
        let mut found: *mut libc::passwd = std::ptr::null_mut();
        let rc =
            unsafe { libc::getpwuid_r(uid, &mut pwd, buf.as_mut_ptr(), buf.len(), &mut found) };
        if rc == 0 && !found.is_null() && !pwd.pw_name.is_null() {
            let name = unsafe { std::ffi::CStr::from_ptr(pwd.pw_name) };
            return Ok(Value::Str(name.to_string_lossy().into_owned()));
        }
        return Err(crate::safety::bad_state_with_hint(
            "whoami",
            &format!("uid {uid} has no entry in the user database"),
            "the process runs as a uid with no passwd entry (common in containers)",
        ));
    }
    #[cfg(windows)]
    {
        return match std::env::var("USERNAME") {
            Ok(u) if !u.is_empty() => Ok(Value::Str(u)),
            _ => Err(crate::safety::bad_state_with_hint(
                "whoami",
                "USERNAME is not set",
                "this process was started without a user environment",
            )),
        };
    }
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "whoami",
        "no user database on this platform; NOTHING WAS INSPECTED",
        "",
    ))
}

fn bi_sys_user_info(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Returns consistent Record {name, home, shell, domain} on all platforms
    let mut rec = std::collections::BTreeMap::new();

    #[cfg(target_os = "windows")]
    {
        if let Ok(user) = std::env::var("USERNAME") {
            rec.insert("name".to_string(), Value::Str(user));
        }
        if let Ok(domain) = std::env::var("USERDOMAIN") {
            rec.insert("domain".to_string(), Value::Str(domain));
        }
        if let Ok(profile) = std::env::var("USERPROFILE") {
            rec.insert("home".to_string(), Value::Str(profile));
        }
        // Detect default shell on Windows
        if let Ok(comspec) = std::env::var("COMSPEC") {
            rec.insert("shell".to_string(), Value::Str(comspec));
        } else {
            rec.insert("shell".to_string(), Value::Str("cmd.exe".to_string()));
        }
    }
    #[cfg(not(target_os = "windows"))]
    {
        if let Ok(user) = std::env::var("USER") {
            rec.insert("name".to_string(), Value::Str(user));
        }
        if let Ok(home) = std::env::var("HOME") {
            rec.insert("home".to_string(), Value::Str(home));
        }
        if let Ok(shell) = std::env::var("SHELL") {
            rec.insert("shell".to_string(), Value::Str(shell));
        }
        rec.insert("domain".to_string(), Value::Str("local".to_string()));
    }

    Ok(Value::Record(rec))
}

fn bi_sys_env_all(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut rec = std::collections::BTreeMap::new();
    for (key, val) in std::env::vars() {
        let gated = gate_env_secret(&key, val);
        rec.insert(key, gated);
    }
    Ok(Value::Record(rec))
}

fn bi_sys_locale(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        // The user's locale, as `(Get-Culture).Name` gave it, without
        // starting PowerShell to ask.
        #[link(name = "kernel32")]
        extern "system" {
            fn GetUserDefaultLocaleName(name: *mut u16, len: i32) -> i32;
        }
        // LOCALE_NAME_MAX_LENGTH, NUL included.
        let mut buf = [0u16; 85];
        // SAFETY: `buf` holds `len` UTF-16 units.
        let n = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as i32) };
        if n > 1 {
            return Ok(Value::Str(String::from_utf16_lossy(&buf[..n as usize - 1])));
        }
    }
    #[cfg(not(target_os = "windows"))]
    {
        if let Ok(lang) = std::env::var("LANG") {
            return Ok(Value::Str(lang));
        }
    }
    Ok(Value::Str("C".to_string()))
}

fn bi_sys_timezone(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        // The zone ID `(Get-TimeZone).Id` gave (`Pacific Standard Time`),
        // read from where Windows keeps it instead of from PowerShell. A
        // failed read used to fall through to "UTC".
        return match windows_hklm_string(
            r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation",
            "TimeZoneKeyName",
        ) {
            Ok(Some(zone)) if !zone.is_empty() => Ok(Value::Str(zone)),
            Ok(_) => Err(crate::safety::not_found(
                "sys_timezone",
                "registry value",
                r"HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\TimeZoneKeyName",
            )),
            Err(code) => Err(crate::safety::io_fault(
                "sys_timezone",
                &format!("reading the time zone from the registry failed (error {code})"),
                "the zone is unknown, not UTC; retry, or read Get-TimeZone",
            )),
        };
    }
    #[cfg(not(target_os = "windows"))]
    {
        if let Ok(tz) = std::env::var("TZ") {
            return Ok(Value::Str(tz));
        }
        if let Ok(tz) = std::fs::read_to_string("/etc/timezone") {
            return Ok(Value::Str(tz.trim().to_string()));
        }
        // macOS has no /etc/timezone, so this fell through to the "UTC"
        // default below: a Mac in Los Angeles reported UTC, confidently and
        // wrongly. The zone name is the tail of what /etc/localtime points
        // at, which is also how Linux distros that ship no /etc/timezone
        // record it.
        if let Ok(target) = std::fs::read_link("/etc/localtime") {
            let path = target.to_string_lossy();
            if let Some(i) = path.find("zoneinfo/") {
                let zone = &path[i + "zoneinfo/".len()..];
                if !zone.is_empty() {
                    return Ok(Value::Str(zone.to_string()));
                }
            }
        }
        // With no /etc/localtime, glibc and musl use UTC, so UTC is the
        // answer. One that exists but names no zone (a copied tzfile, as in
        // many containers) was reported as UTC whatever it held.
        match std::fs::symlink_metadata("/etc/localtime") {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Value::Str("UTC".to_string())),
            _ => Err(crate::safety::unimplemented(
                "sys_timezone",
                "naming the zone when TZ is unset and /etc/localtime is not a link into zoneinfo",
                "set TZ to the zone name",
            )),
        }
    }
}

// ============================================================================
// 310-329: Service & Daemon Management
// ============================================================================

/// Parse the `Get-Service | ConvertTo-Json` output into service records.
///
/// Empty output from a successful probe is a host with no services, so it is
/// `[]`. Anything else that does not parse, is neither an array nor an object,
/// or holds an item without a `Name` is refused. Dropping such an item would
/// hand back a shorter list that reads as "no such service".
#[cfg(any(windows, test))]
fn win_service_records(builtin: &str, stdout: &str) -> Result<Vec<Value>> {
    let text = stdout.trim();
    if text.is_empty() {
        return Ok(vec![]);
    }
    let json: serde_json::Value =
        serde_json::from_str(text).map_err(|_| net_unparsed(builtin, "powershell"))?;
    let items = match json {
        serde_json::Value::Array(arr) => arr,
        obj @ serde_json::Value::Object(_) => vec![obj],
        _ => return Err(net_unparsed(builtin, "powershell")),
    };
    items
        .into_iter()
        .map(|item| {
            let o = match item {
                serde_json::Value::Object(o) => o,
                _ => return Err(net_unparsed(builtin, "powershell")),
            };
            let name = o
                .get("Name")
                .cloned()
                .ok_or_else(|| net_unparsed(builtin, "powershell"))?;
            let mut rec = std::collections::BTreeMap::new();
            rec.insert("name".to_string(), json_to_value(name));
            if let Some(v) = o.get("DisplayName") {
                rec.insert("display_name".to_string(), json_to_value(v.clone()));
            }
            let status_str = match o.get("Status").and_then(|v| v.as_i64()) {
                Some(1) => "stopped",
                Some(4) => "running",
                Some(2) => "start_pending",
                Some(3) => "stop_pending",
                _ => "unknown",
            };
            rec.insert("status".to_string(), Value::Str(status_str.to_string()));
            Ok(Value::Record(rec))
        })
        .collect()
}

/// Check `systemctl list-units --output=json` output and pass it through in
/// the shape it already had. Anything that is not a JSON array of objects,
/// including empty output, is refused rather than read as "no services".
#[cfg(any(target_os = "linux", test))]
fn systemd_units(builtin: &str, stdout: &str) -> Result<Value> {
    let json: serde_json::Value =
        serde_json::from_str(stdout.trim()).map_err(|_| net_unparsed(builtin, "systemctl"))?;
    let ok = matches!(
        &json,
        serde_json::Value::Array(items) if items.iter().all(|i| i.is_object())
    );
    if !ok {
        return Err(net_unparsed(builtin, "systemctl"));
    }
    Ok(json_to_value(json))
}

fn bi_svc_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-Command",
            "Get-Service | Select-Object Name,DisplayName,Status | ConvertTo-Json",
        ]);
        let output = bounded_cmd_output("svc_list", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                "svc_list",
                "Get-Service",
                output.status.code(),
                &String::from_utf8_lossy(&output.stderr),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout);
        return win_service_records("svc_list", &text).map(Value::Array);
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("systemctl");
        cmd.args([
            "list-units",
            "--type=service",
            "--no-pager",
            "--output=json",
        ]);
        let output = bounded_cmd_output("svc_list", "systemctl", cmd, PROBE_DEADLINE_SECS)?;
        // Old systemd (before --output=json) exits non-zero here; that is a
        // tool failure, not an empty list.
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                "svc_list",
                "systemctl list-units",
                output.status.code(),
                &String::from_utf8_lossy(&output.stderr),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout);
        return systemd_units("svc_list", &text);
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("launchctl");
        cmd.arg("list");
        // A failing launchctl used to answer an empty service list, which reads
        // as "no services". It is an error now.
        let text = probe_text("svc_list", "launchctl", cmd)?;
        // Format: PID\tStatus\tLabel
        let services: Vec<Value> = text
            .lines()
            .skip(1)
            .filter_map(|line| {
                let parts: Vec<&str> = line.split('\t').collect();
                if parts.len() >= 3 {
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("name".to_string(), Value::Str(parts[2].to_string()));
                    let status = if parts[0] == "-" {
                        "stopped"
                    } else {
                        "running"
                    };
                    rec.insert("status".to_string(), Value::Str(status.to_string()));
                    Some(Value::Record(rec))
                } else {
                    None
                }
            })
            .collect();
        return Ok(Value::Array(services));
    }
    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            "svc_list",
            "listing services is not implemented on this platform",
            "there is no service-manager probe for this platform",
        ))
    }
}

fn bi_svc_status(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "svc_status",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    crate::safety::reject_option_like("svc_status", std::slice::from_ref(&name))?;
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd
            .args([
                "-Command",
                // A missing service exits 3, distinct from every other failure.
                &crate::ps_script!(
                    "try {{ Get-Service -Name {} -ErrorAction Stop | Select-Object Name,Status | ConvertTo-Json }} catch {{ if ($_.FullyQualifiedErrorId -like 'NoServiceFoundForGivenName*') {{ exit 3 }} else {{ throw }} }}",
                    crate::safety::ps_quote(&name)
                ),
            ]);
        let output = bounded_cmd_output("svc_status", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                if let Some(obj) = json.as_object() {
                    let mut rec = std::collections::BTreeMap::new();
                    if let Some(v) = obj.get("Name") {
                        rec.insert("name".to_string(), json_to_value(v.clone()));
                    }
                    let status_str = match obj.get("Status").and_then(|v| v.as_i64()) {
                        Some(1) => "stopped",
                        Some(2) => "start_pending",
                        Some(3) => "stop_pending",
                        Some(4) => "running",
                        Some(5) => "continue_pending",
                        Some(6) => "pause_pending",
                        Some(7) => "paused",
                        _ => "unknown",
                    };
                    rec.insert("status".to_string(), Value::Str(status_str.to_string()));
                    return Ok(Value::Record(rec));
                }
            }
        }
        // A service that does not exist fell through to null, then to a tool
        // failure; the declaration promises E_NOT_FOUND, as on Linux.
        if output.status.code() == Some(3) {
            return Err(crate::safety::not_found("svc_status", "service", &name));
        }
        return Err(crate::safety::tool_failed(
            "svc_status",
            "Get-Service",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    #[cfg(target_os = "linux")]
    {
        // `systemctl is-active` says "inactive" for a unit that does not
        // exist, so a missing service read as a stopped one. LoadState tells
        // them apart.
        let mut cmd = crate::safety::child_command("systemctl");
        cmd.args([
            "show",
            "-p",
            "LoadState",
            "-p",
            "ActiveState",
            "-p",
            "SubState",
            &name,
        ]);
        let output = bounded_cmd_output("svc_status", "systemctl", cmd, PROBE_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                "svc_status",
                "systemctl show",
                output.status.code(),
                &String::from_utf8_lossy(&output.stderr),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout).to_string();
        let prop = |k: &str| {
            text.lines()
                .find_map(|l| l.strip_prefix(&format!("{k}=")))
                .unwrap_or("")
                .to_string()
        };
        if prop("LoadState") == "not-found" {
            return Err(crate::safety::not_found("svc_status", "service", &name));
        }
        // A loaded unit always reports its ActiveState; an empty one would
        // answer "" as a status.
        if prop("ActiveState").is_empty() {
            return Err(crate::safety::bad_state_with_hint(
                "svc_status",
                &format!("systemctl reported no ActiveState for `{name}`"),
                "a systemd that reports ActiveState for every unit it loads",
            ));
        }
        let mut rec = std::collections::BTreeMap::new();
        rec.insert("name".to_string(), Value::Str(name.clone()));
        rec.insert("status".to_string(), Value::Str(prop("ActiveState")));
        rec.insert("sub_state".to_string(), Value::Str(prop("SubState")));
        return Ok(Value::Record(rec));
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("launchctl");
        cmd.args(["list", &name]);
        let output = bounded_cmd_output("svc_status", "launchctl", cmd, PROBE_DEADLINE_SECS)?;
        // `launchctl list <label>` fails for a label that is not loaded, which
        // read as "stopped", and succeeds for a loaded job whether or not it
        // is running, which read as "running". A running job has a PID.
        if !output.status.success() {
            return Err(crate::safety::not_found(
                "svc_status",
                "loaded service",
                &name,
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout);
        let mut rec = std::collections::BTreeMap::new();
        rec.insert("name".to_string(), Value::Str(name.clone()));
        let running = text.contains("\"PID\" =");
        rec.insert(
            "status".to_string(),
            Value::Str(if running { "running" } else { "stopped" }.to_string()),
        );
        return Ok(Value::Record(rec));
    }
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "svc_status",
        "service status is not implemented on this OS; NOTHING WAS INSPECTED",
        "query the service manager directly",
    ))
}

/// The service name `svc_start` and its siblings take: letters, digits and
/// `-_.@:`, not beginning with `-`. Systemd units (`getty@tty1.service`),
/// launchd labels (`com.example.agent`) and Windows service names all fit.
fn svc_name(builtin: &str, args: &[Value], input: &Option<Value>) -> Result<String> {
    refuse_piped(builtin, input)?;
    k8s_max_args(builtin, args, 1)?;
    match args.first() {
        Some(Value::Str(s))
            if !s.is_empty()
                && !s.starts_with('-')
                && s.len() <= 256
                && s.chars()
                    .all(|c| c.is_ascii_alphanumeric() || "-_.@:".contains(c)) =>
        {
            Ok(s.clone())
        }
        Some(Value::Str(s)) => Err(crate::safety::bad_arg(
            builtin,
            "a service name of letters, digits and -_.@: not beginning with -",
            s,
        )),
        other => Err(crate::safety::bad_arg(
            builtin,
            "a service name String",
            other.map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

/// Run one service-manager command and turn a nonzero exit into E_TOOL_FAILED.
fn svc_run(builtin: &str, program: &str, argv: &[&str]) -> Result<()> {
    let run = tool_run(
        builtin,
        program,
        None,
        argv,
        Keep::Tail(TOOL_STDERR_TAIL),
        TOOL_DEADLINE_SECS,
    )?;
    if !run.success {
        return Err(crate::safety::tool_failed(
            builtin,
            &run.command,
            run.code,
            &run.stderr,
        ));
    }
    Ok(())
}

/// Start, stop, restart, enable or disable one service through the platform
/// service manager: `systemctl` on Linux, `launchctl` on macOS, and the
/// PowerShell service cmdlets on Windows (the name single-quoted by
/// `ps_quote`). The result is {name, action}. A refusal by the manager (no such
/// service, not permitted) is E_TOOL_FAILED; another OS is E_UNIMPLEMENTED.
///
/// Each of these used to answer `true` or `false` as a value, so an unknown
/// service or a denied request read as an ordinary result; to drop surplus
/// arguments and pipeline input; and to run with no deadline. On an
/// unsupported OS they answered `false` without trying.
fn svc_action(
    builtin: &str,
    action: &str,
    args: Vec<Value>,
    input: Option<Value>,
) -> Result<Value> {
    let name = svc_name(builtin, &args, &input)?;
    if cfg!(windows) {
        let quoted = crate::safety::ps_quote(&name);
        let script = match action {
            "start" => crate::ps_script!("Start-Service {} -ErrorAction Stop", quoted),
            "stop" => crate::ps_script!("Stop-Service {} -ErrorAction Stop", quoted),
            "restart" => crate::ps_script!("Restart-Service {} -ErrorAction Stop", quoted),
            "enable" => crate::ps_script!(
                "Set-Service {} -StartupType Automatic -ErrorAction Stop",
                quoted
            ),
            _ => crate::ps_script!(
                "Set-Service {} -StartupType Disabled -ErrorAction Stop",
                quoted
            ),
        };
        svc_run(
            builtin,
            "powershell",
            &["-NoProfile", "-NonInteractive", "-Command", &script],
        )?;
    } else if cfg!(target_os = "linux") {
        svc_run(builtin, "systemctl", &[action, "--", &name])?;
    } else if cfg!(target_os = "macos") {
        let domain = format!("system/{name}");
        match action {
            // launchctl has no restart; kickstart -k kills and restarts the job.
            "restart" => svc_run(builtin, "launchctl", &["kickstart", "-k", &domain])?,
            "enable" | "disable" => svc_run(builtin, "launchctl", &[action, &domain])?,
            _ => svc_run(builtin, "launchctl", &[action, &name])?,
        }
    } else {
        return Err(crate::safety::unimplemented(
            builtin,
            "service control is not implemented on this OS; nothing was changed",
            "use the service manager directly",
        ));
    }
    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(name));
    rec.insert("action".to_string(), Value::Str(action.to_string()));
    Ok(Value::Record(rec))
}

fn bi_svc_start(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    svc_action("svc_start", "start", args, input)
}

fn bi_svc_stop(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    svc_action("svc_stop", "stop", args, input)
}

fn bi_svc_restart(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    svc_action("svc_restart", "restart", args, input)
}

fn bi_svc_enable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    svc_action("svc_enable", "enable", args, input)
}

fn bi_svc_disable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    svc_action("svc_disable", "disable", args, input)
}

fn bi_svc_logs(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "svc_logs",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let lines = args
        .get(1)
        .and_then(|v| match v {
            Value::Int(n) => Some(*n),
            _ => None,
        })
        .unwrap_or(100);

    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd
            .args([
                "-Command",
                &crate::ps_script!(
                    // Get-EventLog exits 1 when there are no entries; an empty
                    // log is [], not a failure.
                    "ConvertTo-Json -InputObject @(Get-EventLog -LogName Application -Source {} -Newest {} -ErrorAction SilentlyContinue | Select-Object TimeGenerated,EntryType,Message)",
                    crate::safety::ps_quote(&name), lines
                ),
            ]);
        let output = bounded_cmd_output("svc_logs", "powershell", cmd, TOOL_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                let items = match &json {
                    serde_json::Value::Array(arr) => arr.clone(),
                    obj @ serde_json::Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                let entries: Vec<Value> = items
                    .iter()
                    .filter_map(|obj| {
                        let o = obj.as_object()?;
                        let mut rec = std::collections::BTreeMap::new();
                        if let Some(v) = o.get("TimeGenerated") {
                            rec.insert("timestamp".to_string(), json_to_value(v.clone()));
                        }
                        if let Some(v) = o.get("EntryType") {
                            rec.insert("level".to_string(), json_to_value(v.clone()));
                        }
                        if let Some(v) = o.get("Message") {
                            rec.insert("message".to_string(), json_to_value(v.clone()));
                        }
                        Some(Value::Record(rec))
                    })
                    .collect();
                return Ok(Value::Array(entries));
            }
        }
        // A failed query answered [], "no log entries".
        return Err(crate::safety::tool_failed(
            "svc_logs",
            "Get-EventLog",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("journalctl");
        cmd.args([
            "-u",
            &name,
            "-n",
            &lines.to_string(),
            "--no-pager",
            "-o",
            "json",
        ]);
        let output = bounded_cmd_output("svc_logs", "journalctl", cmd, TOOL_DEADLINE_SECS)?;
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            let entries: Vec<Value> = text
                .lines()
                .filter_map(|line| {
                    serde_json::from_str::<serde_json::Value>(line)
                        .ok()
                        .and_then(|obj| {
                            let o = obj.as_object()?;
                            let mut rec = std::collections::BTreeMap::new();
                            if let Some(v) = o.get("__REALTIME_TIMESTAMP") {
                                rec.insert("timestamp".to_string(), json_to_value(v.clone()));
                            }
                            if let Some(v) = o.get("PRIORITY") {
                                rec.insert("level".to_string(), json_to_value(v.clone()));
                            }
                            if let Some(v) = o.get("MESSAGE") {
                                rec.insert("message".to_string(), json_to_value(v.clone()));
                            }
                            if let Some(v) = o.get("_PID") {
                                rec.insert("pid".to_string(), json_to_value(v.clone()));
                            }
                            Some(Value::Record(rec))
                        })
                })
                .collect();
            return Ok(Value::Array(entries));
        }
        // Fallback: text parsing
        let mut cmd = crate::safety::child_command("journalctl");
        cmd.args(["-u", &name, "-n", &lines.to_string(), "--no-pager"]);
        let output = bounded_cmd_output("svc_logs", "journalctl", cmd, TOOL_DEADLINE_SECS)?;
        // Unreadable journals (no systemd, no permission) answered [].
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                "svc_logs",
                "journalctl",
                output.status.code(),
                &String::from_utf8_lossy(&output.stderr),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout);
        let entries: Vec<Value> = text
            .lines()
            .filter(|l| !l.trim().is_empty())
            .map(|l| {
                let mut rec = std::collections::BTreeMap::new();
                rec.insert("message".to_string(), Value::Str(l.to_string()));
                Value::Record(rec)
            })
            .collect();
        return Ok(Value::Array(entries));
    }
    #[cfg(target_os = "macos")]
    {
        // The name goes into a log predicate inside single quotes; a quote or
        // backslash in it would change the predicate.
        // Code points, not char literals: see the scanner note in
        // platform_disk_usage. 0x27 is the single quote, 0x5c the backslash.
        if name.chars().any(|c| matches!(c as u32, 0x27 | 0x5c)) {
            return Err(crate::safety::bad_arg(
                "svc_logs",
                "a process name without quotes or backslashes",
                &name,
            ));
        }
        let mut cmd = crate::safety::child_command("log");
        cmd.args([
            "show",
            "--predicate",
            &format!("process == '{}'", name),
            "--last",
            "1h",
            "--style",
            "compact",
        ]);
        let output = bounded_cmd_output("svc_logs", "log", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                "svc_logs",
                "log show",
                output.status.code(),
                &String::from_utf8_lossy(&output.stderr),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout);
        // The newest `lines` entries; this took the oldest. The first line is
        // the column header.
        let all: Vec<&str> = text
            .lines()
            .skip(1)
            .filter(|l| !l.trim().is_empty())
            .collect();
        let entries: Vec<Value> = all[all.len().saturating_sub(lines.max(0) as usize)..]
            .iter()
            .map(|l| {
                let mut rec = std::collections::BTreeMap::new();
                // macOS log compact format: "timestamp  processName[pid]  message"
                // Try to split at known boundaries
                let parts: Vec<&str> = l.splitn(3, "  ").collect();
                if parts.len() >= 2 {
                    rec.insert(
                        "timestamp".to_string(),
                        Value::Str(parts[0].trim().to_string()),
                    );
                    let msg = if parts.len() >= 3 { parts[2] } else { parts[1] };
                    rec.insert("message".to_string(), Value::Str(msg.trim().to_string()));
                } else {
                    rec.insert("message".to_string(), Value::Str(l.to_string()));
                }
                Value::Record(rec)
            })
            .collect();
        return Ok(Value::Array(entries));
    }
    #[allow(unreachable_code)]
    {
        let _ = (name, lines);
        Ok(Value::Null)
    }
}

fn bi_svc_info(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_svc_status(args, None)
}

#[path = "services.rs"]
mod services;

fn bi_svc_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    services::svc_create(args, input)
}

fn bi_svc_delete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    services::svc_delete(args, input)
}

fn bi_cron_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if !args.is_empty() || input.is_some() {
        return Err(crate::safety::arg_err(
            "cron_list accepts no arguments or pipeline input",
        ));
    }
    #[cfg(windows)]
    {
        let script = "$ErrorActionPreference='Stop'; $OutputEncoding=[System.Text.UTF8Encoding]::new($false); [Console]::OutputEncoding=$OutputEncoding; ConvertTo-Json -InputObject @(Get-ScheduledTask -ErrorAction Stop | Select-Object TaskName,@{Name='State';Expression={$_.State.ToString()}},TaskPath) -Depth 3 -Compress";
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-NoLogo",
            "-NoProfile",
            "-NonInteractive",
            "-Command",
            script,
        ])
        .stdin(std::process::Stdio::null());
        let output = bounded_cmd_output("cron_list", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        parse_cron_listing(output, true)
    }
    #[cfg(unix)]
    {
        let mut cmd = crate::safety::child_command("crontab");
        cmd.arg("-l")
            .env("LC_ALL", "C")
            .stdin(std::process::Stdio::null());
        let output = bounded_cmd_output("cron_list", "crontab", cmd, PROBE_DEADLINE_SECS)?;
        parse_cron_listing(output, false)
    }
    #[cfg(not(any(unix, windows)))]
    {
        Err(crate::safety::unimplemented(
            "cron_list",
            "scheduler queries are unavailable on this platform",
            "use a supported platform scheduler",
        ))
    }
}

#[cfg(any(unix, windows, test))]
fn parse_cron_listing(output: std::process::Output, windows: bool) -> Result<Value> {
    let tool = if windows {
        "powershell Get-ScheduledTask"
    } else {
        "crontab -l"
    };
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let diagnostic = stderr
            .trim()
            .strip_prefix("crontab: ")
            .unwrap_or(stderr.trim());
        let absent = diagnostic
            .strip_prefix("no crontab for ")
            .is_some_and(|user| !user.is_empty() && !user.contains(['\n', '\r']));
        if !windows
            && output.status.code() == Some(1)
            && output.stdout.iter().all(u8::is_ascii_whitespace)
            && absent
        {
            return Ok(Value::Array(vec![]));
        }
        return Err(crate::safety::tool_failed(
            "cron_list",
            tool,
            output.status.code(),
            &stderr,
        ));
    }
    let malformed = || {
        crate::safety::bad_state_with_hint(
            "cron_list",
            "unexpected scheduler output",
            "complete task JSON or supported user-crontab syntax",
        )
    };
    let text = String::from_utf8(output.stdout).map_err(|_| malformed())?;
    let mut rows = Vec::new();
    if windows {
        let json: serde_json::Value = serde_json::from_str(&text).map_err(|_| malformed())?;
        let tasks = json.as_array().ok_or_else(malformed)?;
        for task in tasks {
            let mut row = std::collections::BTreeMap::new();
            for (source, target) in [
                ("TaskName", "name"),
                ("State", "state"),
                ("TaskPath", "path"),
            ] {
                let field = task
                    .get(source)
                    .and_then(|v| v.as_str())
                    .filter(|s| !s.is_empty())
                    .ok_or_else(malformed)?;
                row.insert(target.into(), Value::Str(field.into()));
            }
            rows.push(Value::Record(row));
        }
    } else {
        for line in text.lines() {
            let mut rest = line.trim_start();
            if rest.is_empty() || rest.starts_with('#') {
                continue;
            }
            if let Some((name, _)) = rest.split_once('=') {
                let name = name.trim();
                let mut chars = name.bytes();
                if chars
                    .next()
                    .is_some_and(|c| c.is_ascii_alphabetic() || c == b'_')
                    && chars.all(|c| c.is_ascii_alphanumeric() || c == b'_')
                {
                    continue;
                }
            }
            let mut fields = Vec::new();
            let count = if rest.starts_with('@') { 1 } else { 5 };
            for _ in 0..count {
                let end = rest.find(char::is_whitespace).ok_or_else(malformed)?;
                fields.push(&rest[..end]);
                rest = rest[end..].trim_start();
            }
            if rest.is_empty() {
                return Err(malformed());
            }
            if count == 1
                && !matches!(
                    fields[0],
                    "@reboot"
                        | "@yearly"
                        | "@annually"
                        | "@monthly"
                        | "@weekly"
                        | "@daily"
                        | "@midnight"
                        | "@hourly"
                )
            {
                return Err(malformed());
            }
            let mut row = std::collections::BTreeMap::new();
            row.insert("schedule".into(), Value::Str(fields.join(" ")));
            row.insert("command".into(), Value::Str(rest.into()));
            rows.push(Value::Record(row));
        }
    }
    Ok(Value::Array(rows))
}

#[cfg(all(test, any(unix, windows)))]
mod cron_listing_tests {
    use super::*;
    fn output(code: u32, stdout: &[u8], stderr: &[u8]) -> std::process::Output {
        #[cfg(unix)]
        let status = {
            use std::os::unix::process::ExitStatusExt;
            std::process::ExitStatus::from_raw((code as i32) << 8)
        };
        #[cfg(windows)]
        let status = {
            use std::os::windows::process::ExitStatusExt;
            std::process::ExitStatus::from_raw(code)
        };
        std::process::Output {
            status,
            stdout: stdout.to_vec(),
            stderr: stderr.to_vec(),
        }
    }
    #[test]
    fn windows_tasks_require_complete_string_records_and_a_real_empty_array() {
        assert!(
            matches!(parse_cron_listing(output(0,b"[]",b""),true).unwrap(),Value::Array(a) if a.is_empty())
        );
        let rows = parse_cron_listing(
            output(
                0,
                br#"[{"TaskName":"test","State":"Ready","TaskPath":"/"}]"#,
                b"",
            ),
            true,
        )
        .unwrap();
        assert!(matches!(rows,Value::Array(a) if a.len()==1));
        for text in [
            "",
            "null",
            "1",
            "{}",
            "[{}]",
            "[null]",
            r#"[{"TaskName":"test","State":3,"TaskPath":"/"}]"#,
            r#"[{"TaskName":"test","State":"Ready"}]"#,
        ] {
            let err = parse_cron_listing(output(0, text.as_bytes(), b""), true)
                .unwrap_err()
                .to_string();
            assert!(err.contains("E_BAD_STATE"), "{err}");
        }
    }
    #[test]
    fn unix_lines_preserve_commands_skip_environment_and_accept_special_schedules() {
        let Value::Array(rows)=parse_cron_listing(output(0,b"# comment\nSHELL = /bin/sh\nMAILTO=\"a@b\"\n  0   1\t* * * echo a  b=1\n@reboot echo ready\n",b""),false).unwrap() else {panic!("array")};
        assert_eq!(rows.len(), 2);
        let Value::Record(first) = &rows[0] else {
            panic!("record")
        };
        assert_eq!(first.get("schedule"), Some(&Value::Str("0 1 * * *".into())));
        assert_eq!(
            first.get("command"),
            Some(&Value::Str("echo a  b=1".into()))
        );
        for text in [
            "0 1 * *",
            "0 1 * * * ",
            "@unknown command",
            "0 1 * * * echo ok\ninvalid",
        ] {
            assert!(parse_cron_listing(output(0, text.as_bytes(), b""), false)
                .unwrap_err()
                .to_string()
                .contains("E_BAD_STATE"));
        }
    }
    #[test]
    fn only_a_specific_absent_crontab_diagnostic_means_no_jobs() {
        assert!(
            matches!(parse_cron_listing(output(1,b"",b"no crontab for test\n"),false).unwrap(),Value::Array(a) if a.is_empty())
        );
        for (code, stdout, stderr, windows) in [
            (2, b"".as_slice(), b"no crontab for test".as_slice(), false),
            (1, b"unexpected", b"no crontab for test", false),
            (1, b"", b"permission denied: no crontab for test", false),
            (1, b"", b"no crontab for test", true),
        ] {
            assert!(parse_cron_listing(output(code, stdout, stderr), windows)
                .unwrap_err()
                .to_string()
                .contains("E_TOOL_FAILED"));
        }
        for windows in [false, true] {
            assert!(parse_cron_listing(output(0, b"\xff", b""), windows)
                .unwrap_err()
                .to_string()
                .contains("E_BAD_STATE"));
        }
    }
}

#[path = "scheduler.rs"]
mod scheduler;

fn bi_cron_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    scheduler::guard_and_add(args, input)
}

fn bi_cron_remove(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    guard_and_change_cron("cron_remove", args, input, "remove")
}

fn bi_cron_enable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    guard_and_change_cron("cron_enable", args, input, "enable")
}

fn bi_cron_disable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    guard_and_change_cron("cron_disable", args, input, "disable")
}

fn guard_and_change_cron(
    name: &str,
    args: Vec<Value>,
    input: Option<Value>,
    action: &str,
) -> Result<Value> {
    let [Value::Str(target)] = args.as_slice() else {
        return Err(crate::safety::arg_err(format!(
            "{name} requires one String target"
        )));
    };
    if input.is_some()
        || target.trim().is_empty()
        || target.contains(['\0', '\n', '\r'])
        || target.starts_with(['-', '/'])
        || target.len() > 65536
    {
        return Err(crate::safety::arg_err(
            "invalid scheduler target or pipeline input",
        ));
    }
    if cfg!(windows) && target.contains(['*', '?']) {
        return Err(crate::safety::arg_err(
            "scheduler target must name one task; wildcards are forbidden",
        ));
    }
    if cfg!(unix) {
        let parsed = parse_cron_listing(cron_success_output(target.as_bytes().to_vec()), false)
            .map_err(|_| crate::safety::arg_err("target must be one complete crontab job"))?;
        if !matches!(parsed, Value::Array(ref rows) if rows.len() == 1) {
            return Err(crate::safety::arg_err(
                "target must be one complete crontab job",
            ));
        }
    }
    if crate::tx::is_active() {
        return Err(crate::safety::unimplemented(
            name,
            "scheduler changes cannot be rolled back",
            "finish the transaction first",
        ));
    }
    if action == "enable" {
        crate::safety::guard_exec(name, format!("enable scheduled job: {target}"))?;
    } else {
        crate::safety::guard(crate::safety::GuardCtx {
            builtin: name,
            effect: crate::safety::effect_of(name),
            what: action,
            targets: vec![target.clone()],
            blast_radius: serde_json::json!({"scheduled_jobs": 1}),
            reversible: false,
            fs_paths: false,
        })?;
    }
    change_cron_backend(
        name,
        target,
        action,
        cfg!(windows),
        |tool, arguments, stdin| scheduler::run_tool(name, tool, arguments, stdin),
    )
}

// This lock serializes this process's read/modify/write operations. Other crontab
// clients can still race; the native user-crontab API has no compare-and-swap.
static CRON_CHANGE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn change_cron_backend(
    name: &str,
    target: &str,
    action: &str,
    windows: bool,
    mut run: impl FnMut(&str, &[&str], Option<&[u8]>) -> Result<std::process::Output>,
) -> Result<Value> {
    if windows && target.contains(['*', '?']) {
        return Err(crate::safety::arg_err(
            "scheduler target must name one task; wildcards are forbidden",
        ));
    }
    let _lock = CRON_CHANGE_LOCK.lock().map_err(|_| {
        crate::safety::bad_state_with_hint(name, "scheduler lock poisoned", "restart the runtime")
    })?;
    let check = |output: std::process::Output, tool: &str| -> Result<Vec<u8>> {
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                name,
                tool,
                output.status.code(),
                &String::from_utf8_lossy(&output.stderr),
            ));
        }
        Ok(output.stdout)
    };
    if windows {
        let arguments = match action {
            "remove" => vec!["/Delete", "/TN", target, "/F"],
            "enable" => vec!["/Change", "/TN", target, "/ENABLE"],
            "disable" => vec!["/Change", "/TN", target, "/DISABLE"],
            _ => return Err(crate::safety::arg_err("unknown scheduler action")),
        };
        check(run("schtasks", &arguments, None)?, "schtasks")?;
    } else {
        let bytes = check(run("crontab", &["-l"], None)?, "crontab")?;
        let text = std::str::from_utf8(&bytes).map_err(|_| {
            crate::safety::bad_state_with_hint(name, "non-UTF-8 crontab", "UTF-8 user crontab")
        })?;
        let replacement = transform_cron_entry(text, target, action)?;
        if replacement == text {
            return Ok(Value::Bool(true));
        }
        check(
            run("crontab", &["-"], Some(replacement.as_bytes()))?,
            "crontab",
        )?;
    }
    Ok(Value::Bool(true))
}

fn transform_cron_entry(text: &str, target: &str, action: &str) -> Result<String> {
    const DISABLED: &str = "# ironshell-disabled: ";
    if target.starts_with('#') || target.trim().is_empty() {
        return Err(crate::safety::arg_err(
            "target must be an active crontab entry, without a comment prefix",
        ));
    }
    // Validate the selected entry using the same parser as listing. It must be
    // exactly one job, never an environment assignment or a comment.
    let parsed = parse_cron_listing(cron_success_output(target.as_bytes().to_vec()), false)
        .map_err(|_| crate::safety::arg_err("target must be one complete crontab job"))?;
    if !matches!(parsed, Value::Array(ref rows) if rows.len() == 1) {
        return Err(crate::safety::arg_err(
            "target must be one complete crontab job",
        ));
    }
    let disabled = format!("{DISABLED}{target}");
    let matches = text
        .lines()
        .filter(|line| *line == target || *line == disabled)
        .count();
    if matches != 1 {
        return Err(crate::safety::bad_state_with_hint(
            "cron",
            &format!("expected one matching job, found {matches}"),
            "select a unique existing crontab entry",
        ));
    }
    let mut result = String::new();
    for line in text.split_inclusive('\n') {
        let entry = line.strip_suffix('\n').unwrap_or(line);
        if entry == target || entry == disabled {
            match action {
                "remove" => continue,
                "enable" => result.push_str(target),
                "disable" => result.push_str(&disabled),
                _ => return Err(crate::safety::arg_err("unknown scheduler action")),
            }
            if line.ends_with('\n') {
                result.push('\n');
            }
        } else {
            result.push_str(line);
        }
    }
    Ok(result)
}

fn cron_success_output(stdout: Vec<u8>) -> std::process::Output {
    #[cfg(unix)]
    let status = {
        use std::os::unix::process::ExitStatusExt;
        std::process::ExitStatus::from_raw(0)
    };
    #[cfg(windows)]
    let status = {
        use std::os::windows::process::ExitStatusExt;
        std::process::ExitStatus::from_raw(0)
    };
    std::process::Output {
        status,
        stdout,
        stderr: vec![],
    }
}

#[cfg(test)]
mod cron_mutation_tests {
    use super::*;
    #[test]
    fn transformations_preserve_unrelated_bytes_and_are_idempotent() {
        let job = "0 1 * * * echo hello";
        let text = format!("# owned comment\nPATH=/bin\n{job}\n@daily other");
        let disabled = transform_cron_entry(&text, job, "disable").unwrap();
        assert_eq!(
            disabled,
            format!("# owned comment\nPATH=/bin\n# ironshell-disabled: {job}\n@daily other")
        );
        assert_eq!(
            transform_cron_entry(&disabled, job, "disable").unwrap(),
            disabled
        );
        assert_eq!(
            transform_cron_entry(&disabled, job, "enable").unwrap(),
            text
        );
        assert_eq!(
            transform_cron_entry(&text, job, "remove").unwrap(),
            "# owned comment\nPATH=/bin\n@daily other"
        );
        for invalid in ["PATH=/bin", "# comment", "@unknown x"] {
            assert!(transform_cron_entry(&text, invalid, "remove").is_err());
        }
        assert!(transform_cron_entry(&format!("{job}\n{job}\n"), job, "remove").is_err());
        assert!(transform_cron_entry("", job, "remove").is_err());
    }
    #[test]
    fn failures_never_report_success_or_write_after_failed_read() {
        for windows in [true, false] {
            let mut calls = 0;
            let result = change_cron_backend(
                "cron_remove",
                "@daily echo test",
                "remove",
                windows,
                |_, _, _| {
                    calls += 1;
                    let mut output = cron_success_output(vec![]);
                    #[cfg(windows)]
                    {
                        use std::os::windows::process::ExitStatusExt;
                        output.status = std::process::ExitStatus::from_raw(1);
                    }
                    #[cfg(unix)]
                    {
                        use std::os::unix::process::ExitStatusExt;
                        output.status = std::process::ExitStatus::from_raw(256);
                    }
                    output.stderr = b"access denied".to_vec();
                    Ok(output)
                },
            );
            assert!(result.unwrap_err().to_string().contains("E_TOOL_FAILED"));
            assert_eq!(calls, 1);
        }
        for target in ["*", "\\Folder\\*"] {
            let result = change_cron_backend("cron_remove", target, "remove", true, |_, _, _| {
                panic!("wildcard reached native backend")
            });
            assert!(result.unwrap_err().to_string().contains("E_BAD_ARG"));
        }
    }
    #[test]
    fn native_backends_receive_exact_targets_and_checked_updates() {
        let job = "@daily echo hello";
        let mut calls = 0;
        assert_eq!(
            change_cron_backend(
                "cron_disable",
                job,
                "disable",
                false,
                |tool, args, stdin| {
                    assert_eq!(tool, "crontab");
                    calls += 1;
                    if calls == 1 {
                        assert_eq!(args, &["-l"]);
                        assert!(stdin.is_none());
                        Ok(cron_success_output(format!("{job}\n").into_bytes()))
                    } else {
                        assert_eq!(args, &["-"]);
                        assert_eq!(
                            stdin.unwrap(),
                            format!("# ironshell-disabled: {job}\n").as_bytes()
                        );
                        Ok(cron_success_output(vec![]))
                    }
                }
            )
            .unwrap(),
            Value::Bool(true)
        );
        assert_eq!(calls, 2);
        for (action, expected) in [
            ("remove", vec!["/Delete", "/TN", "\\Owned task", "/F"]),
            ("enable", vec!["/Change", "/TN", "\\Owned task", "/ENABLE"]),
            (
                "disable",
                vec!["/Change", "/TN", "\\Owned task", "/DISABLE"],
            ),
        ] {
            change_cron_backend("cron", "\\Owned task", action, true, |tool, args, stdin| {
                assert_eq!(tool, "schtasks");
                assert_eq!(args, expected);
                assert!(stdin.is_none());
                Ok(cron_success_output(vec![]))
            })
            .unwrap();
        }
    }
}

fn bi_at_schedule(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    scheduler::guard_and_schedule(args, input)
}

fn bi_at_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if !args.is_empty() || input.is_some() {
        return Err(crate::safety::arg_err(
            "at_list accepts no arguments or pipeline input",
        ));
    }
    #[cfg(unix)]
    {
        let mut cmd = crate::safety::child_command("atq");
        cmd.stdin(std::process::Stdio::null());
        let output = bounded_cmd_output("at_list", "atq", cmd, PROBE_DEADLINE_SECS)?;
        parse_at_queue(output)
    }
    #[cfg(windows)]
    {
        scheduler::list_windows_at()
    }
    #[cfg(not(any(unix, windows)))]
    {
        Err(crate::safety::unimplemented(
            "at_list",
            "unsupported scheduler platform",
            "use a supported platform",
        ))
    }
}

#[cfg(any(unix, test))]
fn parse_at_queue(output: std::process::Output) -> Result<Value> {
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "at_list",
            "atq",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    let malformed = || {
        crate::safety::bad_state_with_hint(
            "at_list",
            "unexpected atq output",
            "tab-separated job ID and schedule/queue/user layout",
        )
    };
    let text = String::from_utf8(output.stdout).map_err(|_| malformed())?;
    let mut jobs = Vec::new();
    for line in text.lines().filter(|l| !l.trim().is_empty()) {
        let (id, rest) = line.split_once('\t').ok_or_else(malformed)?;
        let id = id.trim();
        if id.is_empty()
            || !id.bytes().all(|b| b.is_ascii_digit())
            || id.parse::<u64>().ok().is_none_or(|n| n == 0)
        {
            return Err(malformed());
        }
        let tokens: Vec<_> = rest.split_whitespace().collect();
        if tokens.len() < 3 {
            return Err(malformed());
        }
        let mut rec = std::collections::BTreeMap::new();
        rec.insert("job_id".into(), Value::Str(id.into()));
        rec.insert("queue".into(), Value::Str(tokens[tokens.len() - 2].into()));
        rec.insert("user".into(), Value::Str(tokens[tokens.len() - 1].into()));
        // Keep the previous schedule field: the entire unparsed tail, including
        // queue and user. Date/locale normalization is not claimed.
        rec.insert("schedule".into(), Value::Str(rest.trim().into()));
        jobs.push(Value::Record(rec));
    }
    Ok(Value::Array(jobs))
}

#[cfg(all(test, any(unix, windows)))]
mod at_queue_contract_tests {
    use super::*;
    fn output(success: bool, bytes: &[u8]) -> std::process::Output {
        #[cfg(unix)]
        let status = {
            use std::os::unix::process::ExitStatusExt;
            std::process::ExitStatus::from_raw(if success { 0 } else { 256 })
        };
        #[cfg(windows)]
        let status = {
            use std::os::windows::process::ExitStatusExt;
            std::process::ExitStatus::from_raw(if success { 0 } else { 1 })
        };
        std::process::Output {
            status,
            stdout: bytes.to_vec(),
            stderr: b"permission denied".to_vec(),
        }
    }
    #[test]
    fn successful_empty_and_populated_queues_have_distinct_results() {
        assert!(
            matches!(parse_at_queue(output(true,b"  \n")).unwrap(),Value::Array(a) if a.is_empty())
        );
        let Value::Array(rows) =
            parse_at_queue(output(true, b"12\tFri Oct 2 10:00:00 2026   a   user  \n")).unwrap()
        else {
            panic!("expected array")
        };
        let Value::Record(row) = &rows[0] else {
            panic!("expected record")
        };
        assert_eq!(row.get("job_id"), Some(&Value::Str("12".into())));
        assert_eq!(row.get("queue"), Some(&Value::Str("a".into())));
        assert_eq!(row.get("user"), Some(&Value::Str("user".into())));
        assert_eq!(
            row.get("schedule"),
            Some(&Value::Str("Fri Oct 2 10:00:00 2026   a   user".into()))
        );
    }
    #[test]
    fn unsuccessful_queries_and_malformed_successes_are_coded() {
        for bytes in [b"".as_slice(), b"12\tdate a user", b"\xff"] {
            let err = parse_at_queue(output(false, bytes))
                .unwrap_err()
                .to_string();
            assert!(
                err.contains("E_TOOL_FAILED") && err.contains("permission denied"),
                "{err}"
            );
        }
        for bytes in [
            b"\xff".as_slice(),
            b"noise",
            b"0\tdate a user",
            b"x\tdate a user",
            b"1\ta user",
            b"1\tdate a user\nnoise",
        ] {
            let err = parse_at_queue(output(true, bytes)).unwrap_err().to_string();
            assert!(err.contains("E_BAD_STATE"), "{err}");
        }
    }
}

fn bi_at_remove(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    scheduler::guard_and_remove(args, input)
}

fn bi_startup_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd
            .args(["-Command", "Get-CimInstance Win32_StartupCommand | Select-Object Name,Command,Location | ConvertTo-Json"]);
        let output = bounded_cmd_output("startup_list", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                let items = match &json {
                    serde_json::Value::Array(arr) => arr.clone(),
                    obj @ serde_json::Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                let startup: Vec<Value> = items
                    .iter()
                    .filter_map(|obj| {
                        let o = obj.as_object()?;
                        let mut rec = std::collections::BTreeMap::new();
                        if let Some(v) = o.get("Name") {
                            rec.insert("name".to_string(), json_to_value(v.clone()));
                        }
                        if let Some(v) = o.get("Command") {
                            rec.insert("command".to_string(), json_to_value(v.clone()));
                        }
                        if let Some(v) = o.get("Location") {
                            rec.insert("location".to_string(), json_to_value(v.clone()));
                        }
                        Some(Value::Record(rec))
                    })
                    .collect();
                return Ok(Value::Array(startup));
            }
            // With no startup commands PowerShell prints nothing at all.
            if String::from_utf8_lossy(&output.stdout).trim().is_empty() {
                return Ok(Value::Array(vec![]));
            }
        }
        return Err(crate::safety::tool_failed(
            "startup_list",
            "powershell Get-CimInstance Win32_StartupCommand",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("systemctl");
        cmd.args([
            "list-unit-files",
            "--type=service",
            "--state=enabled",
            "--no-pager",
            "--no-legend",
        ]);
        let output = bounded_cmd_output("startup_list", "systemctl", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            let services: Vec<Value> = text
                .lines()
                .filter(|l| !l.trim().is_empty())
                .map(|l| {
                    let parts: Vec<&str> = l.split_whitespace().collect();
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert(
                        "name".to_string(),
                        Value::Str(parts.first().unwrap_or(&"").to_string()),
                    );
                    rec.insert(
                        "state".to_string(),
                        Value::Str(parts.get(1).unwrap_or(&"").to_string()),
                    );
                    Value::Record(rec)
                })
                .collect();
            return Ok(Value::Array(services));
        }
        // Without systemd (a container, WSL without it) systemctl fails; that
        // is not "nothing starts at boot".
        return Err(crate::safety::tool_failed(
            "startup_list",
            "systemctl list-unit-files",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("launchctl");
        cmd.args(["list"]);
        let output = bounded_cmd_output("startup_list", "launchctl", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            let services: Vec<Value> = text
                .lines()
                .skip(1) // skip header
                .filter(|l| !l.trim().is_empty())
                .map(|l| {
                    let parts: Vec<&str> = l.split('\t').collect();
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert(
                        "pid".to_string(),
                        Value::Str(parts.first().unwrap_or(&"").trim().to_string()),
                    );
                    rec.insert(
                        "exit_code".to_string(),
                        Value::Str(parts.get(1).unwrap_or(&"").trim().to_string()),
                    );
                    rec.insert(
                        "name".to_string(),
                        Value::Str(parts.get(2).unwrap_or(&"").trim().to_string()),
                    );
                    Value::Record(rec)
                })
                .collect();
            return Ok(Value::Array(services));
        }
        return Err(crate::safety::tool_failed(
            "startup_list",
            "launchctl list",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    // Every failure above, and every other operating system, used to land
    // here as `[]`: "nothing starts at boot", said without looking.
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "startup_list",
        "listing startup items is implemented for Windows, Linux (systemd) and macOS only; NOTHING WAS INSPECTED",
        "use this system's init tooling directly",
    ))
}

// ============================================================================
// 330-349: Archive & Compression
// ============================================================================

/// The file operands of a zip call: every argument after the archive, each of
/// which must be a string. At least one is required.
fn zip_file_args(builtin: &str, args: &[Value]) -> Result<Vec<String>> {
    let files = args
        .iter()
        .skip(1)
        .map(|v| match v {
            Value::Str(s) => Ok(s.clone()),
            other => Err(crate::safety::bad_arg(
                builtin,
                "a file name: String",
                other.type_name(),
            )),
        })
        .collect::<Result<Vec<String>>>()?;
    if files.is_empty() {
        return Err(crate::safety::bad_arg(
            builtin,
            "at least one file to add",
            "none",
        ));
    }
    Ok(files)
}

/// What a zip write has taken in so far: the entry names (a name may be stored
/// once), the source bytes read, and the entry count.
struct ZipBuild {
    names: std::collections::HashSet<String>,
    bytes: u64,
    entries: usize,
}

fn zip_write_error(builtin: &str, e: impl std::fmt::Display) -> anyhow::Error {
    crate::safety::io_fault(
        builtin,
        &format!("writing the zip archive failed: {e}"),
        "check the free space and that the archive's folder is writable",
    )
}

/// Take `name` for a new entry, refusing a second entry of the same name.
fn zip_claim_name(builtin: &str, st: &mut ZipBuild, name: &str) -> Result<()> {
    if !st.names.insert(name.to_string()) {
        return Err(crate::safety::bad_arg_with_hint(
            builtin,
            "members that are stored under different names",
            &format!("two members would both be stored as `{name}`"),
            "pass each file or folder once; members are stored under their last path component",
        ));
    }
    Ok(())
}

/// Add `fs_path`, a file or a whole folder, to `w` under `entry_name`. Empty
/// folders are kept as directory entries. A symlink to a folder is not followed.
fn zip_add_tree(
    builtin: &str,
    w: &mut zip::ZipWriter<std::fs::File>,
    fs_path: &std::path::Path,
    entry_name: &str,
    st: &mut ZipBuild,
) -> Result<()> {
    let shown = fs_path.to_string_lossy().into_owned();
    let meta =
        std::fs::metadata(fs_path).map_err(|e| crate::safety::fs_error(builtin, &shown, &e))?;
    st.entries += 1;
    if st.entries > WALK_MAX_ENTRIES {
        return Err(walk_over(builtin, WALK_MAX_ENTRIES));
    }
    let opts = zip::write::SimpleFileOptions::default()
        .compression_method(zip::CompressionMethod::Deflated);
    if meta.is_dir() {
        zip_claim_name(builtin, st, &format!("{entry_name}/"))?;
        w.add_directory(entry_name, opts)
            .map_err(|e| zip_write_error(builtin, e))?;
        let mut kids = Vec::new();
        for k in
            std::fs::read_dir(fs_path).map_err(|e| crate::safety::fs_error(builtin, &shown, &e))?
        {
            kids.push(k.map_err(|e| crate::safety::fs_error(builtin, &shown, &e))?);
        }
        kids.sort_by_key(|k| k.file_name());
        for k in kids {
            let p = k.path();
            let is_link = std::fs::symlink_metadata(&p)
                .map(|m| m.file_type().is_symlink())
                .unwrap_or(false);
            if is_link && p.is_dir() {
                continue;
            }
            let child = format!("{entry_name}/{}", k.file_name().to_string_lossy());
            zip_add_tree(builtin, w, &p, &child, st)?;
        }
        return Ok(());
    }
    zip_claim_name(builtin, st, entry_name)?;
    #[cfg(unix)]
    let opts = {
        use std::os::unix::fs::PermissionsExt as _;
        opts.unix_permissions(meta.permissions().mode() & 0o777)
    };
    w.start_file(entry_name, opts)
        .map_err(|e| zip_write_error(builtin, e))?;
    let mut src =
        std::fs::File::open(fs_path).map_err(|e| crate::safety::fs_error(builtin, &shown, &e))?;
    let n = std::io::copy(&mut src, w).map_err(|e| crate::safety::fs_error(builtin, &shown, &e))?;
    st.bytes = st.bytes.saturating_add(n);
    if st.bytes > FILE_OUTPUT_CAP {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("the members total more than {FILE_OUTPUT_CAP} bytes"),
            "nothing was written; archive fewer or smaller members",
        ));
    }
    Ok(())
}

/// Write `members` (each under its last path component) into `out`. With `old`,
/// the entries of that existing archive follow, except those the members
/// replace: this is `zip_add`'s update.
fn zip_write_archive(
    builtin: &str,
    out: std::fs::File,
    old: Option<&str>,
    members: &[String],
) -> Result<()> {
    let mut w = zip::ZipWriter::new(out);
    let mut st = ZipBuild {
        names: std::collections::HashSet::new(),
        bytes: 0,
        entries: 0,
    };
    for m in members {
        let p = std::path::Path::new(m);
        let leaf = p
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .or_else(|| {
                std::fs::canonicalize(p)
                    .ok()
                    .and_then(|c| c.file_name().map(|n| n.to_string_lossy().into_owned()))
            })
            .ok_or_else(|| {
                crate::safety::bad_arg(builtin, "a file or folder with a name", m.as_str())
            })?;
        zip_add_tree(builtin, &mut w, p, &leaf, &mut st)?;
    }
    if let Some(old) = old {
        let f = std::fs::File::open(old).map_err(|e| crate::safety::fs_error(builtin, old, &e))?;
        let mut src = zip::ZipArchive::new(f).map_err(|e| zip_not_an_archive(builtin, old, e))?;
        for i in 0..src.len() {
            let entry = src
                .by_index_raw(i)
                .map_err(|e| zip_not_an_archive(builtin, old, e))?;
            let name = entry
                .name()
                .map(|n| n.into_owned())
                .unwrap_or_else(|_| String::from_utf8_lossy(entry.name_raw()).into_owned());
            if st.names.contains(&name) {
                continue;
            }
            w.raw_copy_file(entry)
                .map_err(|e| zip_write_error(builtin, e))?;
        }
    }
    w.finish().map_err(|e| zip_write_error(builtin, e))?;
    Ok(())
}

/// The members of a zip call, resolved. Under an enforced workspace each must
/// lie inside it, and each must exist.
fn zip_resolve_members(builtin: &str, files: &[String]) -> Result<Vec<String>> {
    let enforce = crate::safety::current_mode() == crate::safety::Mode::Agent
        || std::env::var("IRONSHELL_WORKSPACE").is_ok();
    let mut out = Vec::with_capacity(files.len());
    for f in files {
        let m = crate::safety::resolve_path_str(f);
        if enforce && !crate::safety::within_workspace(&m) {
            return Err(crate::safety::policy_deny(
                builtin,
                format!("member '{m}' is outside the workspace"),
                "archive only paths inside the workspace",
            ));
        }
        if std::fs::metadata(&m).is_err() {
            return Err(crate::safety::not_found(builtin, "file", f));
        }
        out.push(m);
    }
    Ok(out)
}

// 330: bi_zip_create - Write a new zip archive from files.
//
// Written in-process: this used to run PowerShell's Compress-Archive, whose
// raw error text leaked out, which dropped empty folders, and which wrote
// no archive for a lone empty folder while the call answered true.
//
// An existing archive is refused rather than added to: that is zip_add's job.
// Every file operand must be a string, and at least one is required. Each
// member is stored under its last path component (a folder with everything
// inside it, empty folders included). A failed run removes the archive it
// started.
fn bi_zip_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("zip_create", &input)?;
    let archive = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "zip_create",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let files = zip_file_args("zip_create", &args)?;
    crate::safety::reject_option_like("zip_create", std::slice::from_ref(&archive))?;
    crate::safety::reject_option_like("zip_create", &files)?;
    let archive = guard_local_write("zip_create", &crate::safety::resolve_path_str(&archive))?;
    refuse_existing("zip_create", &archive)?;
    let members = zip_resolve_members("zip_create", &files)?;
    // The archive is new (refused above if it exists), so rollback removes it.
    crate::tx::snapshot(&archive);
    let out = create_new_output("zip_create", &archive)?;
    if let Err(e) = zip_write_archive("zip_create", out, None, &members) {
        remove_partial(&archive);
        return Err(e);
    }
    Ok(Value::Bool(true))
}

// Archive entries are checked before the extracting tool runs. The tool would
// write each member relative to the destination, so a member whose name is
// absolute, or climbs out with `..`, lands outside it ("zip slip"). A symlink
// or hard link whose target does the same is refused too, since a later member
// could then be written through it. Nothing is written if any entry is refused.

/// True when an archive entry name, or a link target, can resolve outside the
/// directory the archive is extracted into: an absolute path, a drive path
/// (`C:x`, `C:\x`), a UNC path, or any `..` component. Both `/` and `\` separate
/// components, because one archive may be extracted on either platform.
fn archive_entry_escapes(name: &str) -> bool {
    if name.starts_with('/') || name.starts_with('\\') {
        return true;
    }
    let b = name.as_bytes();
    if b.len() >= 2 && b[1] == b':' && b[0].is_ascii_alphabetic() {
        return true;
    }
    name.split(['/', '\\']).any(|part| part == "..")
}

/// Refuse the first entry, or link target, that would land outside the
/// destination, and any archive with more than `WALK_MAX_ENTRIES` entries.
/// Each item is an entry name and, for a symlink or hard link, its target.
fn check_archive_entries(
    builtin: &str,
    entries: impl Iterator<Item = (String, Option<String>)>,
) -> Result<()> {
    for (n, (name, target)) in entries.enumerate() {
        if n >= WALK_MAX_ENTRIES {
            return Err(walk_over(builtin, WALK_MAX_ENTRIES));
        }
        if archive_entry_escapes(&name) {
            return Err(refuse_archive_entry(builtin, &name));
        }
        // A member named like a Windows device would be written as a file
        // that cannot be deleted.
        if cfg!(windows) {
            if let Some(device) = crate::safety::reserved_device_name(&name) {
                return Err(anyhow::Error::new(crate::safety::reserved_device_error(
                    builtin, &device,
                )));
            }
        }
        if let Some(t) = target {
            if archive_entry_escapes(&t) {
                return Err(refuse_archive_entry(builtin, &name));
            }
        }
    }
    Ok(())
}

/// The most an archive may declare as uncompressed content before
/// `zip_extract` or `tar_extract` refuses it: the sum of its members' sizes.
const ARCHIVE_EXTRACT_MAX_BYTES: u64 = 4 * 1024 * 1024 * 1024;

/// Refuse an archive whose members declare more than `ARCHIVE_EXTRACT_MAX_BYTES`
/// in total, before anything is written. Declared sizes can lie: a zip's
/// uncompressed size and a tar header's size are written by whoever made the
/// archive, so a small archive can claim little and inflate to far more. This
/// bounds what the archive claims, not what the extracting tool writes. The
/// tool's deadline (`TOOL_LONG_DEADLINE_SECS`) is what bounds the work done.
fn check_archive_budget(builtin: &str, declared: u64) -> Result<()> {
    if declared > ARCHIVE_EXTRACT_MAX_BYTES {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!(
                "the archive declares {declared} bytes uncompressed, over the {ARCHIVE_EXTRACT_MAX_BYTES}-byte limit"
            ),
            "nothing was extracted; extract the parts you need, or split the archive",
        ));
    }
    Ok(())
}

/// Refuse an archive whose members, or whose links' targets, would land on a
/// path `guard` protects: the audit log, the governance files, or in agent
/// mode a `.git` directory. The extracting tool writes them where the
/// archive says, so `guard` never sees those paths; they are judged here,
/// against the resolved destination, before anything is written.
fn check_archive_protected(
    builtin: &str,
    dest: &str,
    entries: &[(String, Option<String>)],
) -> Result<()> {
    let root = std::path::Path::new(dest);
    for (name, target) in entries {
        let landing = root.join(name);
        let mut paths = vec![landing.clone()];
        if let Some(t) = target {
            paths.push(landing.parent().unwrap_or(root).join(t));
        }
        for p in paths {
            let p = p.to_string_lossy();
            if let Some(why) = crate::safety::protected_write_refusal(&p) {
                return Err(crate::safety::policy_deny(
                    builtin,
                    format!("{builtin}: entry `{name}` would write {p}, which is {why}"),
                    "the archive was refused before anything was written; extract it somewhere else or remove the entry",
                ));
            }
        }
    }
    Ok(())
}

/// The directories under `dir`'s first existing ancestor that do not exist yet,
/// outermost first, appended to `out` unless already there. The paths are in the
/// journal's spelling.
fn plan_missing_dirs(
    dir: &std::path::Path,
    seen: &mut std::collections::HashSet<String>,
    out: &mut Vec<String>,
) {
    let mut missing: Vec<std::path::PathBuf> = Vec::new();
    let mut cursor = Some(dir);
    while let Some(d) = cursor {
        if d.as_os_str().is_empty() || d.exists() {
            break;
        }
        missing.push(d.to_path_buf());
        cursor = d.parent();
    }
    for d in missing.into_iter().rev() {
        let p = crate::journal::normalized_path(&d.to_string_lossy());
        if seen.insert(p.clone()) {
            out.push(p);
        }
    }
}

/// Every path an extraction of `entries` (name, is-a-directory) under `root`
/// will create or overwrite, in the order the journal step must hold them: each
/// missing directory before what goes in it. Undo walks the step backwards, so
/// files go first and each created directory is removed innermost first, and
/// only while empty. Names are split as the extractors split them. An entry that
/// would escape `root` is left out (the extractors refuse it).
fn extraction_journal_paths(
    root: &std::path::Path,
    entries: impl Iterator<Item = (String, bool)>,
) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    plan_missing_dirs(root, &mut seen, &mut out);
    for (name, is_dir) in entries {
        if archive_entry_escapes(&name) {
            continue;
        }
        let mut target = root.to_path_buf();
        let mut any = false;
        for part in name
            .split(['/', '\\'])
            .filter(|p| !p.is_empty() && *p != ".")
        {
            target.push(part);
            any = true;
        }
        if !any {
            continue;
        }
        if is_dir {
            plan_missing_dirs(&target, &mut seen, &mut out);
            continue;
        }
        if let Some(parent) = target.parent() {
            plan_missing_dirs(parent, &mut seen, &mut out);
        }
        if target.is_dir() {
            continue;
        }
        let p = crate::journal::normalized_path(&target.to_string_lossy());
        if seen.insert(p.clone()) {
            out.push(p);
        }
    }
    out
}

fn refuse_archive_entry(builtin: &str, name: &str) -> anyhow::Error {
    crate::safety::policy_deny(
        builtin,
        format!("{builtin}: entry `{name}` would land outside the destination"),
        "the archive was refused before anything was written; remove the entry \
         or rebuild the archive with relative paths that stay inside it",
    )
}

/// Largest symlink target read from a zip entry. Longer targets are not read in
/// full; they are refused as if absolute.
const ARCHIVE_LINK_TARGET_MAX: u64 = 4096;

/// List every entry of a zip archive, with the target of each symlink entry.
/// The zip format stores a symlink as a member whose unix mode is `S_IFLNK` and
/// whose content is the target path.
/// The read jail for an archive a builtin opens. Extracting is an import: the
/// archive may come from outside the workspace, as `file_copy` may copy a file
/// in, and every member it writes is still checked against the workspace.
/// Listing or inspecting an archive is a read, and is refused outside it.
fn archive_source_jail(builtin: &str, archive: &str) -> Result<()> {
    if builtin.ends_with("_extract") {
        return Ok(());
    }
    crate::security::check_read_jail(builtin, archive)
}

fn zip_archive_entries(
    builtin: &str,
    archive: &str,
) -> Result<(Vec<(String, Option<String>)>, u64)> {
    use std::io::Read as _;
    archive_source_jail(builtin, archive)?;
    let file =
        std::fs::File::open(archive).map_err(|e| crate::safety::fs_error(builtin, archive, &e))?;
    let mut zip =
        zip::ZipArchive::new(file).map_err(|e| zip_not_an_archive(builtin, archive, e))?;
    if zip.len() > WALK_MAX_ENTRIES {
        return Err(walk_over(builtin, WALK_MAX_ENTRIES));
    }
    let mut out = Vec::with_capacity(zip.len());
    let mut declared: u64 = 0;
    for i in 0..zip.len() {
        let mut entry = zip.by_index(i).map_err(|e| {
            crate::safety::tool_failed(builtin, "zip", None, &format!("unreadable entry: {e}"))
        })?;
        declared = declared.saturating_add(entry.size());
        let name = entry
            .name()
            .map(|n| n.into_owned())
            .unwrap_or_else(|_| String::from_utf8_lossy(entry.name_raw()).into_owned());
        let is_link = matches!(entry.unix_mode(), Some(m) if m & 0o170000 == 0o120000);
        let target = if is_link {
            let mut buf = Vec::new();
            std::io::Read::take(&mut entry, ARCHIVE_LINK_TARGET_MAX + 1)
                .read_to_end(&mut buf)
                .map_err(|e| {
                    crate::safety::tool_failed(
                        builtin,
                        "zip",
                        None,
                        &format!("unreadable link: {e}"),
                    )
                })?;
            if buf.len() as u64 > ARCHIVE_LINK_TARGET_MAX {
                Some("/".to_string())
            } else {
                Some(String::from_utf8_lossy(&buf).into_owned())
            }
        } else {
            None
        };
        out.push((name, target));
    }
    Ok((out, declared))
}

/// The member names of a compressed tar archive, as `tar -tf` lists them. The
/// sizes are not listed, so the declared total is 0: `tar -tf` gives no size.
fn tar_tool_entry_names(
    builtin: &str,
    archive: &str,
) -> Result<(Vec<(String, Option<String>)>, u64)> {
    crate::safety::reject_option_like(builtin, &[archive.to_string()])?;
    let mut cmd = crate::safety::child_command("tar");
    cmd.arg("-tf").arg(archive);
    let out = bounded_cmd_output(builtin, "tar", cmd, TOOL_DEADLINE_SECS)?;
    if !out.status.success() {
        return Err(crate::safety::tool_failed(
            builtin,
            "tar -tf",
            out.status.code(),
            &String::from_utf8_lossy(&out.stderr),
        ));
    }
    let text = String::from_utf8_lossy(&out.stdout);
    let mut names = Vec::new();
    for line in text.lines().filter(|l| !l.is_empty()) {
        if names.len() >= WALK_MAX_ENTRIES {
            return Err(walk_over(builtin, WALK_MAX_ENTRIES));
        }
        names.push((line.to_string(), None));
    }
    Ok((names, 0))
}

/// The program that decompresses a bzip2, xz or zstd stream, by its first two
/// bytes.
fn tar_stream_decompressor(magic: [u8; 2]) -> Option<&'static str> {
    match magic {
        [0x42, 0x5a] => Some("bzip2"), // "BZ"
        [0xfd, 0x37] => Some("xz"),
        [0x28, 0xb5] => Some("zstd"),
        _ => None,
    }
}

/// List a bzip2, xz or zstd tar by streaming it through its decompressor into
/// the in-process reader, so symlink and hard-link targets are checked as they
/// are for gzip. `None` when the decompressor is not installed: bsdtar has
/// these formats built in and needs no separate program. Past the tool deadline
/// the decompressor is killed and the call is a budget error.
fn tar_decompressed_entries(
    builtin: &str,
    archive: &str,
    tool: &str,
) -> Result<Option<(Vec<(String, Option<String>)>, u64)>> {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};
    crate::safety::reject_option_like(builtin, &[archive.to_string()])?;
    let mut decoder = crate::safety::child_command(tool);
    crate::safety::strip_ironshell_env(&mut decoder);
    let mut child = match decoder
        .arg("-dc")
        .arg("--")
        .arg(archive)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
    {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(crate::safety::spawn_error(builtin, tool, &e)),
    };
    let mut stdout = child.stdout.take().expect("stdout is piped");
    let child = Arc::new(Mutex::new(child));
    let done = Arc::new(AtomicBool::new(false));
    let timed_out = Arc::new(AtomicBool::new(false));
    let watcher = {
        let (child, done, timed_out) = (child.clone(), done.clone(), timed_out.clone());
        std::thread::spawn(move || {
            let start = std::time::Instant::now();
            while !done.load(Ordering::SeqCst) {
                if start.elapsed() >= std::time::Duration::from_secs(TOOL_DEADLINE_SECS) {
                    timed_out.store(true, Ordering::SeqCst);
                    let _ = child.lock().unwrap_or_else(|e| e.into_inner()).kill();
                    return;
                }
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
        })
    };
    // Read to the end, past the tar's end-of-archive blocks, so the exit status
    // says whether the whole stream decompressed.
    let listed = read_tar_entries(builtin, &mut stdout).and_then(|v| {
        std::io::copy(&mut stdout, &mut std::io::sink())
            .map(|_| v)
            .map_err(|e| crate::safety::tool_failed(builtin, tool, None, &e.to_string()))
    });
    done.store(true, Ordering::SeqCst);
    let _ = watcher.join();
    let status = {
        let mut c = child.lock().unwrap_or_else(|e| e.into_inner());
        if listed.is_err() {
            let _ = c.kill();
        }
        c.wait()
            .map_err(|e| crate::safety::spawn_error(builtin, tool, &e))?
    };
    if timed_out.load(Ordering::SeqCst) {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{tool}` did not finish within {TOOL_DEADLINE_SECS} s"),
            "nothing was extracted; the archive was not checked in time",
        ));
    }
    let listed = listed?;
    if !status.success() {
        return Err(crate::safety::tool_failed(
            builtin,
            tool,
            status.code(),
            "the stream did not decompress cleanly",
        ));
    }
    Ok(Some(listed))
}

/// List every entry of a tar archive, with the target of each symlink and hard
/// link. See `tar_archive_listing` for the declared sizes.
fn tar_archive_entries(builtin: &str, archive: &str) -> Result<Vec<(String, Option<String>)>> {
    Ok(tar_archive_listing(builtin, archive)?.0)
}

/// The entries of a tar archive, and the total of their declared sizes. A plain
/// or gzip-compressed tar is read in-process. A bzip2, xz or zstd stream is read
/// in-process through its decompressor; where that program is not installed,
/// only its member names are checked, as `tar -tf` lists them, and no size is
/// known, so the declared total for that case is 0.
fn tar_archive_listing(
    builtin: &str,
    archive: &str,
) -> Result<(Vec<(String, Option<String>)>, u64)> {
    use std::io::{Read, Seek, SeekFrom};
    archive_source_jail(builtin, archive)?;
    let mut file =
        std::fs::File::open(archive).map_err(|e| crate::safety::fs_error(builtin, archive, &e))?;
    let mut magic = [0u8; 2];
    let n = file
        .read(&mut magic)
        .map_err(|e| crate::safety::fs_error(builtin, archive, &e))?;
    file.seek(SeekFrom::Start(0))
        .map_err(|e| crate::safety::fs_error(builtin, archive, &e))?;
    let reader: Box<dyn Read> = if n == 2 && magic == [0x1f, 0x8b] {
        Box::new(flate2::read::GzDecoder::new(file))
    } else if let Some(tool) = tar_stream_decompressor(magic).filter(|_| n == 2) {
        drop(file);
        if let Some(listed) = tar_decompressed_entries(builtin, archive, tool)? {
            return Ok(listed);
        }
        // No decompressor on PATH, so the names come from the tar that will
        // extract them. Link targets are not listed this way; the tool's own
        // protection (GNU tar and bsdtar strip leading `/`, refuse `..`
        // members, and delay symlinks) covers those.
        return tar_tool_entry_names(builtin, archive);
    } else {
        Box::new(file)
    };
    read_tar_entries(builtin, reader)
}

/// Every entry of an uncompressed tar stream, with the target of each symlink
/// and hard link.
fn read_tar_entries<R: std::io::Read>(
    builtin: &str,
    reader: R,
) -> Result<(Vec<(String, Option<String>)>, u64)> {
    let mut ar = tar::Archive::new(reader);
    let entries = ar.entries().map_err(|e| {
        crate::safety::tool_failed(builtin, "tar", None, &format!("not a tar archive: {e}"))
    })?;
    let mut out = Vec::new();
    let mut declared: u64 = 0;
    for entry in entries {
        if out.len() >= WALK_MAX_ENTRIES {
            return Err(walk_over(builtin, WALK_MAX_ENTRIES));
        }
        let entry = entry.map_err(|e| {
            crate::safety::tool_failed(builtin, "tar", None, &format!("unreadable entry: {e}"))
        })?;
        declared = declared.saturating_add(entry.size());
        let name = entry
            .path()
            .map_err(|e| crate::safety::tool_failed(builtin, "tar", None, &e.to_string()))?
            .to_string_lossy()
            .into_owned();
        let ty = entry.header().entry_type();
        let target = if ty.is_symlink() || ty.is_hard_link() {
            entry
                .link_name()
                .map_err(|e| crate::safety::tool_failed(builtin, "tar", None, &e.to_string()))?
                .map(|p| p.to_string_lossy().into_owned())
        } else {
            None
        };
        out.push((name, target));
    }
    Ok((out, declared))
}

fn bi_zip_extract(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let archive = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "zip_extract",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let dest = args
        .get(1)
        .and_then(|v| match v {
            Value::Str(s) => Some(s.clone()),
            _ => None,
        })
        .unwrap_or(".".to_string());
    // Extraction writes every member of the archive, which is not known until
    // it runs, so the journal cannot snapshot them.
    refuse_in_transaction("zip_extract", "extracting an archive cannot be rolled back")?;
    // Refuse a member that would land outside the destination before anything
    // is written.
    let (members, declared) = zip_archive_entries("zip_extract", &archive)?;
    check_archive_entries("zip_extract", members.iter().cloned())?;
    check_archive_budget("zip_extract", declared)?;
    crate::safety::reject_option_like("zip_extract", std::slice::from_ref(&archive))?;
    crate::safety::reject_option_like("zip_extract", std::slice::from_ref(&dest))?;
    let dest = guard_local_write("zip_extract", &dest)?;
    check_archive_protected("zip_extract", &dest, &members)?;
    zip_extract_in_process(&archive, &dest)?;
    Ok(Value::Bool(true))
}

/// Writes every member of a zip archive under `dest`, in-process. This used to
/// run Expand-Archive or unzip, which on the hosts that found it exited 0 with
/// nothing written: the call said `true` and the destination was empty. Here
/// what was written is counted, so success is never claimed for a non-empty
/// archive that produced nothing.
///
/// Every entry name is checked again as it is written (`archive_entry_escapes`),
/// a component holding `:` is refused on Windows (an alternate data stream), and
/// symlink entries are not created, since a later member could be written
/// through one.
fn zip_extract_in_process(archive: &str, dest: &str) -> Result<()> {
    use std::io::Read as _;
    const B: &str = "zip_extract";
    refuse_in_transaction(B, "extracting an archive cannot be rolled back")?;
    let file = std::fs::File::open(archive).map_err(|e| crate::safety::fs_error(B, archive, &e))?;
    let mut zip = zip::ZipArchive::new(file).map_err(|e| zip_not_an_archive(B, archive, e))?;
    let root = std::path::Path::new(dest);
    // One journal step for everything this call writes, recorded before the
    // first byte: each file it creates (undo removes it) or overwrites (undo
    // puts the bytes back), and each directory it creates. The archive is only
    // read, so it is not in the step.
    if crate::journal::enabled() {
        let mut listed: Vec<(String, bool)> = Vec::new();
        for i in 0..zip.len() {
            let f = zip
                .by_index_raw(i)
                .map_err(|e| zip_not_an_archive(B, archive, e))?;
            let name = f
                .name()
                .map(|n| n.into_owned())
                .unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned());
            if f.is_symlink() {
                continue;
            }
            let is_dir = f.is_dir() || name.ends_with('/') || name.ends_with('\\');
            listed.push((name, is_dir));
        }
        crate::journal::record_group(
            B,
            crate::safety::Effect::WriteLocal,
            extraction_journal_paths(root, listed.into_iter()),
        );
    }
    std::fs::create_dir_all(root).map_err(|e| crate::safety::fs_error(B, dest, &e))?;
    let mut written: usize = 0;
    let mut links: usize = 0;
    let mut total: u64 = 0;
    for i in 0..zip.len() {
        let mut entry = zip
            .by_index(i)
            .map_err(|e| zip_not_an_archive(B, archive, e))?;
        let name = entry
            .name()
            .map(|n| n.into_owned())
            .unwrap_or_else(|_| String::from_utf8_lossy(entry.name_raw()).into_owned());
        if archive_entry_escapes(&name) {
            return Err(refuse_archive_entry(B, &name));
        }
        let parts: Vec<&str> = name
            .split(['/', '\\'])
            .filter(|p| !p.is_empty() && *p != ".")
            .collect();
        if cfg!(target_os = "windows") && parts.iter().any(|p| p.contains(':')) {
            return Err(refuse_archive_entry(B, &name));
        }
        if parts.is_empty() {
            continue;
        }
        let mut target = root.to_path_buf();
        for p in &parts {
            target.push(p);
        }
        if entry.is_dir() || name.ends_with('/') || name.ends_with('\\') {
            std::fs::create_dir_all(&target)
                .map_err(|e| crate::safety::fs_error(B, &target, &e))?;
            written += 1;
            continue;
        }
        if entry.is_symlink() {
            links += 1;
            continue;
        }
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent).map_err(|e| crate::safety::fs_error(B, parent, &e))?;
        }
        let shown = target.to_string_lossy().into_owned();
        let mut out = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&target)
            .map_err(|e| crate::safety::fs_error(B, &shown, &e))?;
        let room = ARCHIVE_EXTRACT_MAX_BYTES.saturating_sub(total);
        let n = std::io::copy(&mut (&mut entry).take(room.saturating_add(1)), &mut out)
            .map_err(|e| zip_not_an_archive(B, archive, e))?;
        total = total.saturating_add(n);
        check_archive_budget(B, total)?;
        written += 1;
    }
    if written == 0 && links > 0 {
        return Err(crate::safety::bad_state_with_hint(
            B,
            "the archive holds only symbolic links, which are not extracted",
            "nothing was written; extract it with tar or unzip if links are wanted",
        ));
    }
    Ok(())
}

/// The error for a file that is not a readable zip archive: `E_BAD_ARG`, as
/// `zip_list` answers, rather than a tool failure.
fn zip_not_an_archive(builtin: &str, archive: &str, e: impl std::fmt::Display) -> anyhow::Error {
    crate::safety::bad_arg_with_hint(
        builtin,
        "a zip archive",
        &format!("not a zip archive: {archive}: {e}"),
        "the file is damaged or is not a .zip; check its path and how it was made",
    )
}

// 333: bi_zip_add - Add or refresh files in an existing zip archive.
//
// The archive must already exist; a missing one is E_NOT_FOUND, not a new file.
// A member whose name the archive already holds replaces that entry. The
// archive is rewritten beside itself and moved into place, so a failed run
// leaves the original untouched.
fn bi_zip_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("zip_add", &input)?;
    let archive = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "zip_add",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let files = zip_file_args("zip_add", &args)?;
    crate::safety::reject_option_like("zip_add", std::slice::from_ref(&archive))?;
    crate::safety::reject_option_like("zip_add", &files)?;
    let archive = guard_local_write("zip_add", &crate::safety::resolve_path_str(&archive))?;
    if !std::path::Path::new(&archive).is_file() {
        return Err(crate::safety::not_found("zip_add", "archive", &archive));
    }
    let members = zip_resolve_members("zip_add", &files)?;
    // The one existing archive is rewritten in place.
    crate::tx::snapshot(&archive);
    // The journal keeps the archive's previous bytes; undo writes them back.
    crate::journal::record_group(
        "zip_add",
        crate::safety::Effect::WriteLocal,
        vec![archive.clone()],
    );
    let tmp = format!("{archive}.ish-tmp-{}", std::process::id());
    let out = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&tmp)
        .map_err(|e| crate::safety::fs_error("zip_add", &tmp, &e))?;
    if let Err(e) = zip_write_archive("zip_add", out, Some(&archive), &members) {
        remove_partial(&tmp);
        return Err(e);
    }
    if let Err(e) = std::fs::rename(&tmp, &archive) {
        remove_partial(&tmp);
        return Err(crate::safety::fs_error("zip_add", &archive, &e));
    }
    Ok(Value::Bool(true))
}

// The archive is written to a new file: tar streams it to stdout (`-f -`) and
// the bytes go through `tool_to_new_file`. That refuses an existing archive
// instead of truncating it, jails the destination, caps the size and the
// deadline, and removes a partial archive on failure. The member list is not
// echoed (no `-v`), so the output is not unbounded.
//
// Members are archived as links, not followed: tar is run without `-h` and
// `--dereference`. Under an enforced workspace every member must lie inside it,
// so a symlink an argument reaches cannot pull in a file from outside.
fn bi_tar_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("tar_create", &input)?;
    let archive = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "tar_create",
                "String",
                other.map_or("nothing", |v| v.type_name()),
            ))
        }
    };
    if args.len() < 2 {
        return Err(crate::safety::bad_arg(
            "tar_create",
            "an archive path, then at least one member path",
            "no members",
        ));
    }
    let mut files: Vec<String> = Vec::with_capacity(args.len() - 1);
    for (i, v) in args.iter().enumerate().skip(1) {
        match v {
            Value::Str(s) => files.push(s.clone()),
            other => {
                return Err(crate::safety::bad_arg(
                    "tar_create",
                    &format!("args[{i}]: a member path string"),
                    other.type_name(),
                ))
            }
        }
    }

    // Every name goes to tar positionally, so a leading `-` is an option.
    refuse_option("tar_create", &archive)?;
    crate::safety::reject_option_like("tar_create", &files)?;

    // The archive is a plain tar, or gzipped tar for .tar.gz and .tgz. Any other
    // extension would name a file that is not what it says, so it is refused.
    // A name with no extension is still a plain tar.
    let file_name = archive.rsplit(['/', '\\']).next().unwrap_or(&archive);
    if let Some((_, ext)) = file_name
        .rsplit_once('.')
        .filter(|(stem, _)| !stem.is_empty())
    {
        let lower = file_name.to_ascii_lowercase();
        if !(lower.ends_with(".tar") || lower.ends_with(".tar.gz") || lower.ends_with(".tgz")) {
            let hint = if ext.eq_ignore_ascii_case("zip") {
                "tar_create writes tar, not zip; use zip_create(archive, members) for a .zip archive"
            } else {
                "name the archive .tar, .tar.gz or .tgz (tar_create writes gzip only for .tar.gz and .tgz)"
            };
            return Err(crate::safety::bad_arg_with_hint(
                "tar_create",
                "an archive named .tar, .tar.gz or .tgz",
                &format!("'{archive}'"),
                hint,
            ));
        }
    }

    let enforce = crate::safety::current_mode() == crate::safety::Mode::Agent
        || std::env::var("IRONSHELL_WORKSPACE").is_ok();
    let members: Vec<String> = files
        .iter()
        .map(|f| crate::safety::resolve_path_str(f))
        .collect();
    for m in &members {
        if enforce && !crate::safety::within_workspace(m) {
            return Err(crate::safety::policy_deny(
                "tar_create",
                format!("member '{m}' is outside the workspace"),
                "archive only paths inside the workspace",
            ));
        }
    }
    // tar is run on the resolved paths, and on Windows a missing one comes back
    // as a garbled "Couldn't visit directory" line. Each member must exist first,
    // checked as tar sees it. symlink_metadata, not exists: tar archives a link
    // itself, so a dangling link is a member. A remote share is left to tar.
    for (f, m) in files.iter().zip(&members) {
        if !crate::safety::names_a_remote_share(m) && std::fs::symlink_metadata(m).is_err() {
            return Err(crate::safety::not_found("tar_create", "file", f));
        }
    }

    let out = guard_local_write("tar_create", &archive)?;
    // Each member is stored under a relative name (see `tar_member_name`), so
    // extraction does not recreate the absolute tree it came from. tar is told
    // where to find each one with `-C`.
    let placed: Vec<(String, String)> = members.iter().map(|m| tar_member_name(m)).collect();
    let mut argv: Vec<&str> = vec!["-c", "-f", "-"];
    let mut dir_now: Option<&str> = None;
    for (dir, name) in &placed {
        if dir_now != Some(dir.as_str()) {
            argv.push("-C");
            argv.push(dir.as_str());
            dir_now = Some(dir.as_str());
        }
        argv.push(name.as_str());
    }
    // A .tar.gz or .tgz name gets a gzipped stream, which tar_list and
    // tar_extract read back. The plain tar stream was written under that name.
    if archive_kind(&archive) == Some("tar.gz") {
        tool_to_new_gzip_file("tar_create", "tar", &argv, &out)?;
    } else {
        tool_to_new_file("tar_create", "tar", &argv, &out)?;
    }
    Ok(Value::Bool(true))
}

/// How `tar_create` stores one member: the directory tar is run from, and the
/// name it stores. A member inside the current directory is stored as its path
/// from it (normalised, so `./a/../b` is `b`, and never with `..`); one outside
/// it, or the current directory itself, under its last component, with its tree
/// below that for a folder. The name never starts with `-`, so tar reads it as a
/// name, and always uses `/`.
fn tar_member_name(member: &str) -> (String, String) {
    let base = crate::journal::normalized_path(&crate::safety::resolve_path_str("."));
    let abs = crate::journal::normalized_path(member);
    let abs_path = std::path::Path::new(&abs);
    let (dir, name) = match abs_path
        .strip_prefix(&base)
        .ok()
        .filter(|rel| rel.components().next().is_some())
    {
        Some(rel) => (base.clone(), rel.to_path_buf()),
        None => match (abs_path.parent(), abs_path.file_name()) {
            (Some(parent), Some(last)) => (
                parent.to_string_lossy().into_owned(),
                std::path::PathBuf::from(last),
            ),
            _ => (abs.clone(), std::path::PathBuf::from(".")),
        },
    };
    let parts: Vec<String> = name
        .components()
        .filter_map(|c| match c {
            std::path::Component::Normal(p) => Some(p.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect();
    let mut name = if parts.is_empty() {
        ".".to_string()
    } else {
        parts.join("/")
    };
    if name.starts_with('-') {
        name = format!("./{name}");
    }
    (dir, name)
}

fn bi_tar_extract(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let archive = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "tar_extract",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let dest = args.get(1).and_then(|v| match v {
        Value::Str(s) => Some(s.clone()),
        _ => None,
    });

    crate::safety::reject_option_like("tar_extract", std::slice::from_ref(&archive))?;
    // Extraction writes every member of the archive, which is not known until
    // it runs, so the journal cannot snapshot them.
    refuse_in_transaction("tar_extract", "extracting an archive cannot be rolled back")?;
    // Refuse a member, or a link, that would land outside the destination before
    // tar writes anything.
    let (members, declared) = tar_archive_listing("tar_extract", &archive)?;
    check_archive_entries("tar_extract", members.iter().cloned())?;
    check_archive_budget("tar_extract", declared)?;
    let mut cmd = crate::safety::child_command("tar");
    cmd.args(["-xvf", &archive]);
    // The journal step for the files and directories this call writes: see
    // `extraction_journal_paths`. Recorded after the jail has passed, before the
    // destination is created or anything is written. The archive is not in it.
    let journal_step = |root: &str| {
        if crate::journal::enabled() {
            crate::journal::record_group(
                "tar_extract",
                crate::safety::Effect::WriteLocal,
                extraction_journal_paths(
                    std::path::Path::new(root),
                    members
                        .iter()
                        .map(|(n, _)| (n.clone(), n.ends_with('/') || n.ends_with('\\'))),
                ),
            );
        }
    };
    if let Some(d) = dest {
        crate::safety::reject_option_like("tar_extract", std::slice::from_ref(&d))?;
        // The central check judges only paths that already exist. A `-C`
        // target usually does, but not always, so the destination is jailed
        // here where its meaning is known.
        let d = guard_local_write("tar_extract", &d)?;
        check_archive_protected("tar_extract", &d, &members)?;
        // unzip and Expand-Archive create a missing destination; `tar -C` fails
        // on one ("could not chdir"), so it is created here, after the jail.
        journal_step(&d);
        std::fs::create_dir_all(&d).map_err(|e| crate::safety::fs_error("tar_extract", &d, &e))?;
        cmd.args(["-C", &d]);
    } else {
        check_archive_protected("tar_extract", ".", &members)?;
        journal_step(".");
    }
    // Archives can be large; extraction is bounded by the long deadline.
    let output = bounded_cmd_output("tar_extract", "tar", cmd, TOOL_LONG_DEADLINE_SECS)?;
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "tar_extract",
            "tar",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    Ok(Value::Bool(true))
}

/// What an archive's name says it is: "zip", "tar", "tar.gz", "gzip",
/// "bzip2", "xz", "zstd", or None.
fn archive_kind(path: &str) -> Option<&'static str> {
    let p = path.to_ascii_lowercase();
    Some(if p.ends_with(".zip") {
        "zip"
    } else if p.ends_with(".tar.gz") || p.ends_with(".tgz") {
        "tar.gz"
    } else if p.ends_with(".tar") {
        "tar"
    } else if p.ends_with(".gz") {
        "gzip"
    } else if p.ends_with(".bz2") {
        "bzip2"
    } else if p.ends_with(".xz") {
        "xz"
    } else if p.ends_with(".zst") {
        "zstd"
    } else {
        return None;
    })
}

fn archive_path_arg(builtin: &str, args: &[Value]) -> Result<String> {
    match args.first() {
        Some(Value::Str(s)) => Ok(s.clone()),
        other => Err(crate::safety::bad_arg(
            builtin,
            "path: String",
            other.map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

fn archive_open(builtin: &str, path: &str) -> Result<std::fs::File> {
    crate::security::check_read_jail(builtin, path)?;
    std::fs::File::open(path).map_err(|e| crate::safety::fs_error(builtin, path, &e))
}

fn archive_corrupt(builtin: &str, path: &str, e: impl std::fmt::Display) -> anyhow::Error {
    crate::safety::bad_arg(builtin, "a readable archive", &format!("{path}: {e}"))
}

/// The entries of a tar or tar.gz archive, as {path, size, kind}.
fn tar_entries(builtin: &str, path: &str, gz: bool) -> Result<Vec<Value>> {
    let f = archive_open(builtin, path)?;
    let reader: Box<dyn std::io::Read> = if gz {
        Box::new(flate2::read::GzDecoder::new(f))
    } else {
        Box::new(f)
    };
    let mut ar = tar::Archive::new(reader);
    let mut out = Vec::new();
    for entry in ar
        .entries()
        .map_err(|e| archive_corrupt(builtin, path, e))?
    {
        let entry = entry.map_err(|e| archive_corrupt(builtin, path, e))?;
        let h = entry.header();
        // A header or name that cannot be read used to become an entry with an
        // empty path and size 0. The archive is refused instead.
        let entry_path = entry
            .path()
            .map_err(|e| archive_corrupt(builtin, path, e))?
            .to_string_lossy()
            .to_string();
        let size = h.size().map_err(|e| archive_corrupt(builtin, path, e))?;
        let mut r = BTreeMap::new();
        r.insert("path".to_string(), Value::Str(entry_path));
        r.insert("size".to_string(), Value::Int(size as i64));
        let kind = match h.entry_type() {
            tar::EntryType::Directory => "dir",
            tar::EntryType::Symlink | tar::EntryType::Link => "link",
            _ => "file",
        };
        r.insert("kind".to_string(), Value::Str(kind.to_string()));
        out.push(Value::Record(r));
    }
    Ok(out)
}

fn bi_tar_list(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // In-process. This returned `tar -tvf`'s text verbatim and ignored its
    // exit status, so a missing or damaged archive answered "".
    let path = archive_path_arg("tar_list", &args)?;
    let gz = matches!(archive_kind(&path), Some("tar.gz"));
    Ok(Value::Array(tar_entries("tar_list", &path, gz)?))
}

fn bi_zip_list(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // In-process. The Unix branch parsed `unzip -l` and dropped every line
    // containing "files" -- meant for the summary line, it also removed
    // entries such as src/files.rs -- and every failure answered [].
    let path = archive_path_arg("zip_list", &args)?;
    let mut z = zip::ZipArchive::new(archive_open("zip_list", &path)?)
        .map_err(|e| archive_corrupt("zip_list", &path, e))?;
    let mut out = Vec::new();
    for i in 0..z.len() {
        let f = z
            .by_index_raw(i)
            .map_err(|e| archive_corrupt("zip_list", &path, e))?;
        let mut r = BTreeMap::new();
        let name = f
            .name()
            .map(|n| n.into_owned())
            .unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned());
        r.insert("name".to_string(), Value::Str(name));
        r.insert("size".to_string(), Value::Int(f.size() as i64));
        r.insert(
            "compressed_size".to_string(),
            Value::Int(f.compressed_size() as i64),
        );
        r.insert("dir".to_string(), Value::Bool(f.is_dir()));
        out.push(Value::Record(r));
    }
    Ok(Value::Array(out))
}

fn bi_archive_info(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // A file that did not exist still answered {path, type}.
    let path = archive_path_arg("archive_info", &args)?;
    crate::security::check_read_jail("archive_info", &path)?;
    let meta =
        std::fs::metadata(&path).map_err(|e| crate::safety::fs_error("archive_info", &path, &e))?;
    let mut rec = BTreeMap::new();
    rec.insert("path".to_string(), Value::Str(path.clone()));
    rec.insert(
        "type".to_string(),
        archive_kind(&path)
            .map(|k| Value::Str(k.to_string()))
            .unwrap_or(Value::Null),
    );
    rec.insert("size".to_string(), Value::Int(meta.len() as i64));
    Ok(Value::Record(rec))
}

#[path = "archive_cli.rs"]
mod archive_cli;

fn bi_archive_test(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Whether every entry decompresses and, for zip, matches its CRC. This
    // answered `true` for any zip on Windows without testing it, and for
    // any other format whenever the file merely existed.
    if args.len() != 1 {
        return Err(crate::safety::bad_arg(
            "archive_test",
            "exactly one path",
            &format!("{} arguments", args.len()),
        ));
    }
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            "archive_test",
            "a path argument",
            "pipeline input; archive_test takes no piped value",
        ));
    }
    let path = archive_path_arg("archive_test", &args)?;
    if let Some((codec, tar)) = archive_cli::named(&path) {
        // bzip2, xz and zstd, and the tar archives inside them: the standard
        // tools, checked against the file's magic bytes first.
        return Ok(Value::Bool(archive_cli::test(
            "archive_test",
            &path,
            codec,
            tar,
        )?));
    }
    // bzip2, xz and zstd names were taken by `archive_cli::named` above, so
    // only the in-process formats reach this match.
    let kind = match archive_kind(&path) {
        Some("zip") => LocalArchive::Zip,
        Some("tar") => LocalArchive::Tar,
        Some("tar.gz") => LocalArchive::TarGz,
        Some("gzip") => LocalArchive::Gzip,
        _ => {
            return Err(crate::safety::bad_arg(
                "archive_test",
                "a .zip, .tar, .tar.gz/.tgz or .gz file",
                &path,
            ))
        }
    };
    Ok(Value::Bool(archive_test_local(
        &path,
        kind,
        archive_cli::DECOMPRESSED_CAP,
    )?))
}

/// The formats `archive_test_local` reads in-process. bzip2, xz and zstd are
/// tested by `archive_cli`, which `bi_archive_test` asks first.
#[derive(Clone, Copy)]
enum LocalArchive {
    Zip,
    Tar,
    TarGz,
    Gzip,
}

impl LocalArchive {
    fn label(self) -> &'static str {
        match self {
            LocalArchive::Zip => "zip",
            LocalArchive::Tar => "tar",
            LocalArchive::TarGz => "tar.gz",
            LocalArchive::Gzip => "gzip",
        }
    }
}

/// archive_test for the formats read in-process (zip, tar, tar.gz, gzip),
/// with at most `cap` decompressed bytes. The tool-backed formats had a cap
/// and these did not, so a small archive that inflates to terabytes was read
/// to its end; past the cap the answer is E_BUDGET_EXCEEDED, neither true nor
/// false.
fn archive_test_local(path: &str, kind: LocalArchive, cap: u64) -> Result<bool> {
    use std::cell::Cell;
    struct CappedSink<'a> {
        left: &'a Cell<u64>,
        hit: &'a Cell<bool>,
    }
    impl std::io::Write for CappedSink<'_> {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            let left = self.left.get();
            if buf.len() as u64 > left {
                self.hit.set(true);
                return Err(std::io::Error::other("decompressed size cap reached"));
            }
            self.left.set(left - buf.len() as u64);
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let left = Cell::new(cap);
    let hit = Cell::new(false);
    let sink = |r: &mut dyn std::io::Read| {
        let mut out = CappedSink {
            left: &left,
            hit: &hit,
        };
        std::io::copy(r, &mut out).is_ok()
    };
    let ok = match kind {
        LocalArchive::Zip => {
            let Ok(mut z) = zip::ZipArchive::new(archive_open("archive_test", path)?) else {
                return Ok(false);
            };
            (0..z.len()).all(|i| z.by_index(i).map(|mut f| sink(&mut f)).unwrap_or(false))
        }
        LocalArchive::Tar | LocalArchive::TarGz => {
            let f = archive_open("archive_test", path)?;
            let reader: Box<dyn std::io::Read> = if matches!(kind, LocalArchive::TarGz) {
                Box::new(flate2::read::GzDecoder::new(f))
            } else {
                Box::new(f)
            };
            let mut ar = tar::Archive::new(reader);
            match ar.entries() {
                Ok(entries) => entries
                    .into_iter()
                    .all(|e| e.map(|mut e| sink(&mut e)).unwrap_or(false)),
                Err(_) => false,
            }
        }
        LocalArchive::Gzip => sink(&mut flate2::read::GzDecoder::new(archive_open(
            "archive_test",
            path,
        )?)),
    };
    if hit.get() {
        return Err(crate::safety::budget_exceeded(
            "archive_test",
            format!(
                "the decompressed {} contents passed {} bytes",
                kind.label(),
                cap
            ),
            "the archive is too large to test in-process; it is neither confirmed nor refuted",
        ));
    }
    Ok(ok)
}

#[cfg(test)]
mod archive_test_cap_tests {
    use super::*;
    use std::io::Write as _;

    #[test]
    fn an_archive_past_the_cap_is_budget_exceeded_not_false() {
        // Writes under the temp dir. An agent-mode test in this binary can set
        // the workspace jail to its own temp dir, so the shared lock is held.
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = std::env::temp_dir().join(format!("ae-archcap-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("zeros.gz");
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
        gz.write_all(&vec![0u8; 1 << 20]).unwrap();
        std::fs::write(&path, gz.finish().unwrap()).unwrap();
        let p = path.to_string_lossy().to_string();

        assert!(archive_test_local(&p, LocalArchive::Gzip, 1 << 20).unwrap());
        let e = archive_test_local(&p, LocalArchive::Gzip, (1 << 20) - 1).unwrap_err();
        let code = e
            .downcast_ref::<crate::safety::SafetyError>()
            .map(|s| s.code);
        assert_eq!(code, Some(crate::safety::ErrorCode::BudgetExceeded), "{e}");
        std::fs::remove_dir_all(&dir).unwrap();
    }
}

/// gzip, in-process (flate2): `gzip -k` semantics -- the input is kept and
/// an existing output is not overwritten. This ran the gzip program, which
/// Windows does not have, passed the file name unchecked (a leading `-` was
/// an option), and answered a bare `false` for every failure.
///
/// `out_path` must already have been through guard_local_write in the
/// builtin's own body: tests/guard_enforcement.rs reads `bi_*` bodies, not
/// helpers, to decide which builtins guard themselves.
fn gzip_file(builtin: &str, input: &str, out_path: &str, decompress: bool) -> Result<Value> {
    gzip_file_capped(builtin, input, out_path, decompress, FILE_OUTPUT_CAP)
}

/// [`gzip_file`] with the decompressed-size cap given. A decompression that
/// would write more than `cap` bytes is stopped before the write, refused as
/// E_BUDGET_EXCEEDED, and its partial output removed. Every failure removes the
/// output file, so none is left behind.
fn gzip_file_capped(
    builtin: &str,
    input: &str,
    out_path: &str,
    decompress: bool,
    cap: u64,
) -> Result<Value> {
    crate::security::check_read_jail(builtin, input)?;
    let src =
        std::fs::File::open(input).map_err(|e| crate::safety::fs_error(builtin, input, &e))?;
    // The exclusive create is the existence check: a file that appears after an
    // exists() test would otherwise be truncated, and removed on failure.
    let dst = create_new_output(builtin, out_path)?;
    let result = if decompress {
        let mut out = std::io::BufWriter::new(dst);
        gunzip_capped(flate2::read::GzDecoder::new(src), &mut out, cap)
    } else {
        let mut enc = flate2::write::GzEncoder::new(dst, flate2::Compression::default());
        std::io::copy(&mut std::io::BufReader::new(src), &mut enc)
            .and_then(|_| enc.finish())
            .map(|_| true)
    };
    match result {
        Ok(true) => Ok(Value::Bool(true)),
        Ok(false) => {
            // The writer is closed by now (it is local to the branch above), so
            // the partial file can be removed on every platform.
            Err(fail_removing_partial(
                crate::safety::budget_exceeded(
                    builtin,
                    format!("{input} decompresses to more than {cap} bytes and was stopped"),
                    "the output would be cut short, so it is refused and the partial output is removed; check that the archive is the one you meant",
                ),
                out_path,
            ))
        }
        Err(e) => {
            // no half-written output
            Err(fail_removing_partial(
                crate::safety::bad_arg(
                    builtin,
                    if decompress {
                        "valid gzip data"
                    } else {
                        "a readable file"
                    },
                    &format!("{input}: {e}"),
                ),
                out_path,
            ))
        }
    }
}

/// Copies the gzip stream `src` into `dst`, flushing at the end. Returns
/// `Ok(false)` as soon as the output would pass `cap`; the chunk that would have
/// passed it is not written. Every read consumes input, so the loop ends.
fn gunzip_capped<R: std::io::Read, W: std::io::Write>(
    mut src: R,
    dst: &mut W,
    cap: u64,
) -> std::io::Result<bool> {
    let mut chunk = [0u8; 8192];
    let mut total: u64 = 0;
    loop {
        let n = match src.read(&mut chunk) {
            Ok(0) => break,
            Ok(n) => n,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(e),
        };
        total = total.saturating_add(n as u64);
        if total > cap {
            return Ok(false);
        }
        dst.write_all(&chunk[..n])?;
    }
    dst.flush()?;
    Ok(true)
}

/// Test hook: `gzip_decompress` of `file` with a decompressed-size cap the test
/// chooses (the builtin uses FILE_OUTPUT_CAP). The jail check still runs.
/// Not part of the public API.
#[doc(hidden)]
pub fn __test_gzip_decompress_capped(file: &str, cap: u64) -> Result<Value> {
    let out = guard_local_write(
        "gzip_decompress",
        &gzip_out_path("gzip_decompress", file, true)?,
    )?;
    gzip_file_capped("gzip_decompress", file, &out, true, cap)
}

/// Where gzip_file writes: path.gz, or the path without its .gz.
fn gzip_out_path(builtin: &str, input: &str, decompress: bool) -> Result<String> {
    Ok(if decompress {
        input
            .strip_suffix(".gz")
            .ok_or_else(|| crate::safety::bad_arg(builtin, "a .gz file", input))?
            .to_string()
    } else {
        format!("{input}.gz")
    })
}

fn bi_gzip_compress(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "gzip_compress",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let out = guard_local_write(
        "gzip_compress",
        &gzip_out_path("gzip_compress", &file, false)?,
    )?;
    crate::tx::snapshot(&out); // the one output file; absent until written
    gzip_file("gzip_compress", &file, &out, false)
}

fn bi_gzip_decompress(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "gzip_decompress",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let out = guard_local_write(
        "gzip_decompress",
        &gzip_out_path("gzip_decompress", &file, true)?,
    )?;
    crate::tx::snapshot(&out); // the one output file; absent until written
    gzip_file("gzip_decompress", &file, &out, true)
}

fn bi_bzip2_compress(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "bzip2_compress",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // The file goes to bzip2 positionally; a leading `-` would be an option.
    crate::safety::reject_option_like("bzip2_compress", std::slice::from_ref(&file))?;
    // bzip2 writes `<file>.bz2` beside its input. That output is jailed as
    // gzip_compress's is; the input is resolved the same way, so the file
    // bzip2 writes is the one the jail judged.
    let file = crate::safety::resolve_path_str(&file);
    let out = guard_local_write("bzip2_compress", &format!("{file}.bz2"))?;
    crate::tx::snapshot(&out); // absent until written: bzip2 will not replace it

    // The journal step names the file bzip2 writes, not the input it only reads.
    crate::journal::record_group(
        "bzip2_compress",
        crate::safety::Effect::WriteLocal,
        vec![out.clone()],
    );
    let mut cmd = crate::safety::child_command("bzip2");
    cmd.args(["-k", &file]);
    // Compressing a large file can outlast the short deadlines.
    let output = bounded_cmd_output("bzip2_compress", "bzip2", cmd, TOOL_LONG_DEADLINE_SECS)?;
    // A failure was a bare `false`, with bzip2's reason discarded.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "bzip2_compress",
            "bzip2",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    Ok(Value::Bool(true))
}

// The decompressed stream goes to a new file beside the archive, not in place,
// so bzip2 is run with -c and the output is created exclusively. That lets the
// output be jailed to the workspace (the in-place form wrote wherever the
// archive was, with no check), refuses an existing file, and caps the bytes
// written (a small archive can inflate without bound). A run past the cap or the
// deadline is stopped and its partial file removed.
fn bi_bzip2_decompress(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("bzip2_decompress", &input)?;
    if args.len() != 1 {
        return Err(crate::safety::bad_arg(
            "bzip2_decompress",
            "one path to a .bz2 file",
            &format!("{} arguments", args.len()),
        ));
    }
    let file = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "bzip2_decompress",
                "String",
                other.type_name(),
            ))
        }
    };
    // The file goes to bzip2 positionally; a leading `-` would be an option.
    refuse_option("bzip2_decompress", &file)?;
    let out = file
        .strip_suffix(".bz2")
        .ok_or_else(|| crate::safety::bad_arg("bzip2_decompress", "a .bz2 file", &file))?
        .to_string();
    let input = crate::safety::resolve_path_str(&file);
    regular_file_arg("bzip2_decompress", &input)?;
    let out = guard_local_write("bzip2_decompress", &out)?;
    tool_to_new_file(
        "bzip2_decompress",
        "bzip2",
        &["-d", "-c", input.as_str()],
        &out,
    )?;
    Ok(Value::Bool(true))
}

// 341: bi_xz_compress - Write file.xz beside a file, keeping the file.
//
// The compressed stream goes to a new file created exclusively, so an existing
// file.xz is refused and nothing is overwritten.
fn bi_xz_compress(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("xz_compress", &input)?;
    let file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "xz_compress",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    refuse_option("xz_compress", &file)?;
    let input = crate::safety::resolve_path_str(&file);
    regular_file_arg("xz_compress", &input)?;
    let out = guard_local_write("xz_compress", &format!("{input}.xz"))?;
    tool_to_new_file("xz_compress", "xz", &["-z", "-c", input.as_str()], &out)?;
    Ok(Value::Bool(true))
}

// 342: bi_xz_decompress - Write a .xz file's contents beside it, without the suffix.
//
// The output is capped at FILE_OUTPUT_CAP bytes. A stream that inflates past it
// is stopped and its partial file removed. An existing output is refused.
fn bi_xz_decompress(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("xz_decompress", &input)?;
    let file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "xz_decompress",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    refuse_option("xz_decompress", &file)?;
    let out = file
        .strip_suffix(".xz")
        .ok_or_else(|| crate::safety::bad_arg("xz_decompress", "a .xz file", &file))?
        .to_string();
    let input = crate::safety::resolve_path_str(&file);
    regular_file_arg("xz_decompress", &input)?;
    let out = guard_local_write("xz_decompress", &out)?;
    tool_to_new_file("xz_decompress", "xz", &["-d", "-c", input.as_str()], &out)?;
    Ok(Value::Bool(true))
}

// 343: bi_zstd_compress - Write file.zst beside a file, keeping the file.
fn bi_zstd_compress(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("zstd_compress", &input)?;
    let file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "zstd_compress",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    refuse_option("zstd_compress", &file)?;
    let input = crate::safety::resolve_path_str(&file);
    regular_file_arg("zstd_compress", &input)?;
    let out = guard_local_write("zstd_compress", &format!("{input}.zst"))?;
    tool_to_new_file("zstd_compress", "zstd", &["-q", "-c", input.as_str()], &out)?;
    Ok(Value::Bool(true))
}

// 344: bi_zstd_decompress - Write a .zst file's contents beside it, without the suffix.
//
// Bounded and refused on an existing output, exactly as xz_decompress is.
fn bi_zstd_decompress(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("zstd_decompress", &input)?;
    let file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "zstd_decompress",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    refuse_option("zstd_decompress", &file)?;
    let out = file
        .strip_suffix(".zst")
        .ok_or_else(|| crate::safety::bad_arg("zstd_decompress", "a .zst file", &file))?
        .to_string();
    let input = crate::safety::resolve_path_str(&file);
    regular_file_arg("zstd_decompress", &input)?;
    let out = guard_local_write("zstd_decompress", &out)?;
    tool_to_new_file(
        "zstd_decompress",
        "zstd",
        &["-d", "-q", "-c", input.as_str()],
        &out,
    )?;
    Ok(Value::Bool(true))
}

// ============================================================================
// 350-369: User & Permission Management
// ============================================================================

fn bi_user_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_sys_users(vec![], None)
}

#[path = "accounts.rs"]
mod accounts;

fn bi_user_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::user_add(args, input)
}

fn bi_user_del(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::user_del(args, input)
}

fn bi_user_mod(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::user_mod(args, input)
}

fn bi_user_passwd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::user_passwd(args, input)
}

fn bi_user_lock(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::user_lock(args, input)
}

fn bi_user_unlock(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::user_unlock(args, input)
}

fn bi_group_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_sys_groups(vec![], None)
}

fn bi_group_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::group_add(args, input)
}

fn bi_group_del(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::group_del(args, input)
}

fn bi_group_mod(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    accounts::group_mod(args, input)
}

fn bi_group_members(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let group = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "group_members",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    crate::safety::reject_option_like("group_members", std::slice::from_ref(&group))?;
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-Command",
            &crate::ps_script!(
                "Get-LocalGroupMember {} | Select-Object Name | ConvertTo-Json",
                crate::safety::ps_quote(&group)
            ),
        ]);
        let output = bounded_cmd_output("group_members", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                let items = match &json {
                    serde_json::Value::Array(arr) => arr.clone(),
                    obj @ serde_json::Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                let members: Vec<Value> = items
                    .iter()
                    .filter_map(|obj| {
                        obj.as_object()?
                            .get("Name")?
                            .as_str()
                            .map(|s| Value::Str(s.to_string()))
                    })
                    .collect();
                return Ok(Value::Array(members));
            }
        }
        return Err(crate::safety::tool_failed(
            "group_members",
            "Get-LocalGroupMember",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    #[cfg(not(target_os = "windows"))]
    {
        let mut cmd = crate::safety::child_command("getent");
        cmd.args(["group", &group]);
        let output = bounded_cmd_output("group_members", "getent", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let line = String::from_utf8_lossy(&output.stdout);
            if let Some(members) = line.split(':').nth(3) {
                let member_list: Vec<Value> = members
                    .trim()
                    .split(',')
                    .filter(|s| !s.is_empty())
                    .map(|s| Value::Str(s.to_string()))
                    .collect();
                return Ok(Value::Array(member_list));
            }
        }
        // getent exits 2 for a name it does not know. An unknown group, a
        // failed query and a group with no members all answered [].
        if output.status.code() == Some(2) {
            return Err(crate::safety::not_found("group_members", "group", &group));
        }
        Err(crate::safety::tool_failed(
            "group_members",
            "getent",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ))
    }
}

fn bi_perm_get(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "perm_get",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // A path that could not be read was null.
    crate::security::check_read_jail("perm_get", &path)?;
    let meta =
        std::fs::metadata(&path).map_err(|e| crate::safety::fs_error("perm_get", &path, &e))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = meta.permissions().mode();
        return Ok(Value::Str(format!("{:o}", mode & 0o777)));
    }
    #[cfg(not(unix))]
    {
        let readonly = meta.permissions().readonly();
        Ok(Value::Str(
            if readonly { "readonly" } else { "readwrite" }.to_string(),
        ))
    }
}

fn bi_perm_set(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    guard_and_set_permission_mode("perm_set", args, input)
}

fn bi_perm_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if !(1..=2).contains(&args.len()) || input.is_some() {
        return Err(crate::safety::arg_err(
            "perm_check requires path and optional mode, without pipeline input",
        ));
    }
    let mut args = args.into_iter();
    let Some(Value::Str(path)) = args.next() else {
        return Err(crate::safety::arg_err("perm_check path must be String"));
    };
    let mode = match args.next() {
        None => "r".to_string(),
        Some(Value::Str(mode))
            if matches!(
                mode.as_str(),
                "r" | "read" | "w" | "write" | "x" | "execute"
            ) =>
        {
            mode
        }
        _ => {
            return Err(crate::safety::arg_err(
                "perm_check mode must be r/read, w/write or x/execute",
            ))
        }
    };
    let path = crate::safety::resolve_path_str(&path);
    crate::security::check_read_jail("perm_check", &path)?;
    let metadata =
        fs::metadata(&path).map_err(|e| crate::safety::fs_error("perm_check", &path, &e))?;
    // This is a metadata query, not an access check for the caller's identity,
    // ACLs, privileges, mount flags or sharing restrictions.
    match mode.as_str() {
        "r" | "read" => Ok(Value::Bool(true)),
        "w" | "write" => Ok(Value::Bool(!metadata.permissions().readonly())),
        "x" | "execute" => {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                Ok(Value::Bool(metadata.permissions().mode() & 0o111 != 0))
            }
            #[cfg(windows)]
            {
                Ok(Value::Bool(
                    metadata.is_file() && windows_pathext_executable(std::path::Path::new(&path)),
                ))
            }
            #[cfg(not(any(unix, windows)))]
            {
                Err(crate::safety::unimplemented(
                    "perm_check",
                    "execute permission bits are unavailable on this platform",
                    "inspect platform-specific executable formats and access controls",
                ))
            }
        }
        _ => unreachable!("validated permission mode"),
    }
}

/// Windows executability is a naming rule, not an ACL check: a regular file
/// whose extension appears in PATHEXT (default `.COM;.EXE;.BAT;.CMD`).
#[cfg(windows)]
fn windows_pathext_executable(path: &std::path::Path) -> bool {
    let Some(extension) = path.extension().and_then(|e| e.to_str()) else {
        return false;
    };
    let pathext = std::env::var("PATHEXT")
        .ok()
        .filter(|v| !v.trim().is_empty())
        .unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD".to_string());
    pathext
        .split(';')
        .map(|entry| entry.trim().trim_start_matches('.'))
        .filter(|entry| !entry.is_empty())
        .any(|entry| entry.eq_ignore_ascii_case(extension))
}

#[path = "acl_mount.rs"]
mod acl_mount;
fn bi_acl_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    acl_mount::acl_get(args, input)
}

fn bi_acl_set(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    acl_mount::acl_set(args, input)
}

fn bi_sudo_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if !args.is_empty() || input.is_some() {
        return Err(crate::safety::arg_err(
            "sudo_check accepts no arguments or pipeline input",
        ));
    }
    #[cfg(windows)]
    {
        Ok(Value::Bool(windows_is_admin("sudo_check")?))
    }
    #[cfg(unix)]
    {
        // geteuid cannot fail and inspects this process without spawning id.
        Ok(Value::Bool(unsafe { libc::geteuid() } == 0))
    }
    #[cfg(not(any(unix, windows)))]
    {
        Err(crate::safety::unimplemented(
            "sudo_check",
            "privilege inspection is unavailable on this platform",
            "use the platform's identity inspection tools",
        ))
    }
}

fn bi_sudo_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    services::sudo_exec(args, input)
}

/// Capability numbers from `linux/capability.h`, in order. A bit beyond the
/// end of this table (a newer kernel) is reported as `cap_<n>`, not dropped.
#[cfg(target_os = "linux")]
const LINUX_CAPABILITIES: [&str; 41] = [
    "cap_chown",
    "cap_dac_override",
    "cap_dac_read_search",
    "cap_fowner",
    "cap_fsetid",
    "cap_kill",
    "cap_setgid",
    "cap_setuid",
    "cap_setpcap",
    "cap_linux_immutable",
    "cap_net_bind_service",
    "cap_net_broadcast",
    "cap_net_admin",
    "cap_net_raw",
    "cap_ipc_lock",
    "cap_ipc_owner",
    "cap_sys_module",
    "cap_sys_rawio",
    "cap_sys_chroot",
    "cap_sys_ptrace",
    "cap_sys_pacct",
    "cap_sys_admin",
    "cap_sys_boot",
    "cap_sys_nice",
    "cap_sys_resource",
    "cap_sys_time",
    "cap_sys_tty_config",
    "cap_mknod",
    "cap_lease",
    "cap_audit_write",
    "cap_audit_control",
    "cap_setfcap",
    "cap_mac_override",
    "cap_mac_admin",
    "cap_syslog",
    "cap_wake_alarm",
    "cap_block_suspend",
    "cap_audit_read",
    "cap_perfmon",
    "cap_bpf",
    "cap_checkpoint_restore",
];

#[cfg(target_os = "linux")]
fn decode_capability_mask(hex: &str) -> Option<Vec<Value>> {
    let mask = u64::from_str_radix(hex.trim(), 16).ok()?;
    Some(
        (0..64u32)
            .filter(|bit| mask & (1u64 << bit) != 0)
            .map(|bit| {
                Value::Str(match LINUX_CAPABILITIES.get(bit as usize) {
                    Some(name) => name.to_string(),
                    None => format!("cap_{bit}"),
                })
            })
            .collect(),
    )
}

fn bi_capabilities(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // This parsed `capsh --print`, and got it wrong: capsh writes the
    // effective set as `Current: =...`, with a colon, so the set an agent
    // most needs was never extracted (it surfaced as a key named
    // "current:"), `uid` came back as the string "1000(test) euid=1000(test)",
    // and hosts without libcap's tools failed outright. The kernel publishes
    // all five sets in /proc/self/status as bitmasks; decode those.
    #[cfg(target_os = "linux")]
    {
        let status = std::fs::read_to_string("/proc/self/status")
            .map_err(|e| crate::safety::fs_error("capabilities", "/proc/self/status", &e))?;
        let mut rec = std::collections::BTreeMap::new();
        for line in status.lines() {
            let Some((key, val)) = line.split_once(':') else {
                continue;
            };
            let field = match key {
                "CapInh" => "inheritable",
                "CapPrm" => "permitted",
                "CapEff" => "effective",
                "CapBnd" => "bounding",
                "CapAmb" => "ambient",
                "NoNewPrivs" => {
                    rec.insert("no_new_privs".to_string(), Value::Bool(val.trim() == "1"));
                    continue;
                }
                "Uid" | "Gid" => {
                    // real, effective, saved, filesystem
                    let ids: Vec<i64> = val
                        .split_whitespace()
                        .filter_map(|v| v.parse().ok())
                        .collect();
                    let (real, eff) = if key == "Uid" {
                        ("uid", "euid")
                    } else {
                        ("gid", "egid")
                    };
                    if let [r, e, ..] = ids[..] {
                        rec.insert(real.to_string(), Value::Int(r));
                        rec.insert(eff.to_string(), Value::Int(e));
                    }
                    continue;
                }
                _ => continue,
            };
            let caps = decode_capability_mask(val).ok_or_else(|| {
                crate::safety::bad_state_with_hint(
                    "capabilities",
                    &format!(
                        "/proc/self/status has an unreadable {key} mask: {}",
                        val.trim()
                    ),
                    "this kernel reports capabilities in a format this shell does not know",
                )
            })?;
            rec.insert(field.to_string(), Value::Array(caps));
        }
        for field in [
            "inheritable",
            "permitted",
            "effective",
            "bounding",
            "ambient",
        ] {
            if !rec.contains_key(field) {
                return Err(crate::safety::bad_state_with_hint(
                    "capabilities",
                    &format!("/proc/self/status does not report the {field} set"),
                    "this kernel predates the capability set, or /proc is not procfs",
                ));
            }
        }
        return Ok(Value::Record(rec));
    }
    // Windows has no capability bitmasks; its privileges are listed by
    // `whoami /priv`, a read-only system tool run without a shell.
    #[cfg(windows)]
    {
        return windows_privileges();
    }
    // Linux capability sets are a Linux concept. Everywhere else this fell
    // through to `Ok(Value::Null)`, which a caller reads as "this process
    // has no capabilities" -- a claim about privilege, made without looking.
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "capabilities",
        "Linux capability sets do not exist on this operating system; NOTHING WAS INSPECTED",
        "use `id` on this system",
    ))
}

/// The privileges of this Windows process, from `whoami /priv /fo csv`, as
/// `{privileges: [{name, description, state}]}`. The shape differs from the
/// Linux record because Windows has no capability masks.
#[cfg(windows)]
fn windows_privileges() -> Result<Value> {
    let run = tool_run(
        "capabilities",
        "whoami",
        None,
        &["/priv", "/fo", "csv"],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    if !run.success {
        return Err(crate::safety::tool_failed(
            "capabilities",
            &run.command,
            run.code,
            &run.stderr,
        ));
    }
    let rows = parse_whoami_priv_csv("capabilities", &run.stdout)?;
    let mut rec = BTreeMap::new();
    rec.insert("privileges".to_string(), Value::Array(rows));
    Ok(Value::Record(rec))
}

/// Parses the CSV that `whoami /priv /fo csv` prints. Lines before the header
/// that have one field (a title) are skipped. The header must name the three
/// columns in English; any other layout is refused, not guessed at. Every line
/// after it must hold exactly three fields, or the whole answer is refused.
#[cfg(any(windows, test))]
fn parse_whoami_priv_csv(builtin: &str, text: &str) -> Result<Vec<Value>> {
    const HEADER: [&str; 3] = ["Privilege Name", "Description", "State"];
    let mut rows = Vec::new();
    let mut seen_header = false;
    for line in text.lines() {
        let line = line.trim_end_matches('\r');
        if line.trim().is_empty() {
            continue;
        }
        let Some(fields) = csv_fields(line) else {
            return Err(crate::safety::bad_state_with_hint(
                builtin,
                &format!("whoami /priv printed a malformed CSV line: {line:?}"),
                "this host's whoami output is not the CSV layout this shell reads",
            ));
        };
        if !seen_header {
            if fields.len() == 1 {
                continue;
            }
            if fields.iter().map(String::as_str).eq(HEADER) {
                seen_header = true;
                continue;
            }
            return Err(crate::safety::bad_state_with_hint(
                builtin,
                &format!("whoami /priv printed an unexpected header: {line:?}"),
                "the privilege table is read only in its English layout",
            ));
        }
        if fields.len() != 3 {
            return Err(crate::safety::bad_state_with_hint(
                builtin,
                &format!(
                    "whoami /priv printed a line with {} fields, not 3: {line:?}",
                    fields.len()
                ),
                "this host's whoami output is not the CSV layout this shell reads",
            ));
        }
        let mut rec = BTreeMap::new();
        rec.insert("name".to_string(), Value::Str(fields[0].clone()));
        rec.insert("description".to_string(), Value::Str(fields[1].clone()));
        rec.insert("state".to_string(), Value::Str(fields[2].clone()));
        rows.push(Value::Record(rec));
    }
    if !seen_header {
        return Err(crate::safety::bad_state_with_hint(
            builtin,
            "whoami /priv printed no privilege table",
            "this host's whoami output is not the CSV layout this shell reads",
        ));
    }
    Ok(rows)
}

/// Splits one CSV line into fields. A field may be quoted, and a quoted field
/// may hold commas and doubled quotes (""). None for an unterminated quote or
/// text between a closing quote and the next comma.
#[cfg(any(windows, test))]
fn csv_fields(line: &str) -> Option<Vec<String>> {
    let mut fields = Vec::new();
    let mut chars = line.chars().peekable();
    loop {
        let mut field = String::new();
        if chars.peek() == Some(&'"') {
            chars.next();
            loop {
                match chars.next() {
                    None => return None,
                    Some('"') => {
                        if chars.peek() == Some(&'"') {
                            chars.next();
                            field.push('"');
                        } else {
                            break;
                        }
                    }
                    Some(c) => field.push(c),
                }
            }
            match chars.next() {
                None => {
                    fields.push(field);
                    return Some(fields);
                }
                Some(',') => {}
                Some(_) => return None,
            }
        } else {
            loop {
                match chars.next() {
                    None => {
                        fields.push(field);
                        return Some(fields);
                    }
                    Some(',') => break,
                    Some(c) => field.push(c),
                }
            }
        }
        fields.push(field);
    }
}

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

    const SAMPLE: &str = "\"Privilege Name\",\"Description\",\"State\"\r\n\
\"SeShutdownPrivilege\",\"Shut down the system\",\"Disabled\"\r\n\
\"SeChangeNotifyPrivilege\",\"Bypass traverse checking, for any user\",\"Enabled\"\r\n\
\"SeUndockPrivilege\",\"Say \"\"undock\"\"\",\"Disabled\"\r\n";

    fn field(v: &Value, key: &str) -> String {
        match v {
            Value::Record(r) => match r.get(key) {
                Some(Value::Str(s)) => s.clone(),
                other => panic!("{key}: {other:?}"),
            },
            other => panic!("not a record: {other:?}"),
        }
    }

    #[test]
    fn parses_names_descriptions_and_states_including_quoted_commas() {
        let rows = parse_whoami_priv_csv("capabilities", SAMPLE).expect("sample parses");
        assert_eq!(rows.len(), 3);
        assert_eq!(field(&rows[0], "name"), "SeShutdownPrivilege");
        assert_eq!(field(&rows[0], "state"), "Disabled");
        assert_eq!(
            field(&rows[1], "description"),
            "Bypass traverse checking, for any user"
        );
        assert_eq!(field(&rows[2], "description"), "Say \"undock\"");
    }

    #[test]
    fn skips_a_title_line_before_the_header() {
        let text = format!("\"PRIVILEGES INFORMATION\"\n\n{SAMPLE}");
        assert_eq!(
            parse_whoami_priv_csv("capabilities", &text).unwrap().len(),
            3
        );
    }

    #[test]
    fn a_malformed_line_refuses_the_whole_answer() {
        let text = "\"Privilege Name\",\"Description\",\"State\"\n\
\"SeShutdownPrivilege\",\"Shut down the system\",\"Disabled\"\n\
\"SeBroken\",\"unterminated,\"Enabled\n";
        let err = parse_whoami_priv_csv("capabilities", text).expect_err("malformed");
        assert!(err.to_string().contains("E_BAD_STATE"), "{err}");
    }

    #[test]
    fn a_line_with_the_wrong_field_count_refuses() {
        let text = "\"Privilege Name\",\"Description\",\"State\"\n\"SeOnly\",\"Enabled\"\n";
        let err = parse_whoami_priv_csv("capabilities", text).expect_err("two fields");
        assert!(err.to_string().contains("E_BAD_STATE"), "{err}");
    }

    #[test]
    fn a_localised_header_refuses_rather_than_guessing() {
        let err = parse_whoami_priv_csv("capabilities", "\"Name\",\"Desc\",\"Status\"\n")
            .expect_err("header");
        assert!(err.to_string().contains("E_BAD_STATE"), "{err}");
    }

    #[test]
    fn csv_fields_rejects_text_after_a_closing_quote() {
        assert_eq!(csv_fields("\"a\"b,c"), None);
        assert_eq!(
            csv_fields("a,\"b,c\",d"),
            Some(vec!["a".to_string(), "b,c".to_string(), "d".to_string()])
        );
    }
}

// ============================================================================
// 370-389: Package Management
// ============================================================================

fn detect_package_manager() -> &'static str {
    #[cfg(target_os = "windows")]
    {
        "winget"
    }
    #[cfg(target_os = "macos")]
    {
        return "brew";
    }
    #[cfg(target_os = "linux")]
    {
        if std::path::Path::new("/usr/bin/apt").exists() {
            return "apt";
        }
        if std::path::Path::new("/usr/bin/dnf").exists() {
            return "dnf";
        }
        if std::path::Path::new("/usr/bin/yum").exists() {
            return "yum";
        }
        if std::path::Path::new("/usr/bin/pacman").exists() {
            return "pacman";
        }
        return "apt";
    }
}

fn bi_pkg_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if !args.is_empty() {
        return Err(crate::safety::arg_err(format!(
            "pkg_list takes no arguments, got {}",
            args.len()
        )));
    }
    linux_diagnostics::no_pipeline_input("pkg_list", &input)?;
    let packages = match detect_package_manager() {
        "apt" => pkg_query::list_dpkg("pkg_list")?,
        "pacman" => pkg_query::list_pacman("pkg_list")?,
        "dnf" | "yum" => pkg_query::list_rpm("pkg_list")?,
        "brew" => pkg_query::list_brew("pkg_list")?,
        #[cfg(windows)]
        "winget" => pkg_query::list_windows_arp("pkg_list")?,
        other => {
            return Err(crate::safety::unimplemented(
                "pkg_list",
                &format!(
                    "pkg_list is not implemented for the {other} package manager in 14.0.0; NOTHING WAS LISTED"
                ),
                "list the packages with that manager directly",
            ))
        }
    };
    Ok(Value::Array(
        packages
            .into_iter()
            .map(|(name, version)| {
                let mut rec = std::collections::BTreeMap::new();
                rec.insert("name".to_string(), Value::Str(name));
                // Only a Windows program can record no version.
                let version = if version.is_empty() {
                    Value::Null
                } else {
                    Value::Str(version)
                };
                rec.insert("version".to_string(), version);
                Value::Record(rec)
            })
            .collect(),
    ))
}

/// This package manager is not one the builtin knows how to query. These
/// answered [] ("no files", "no results"), null, or -- for pkg_verify --
/// `true`, "verified", without inspecting anything.
fn pkg_unsupported(builtin: &str, pm: &str) -> anyhow::Error {
    crate::safety::unimplemented(
        builtin,
        &format!(
            "{builtin} is not implemented for the {pm} package manager; NOTHING WAS INSPECTED"
        ),
        "query the package manager directly",
    )
}

/// Whether a nonzero exit from a package query is that tool's documented
/// "nothing matched" answer rather than a failure. Each rule is one tool's own
/// convention: `dpkg -S` and `dpkg-query -L` exit 1 when no package owns the
/// path or the package is not installed; `pacman -Ss` exits 1 with no output
/// when nothing matches; the pacman queries exit 1 with "was not found" or "No
/// package owns" on stderr; `apt-cache show|depends|rdepends` report "No
/// packages found". The text rules are English only: a localised message is
/// not recognised, so it is E_TOOL_FAILED, which still carries the stderr.
fn pkg_no_match(builtin: &str, pm: &str, status: Option<i32>, stderr: &str) -> bool {
    match pm {
        "apt" => {
            (matches!(builtin, "pkg_owner" | "pkg_files") && status == Some(1))
                || stderr.contains("No packages found")
        }
        "pacman" => {
            status == Some(1)
                && ((builtin == "pkg_search" && stderr.trim().is_empty())
                    || stderr.contains("was not found")
                    || stderr.contains("No package owns"))
        }
        "dnf" | "yum" => {
            stderr.contains("No matching Packages") || stderr.contains("No matches found")
        }
        "brew" => stderr.contains("No available formula") || stderr.contains("No available cask"),
        _ => false,
    }
}

/// The error for a package query that exited nonzero. The documented no-match
/// is E_NOT_FOUND naming what was asked for; any other exit is E_TOOL_FAILED
/// with the exit code and the tool's stderr.
fn pkg_query_failure(
    builtin: &str,
    kind: &str,
    name: &str,
    pm: &str,
    program: &str,
    status: Option<i32>,
    stderr: &str,
) -> anyhow::Error {
    if pkg_no_match(builtin, pm, status, stderr) {
        crate::safety::not_found(builtin, kind, name)
    } else {
        crate::safety::tool_failed(builtin, program, status, stderr)
    }
}

fn bi_pkg_search(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let query = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "pkg_search",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    crate::safety::reject_option_like("pkg_search", std::slice::from_ref(&query))?;
    let pm = detect_package_manager();

    let output = match pm {
        "apt" => {
            let mut cmd = crate::safety::child_command("apt-cache");
            cmd.args(["search", &query]);
            bounded_cmd_output("pkg_search", "apt-cache", cmd, TOOL_DEADLINE_SECS)?
        }
        "dnf" | "yum" => {
            let mut cmd = crate::safety::child_command(pm);
            cmd.args(["search", &query]);
            bounded_cmd_output("pkg_search", pm, cmd, TOOL_DEADLINE_SECS)?
        }
        "pacman" => {
            let mut cmd = crate::safety::child_command("pacman");
            cmd.args(["-Ss", &query]);
            bounded_cmd_output("pkg_search", "pacman", cmd, TOOL_DEADLINE_SECS)?
        }
        "brew" => {
            let mut cmd = crate::safety::child_command("brew");
            cmd.args(["search", &query]);
            bounded_cmd_output("pkg_search", "brew", cmd, TOOL_DEADLINE_SECS)?
        }
        "winget" => {
            // `winget search` queries the online sources. apt-cache reads its local index.
            crate::safety::check_egress_unknown("pkg_search", PKG_EGRESS_REASON)?;
            let mut cmd = crate::safety::child_command("winget");
            cmd.args(["search", &query]);
            bounded_cmd_output("pkg_search", "winget", cmd, TOOL_DEADLINE_SECS)?
        }
        other => return Err(pkg_unsupported("pkg_search", other)),
    };
    let program = match pm {
        "apt" => "apt-cache",
        "dnf" | "yum" => pm,
        "pacman" => "pacman",
        "brew" => "brew",
        "winget" => "winget",
        other => other,
    };
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // A query that matched nothing is an empty list, not a failure.
        if !pkg_no_match("pkg_search", pm, output.status.code(), &stderr) {
            return Err(crate::safety::tool_failed(
                "pkg_search",
                program,
                output.status.code(),
                &stderr,
            ));
        }
    }

    let text = String::from_utf8_lossy(&output.stdout);
    let results: Vec<Value> = match pm {
        "apt" => {
            // apt-cache search: "name - description"
            text.lines()
                .filter(|l| !l.trim().is_empty())
                .filter_map(|l| {
                    let parts: Vec<&str> = l.splitn(2, " - ").collect();
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("name".to_string(), Value::Str(parts[0].trim().to_string()));
                    if parts.len() >= 2 {
                        rec.insert(
                            "description".to_string(),
                            Value::Str(parts[1].trim().to_string()),
                        );
                    }
                    Some(Value::Record(rec))
                })
                .collect()
        }
        "brew" => {
            // brew search: one name per line
            text.lines()
                .filter(|l| !l.trim().is_empty() && !l.starts_with("==>"))
                .map(|l| {
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("name".to_string(), Value::Str(l.trim().to_string()));
                    Value::Record(rec)
                })
                .collect()
        }
        _ => {
            // Generic: parse as whitespace-separated
            text.lines()
                .filter(|l| !l.trim().is_empty())
                .map(|l| {
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("name".to_string(), Value::Str(l.trim().to_string()));
                    Value::Record(rec)
                })
                .collect()
        }
    };
    Ok(Value::Array(results))
}

fn bi_pkg_info(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let package = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "pkg_info",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    crate::safety::reject_option_like("pkg_info", std::slice::from_ref(&package))?;
    let pm = detect_package_manager();

    let output = match pm {
        "apt" => {
            let mut cmd = crate::safety::child_command("apt-cache");
            cmd.args(["show", &package]);
            bounded_cmd_output("pkg_info", "apt-cache", cmd, TOOL_DEADLINE_SECS)?
        }
        "dnf" | "yum" => {
            let mut cmd = crate::safety::child_command(pm);
            cmd.args(["info", &package]);
            bounded_cmd_output("pkg_info", pm, cmd, TOOL_DEADLINE_SECS)?
        }
        "pacman" => {
            let mut cmd = crate::safety::child_command("pacman");
            cmd.args(["-Qi", &package]);
            bounded_cmd_output("pkg_info", "pacman", cmd, TOOL_DEADLINE_SECS)?
        }
        "brew" => {
            let mut cmd = crate::safety::child_command("brew");
            cmd.args(["info", &package]);
            bounded_cmd_output("pkg_info", "brew", cmd, TOOL_DEADLINE_SECS)?
        }
        "winget" => {
            // `winget show` reads the manifest from the online sources.
            crate::safety::check_egress_unknown("pkg_info", PKG_EGRESS_REASON)?;
            let mut cmd = crate::safety::child_command("winget");
            cmd.args(["show", &package]);
            bounded_cmd_output("pkg_info", "winget", cmd, TOOL_DEADLINE_SECS)?
        }
        other => return Err(pkg_unsupported("pkg_info", other)),
    };
    let program = match pm {
        "apt" => "apt-cache",
        "dnf" | "yum" => pm,
        "pacman" => "pacman",
        "brew" => "brew",
        "winget" => "winget",
        other => other,
    };
    if !output.status.success() {
        return Err(pkg_query_failure(
            "pkg_info",
            "package",
            &package,
            pm,
            program,
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }

    // Parse key-value "Field: Value" lines into a Record (works for apt, dnf, pacman, brew, winget)
    let text = String::from_utf8_lossy(&output.stdout);
    let mut rec = std::collections::BTreeMap::new();
    for line in text.lines() {
        if let Some(colon_pos) = line.find(':') {
            let key = line[..colon_pos].trim();
            let value = line[colon_pos + 1..].trim();
            if !key.is_empty() && !key.contains(' ') || key.contains("Build Date") {
                rec.insert(
                    key.to_lowercase().replace(' ', "_"),
                    Value::Str(value.to_string()),
                );
            }
        }
    }
    if rec.is_empty() {
        Ok(Value::Str(text.to_string()))
    } else {
        Ok(Value::Record(rec))
    }
}

#[path = "pkg_admin.rs"]
mod pkg_admin;

fn bi_pkg_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::install(args, input)
}

fn bi_pkg_remove(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::remove(args, input)
}

fn bi_pkg_update(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::update(args, input)
}

fn bi_pkg_upgrade(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::upgrade(args, input)
}

fn bi_pkg_clean(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::clean(args, input)
}

fn bi_pkg_sources(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "linux")]
    {
        // No sources.list is a system without apt ([] below). One that exists
        // but cannot be read used to be the same empty list; it is an error.
        let sources = match std::fs::read_to_string("/etc/apt/sources.list") {
            Ok(text) => Some(text),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => {
                return Err(crate::safety::fs_error(
                    "pkg_sources",
                    "/etc/apt/sources.list",
                    &e,
                ))
            }
        };
        if let Some(sources) = sources {
            let entries: Vec<Value> = sources
                .lines()
                .filter(|l| {
                    let t = l.trim();
                    !t.is_empty() && !t.starts_with('#')
                })
                .map(|line| {
                    let mut rec = std::collections::BTreeMap::new();
                    let parts: Vec<&str> = line.split_whitespace().collect();
                    if let Some(typ) = parts.first() {
                        rec.insert("type".to_string(), Value::Str(typ.to_string()));
                    }
                    if let Some(uri) = parts.get(1) {
                        rec.insert("uri".to_string(), Value::Str(uri.to_string()));
                    }
                    if let Some(dist) = parts.get(2) {
                        rec.insert("distribution".to_string(), Value::Str(dist.to_string()));
                    }
                    if parts.len() > 3 {
                        let components: Vec<Value> = parts[3..]
                            .iter()
                            .map(|c| Value::Str(c.to_string()))
                            .collect();
                        rec.insert("components".to_string(), Value::Array(components));
                    }
                    rec.insert("raw".to_string(), Value::Str(line.to_string()));
                    Value::Record(rec)
                })
                .collect();
            return Ok(Value::Array(entries));
        }
    }
    Ok(Value::Array(vec![]))
}

fn bi_pkg_add_source(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::add_source(args, input)
}

fn bi_pkg_files(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let package = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "pkg_files",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    crate::safety::reject_option_like("pkg_files", std::slice::from_ref(&package))?;
    let pm = detect_package_manager();

    let output = match pm {
        "apt" => {
            let mut cmd = crate::safety::child_command("dpkg");
            cmd.args(["-L", &package]);
            bounded_cmd_output("pkg_files", "dpkg", cmd, TOOL_DEADLINE_SECS)?
        }
        "pacman" => {
            let mut cmd = crate::safety::child_command("pacman");
            cmd.args(["-Ql", &package]);
            bounded_cmd_output("pkg_files", "pacman", cmd, TOOL_DEADLINE_SECS)?
        }
        other => return Err(pkg_unsupported("pkg_files", other)),
    };
    let program = match pm {
        "apt" => "dpkg",
        "pacman" => "pacman",
        other => other,
    };
    if !output.status.success() {
        return Err(pkg_query_failure(
            "pkg_files",
            "package",
            &package,
            pm,
            program,
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }

    let text = String::from_utf8_lossy(&output.stdout);
    let files: Vec<Value> = text
        .lines()
        // dpkg -L lists the root as "/."; it is not a file of the package.
        .filter(|l| !l.trim().is_empty() && l.trim() != "/.")
        .map(|l| {
            // pacman -Ql prints "package /path"; dpkg -L prints the path alone,
            // and splitting that at a space cut "/usr/share/doc/a b" to "b".
            match l.split_once(' ') {
                Some((_pkg, path)) if pm == "pacman" => Value::Str(path.to_string()),
                _ => Value::Str(l.trim().to_string()),
            }
        })
        .collect();
    Ok(Value::Array(files))
}

fn bi_pkg_owner(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "pkg_owner",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    crate::safety::reject_option_like("pkg_owner", std::slice::from_ref(&file))?;
    let pm = detect_package_manager();

    let output = match pm {
        "apt" => {
            let mut cmd = crate::safety::child_command("dpkg");
            cmd.args(["-S", &file]);
            bounded_cmd_output("pkg_owner", "dpkg", cmd, TOOL_DEADLINE_SECS)?
        }
        "pacman" => {
            let mut cmd = crate::safety::child_command("pacman");
            cmd.args(["-Qo", &file]);
            bounded_cmd_output("pkg_owner", "pacman", cmd, TOOL_DEADLINE_SECS)?
        }
        other => return Err(pkg_unsupported("pkg_owner", other)),
    };
    let program = match pm {
        "apt" => "dpkg",
        "pacman" => "pacman",
        other => other,
    };
    if !output.status.success() {
        return Err(pkg_query_failure(
            "pkg_owner",
            "file",
            &file,
            pm,
            program,
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }

    let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let mut rec = std::collections::BTreeMap::new();
    // dpkg -S format: "package: /path/to/file"
    // pacman -Qo format: "/path/to/file is owned by package version"
    if pm == "apt" {
        if let Some((pkg, path)) = text.split_once(": ") {
            rec.insert("package".to_string(), Value::Str(pkg.to_string()));
            rec.insert("file".to_string(), Value::Str(path.to_string()));
        } else {
            rec.insert("package".to_string(), Value::Str(text));
            rec.insert("file".to_string(), Value::Str(file));
        }
    } else if pm == "pacman" {
        // "/path/to/file is owned by package version"
        if let Some(pos) = text.find(" is owned by ") {
            let owned_by = &text[pos + 13..];
            let parts: Vec<&str> = owned_by.split_whitespace().collect();
            rec.insert("file".to_string(), Value::Str(text[..pos].to_string()));
            rec.insert(
                "package".to_string(),
                Value::Str(parts.first().unwrap_or(&"").to_string()),
            );
            if let Some(ver) = parts.get(1) {
                rec.insert("version".to_string(), Value::Str(ver.to_string()));
            }
        } else {
            rec.insert("package".to_string(), Value::Str(text));
            rec.insert("file".to_string(), Value::Str(file));
        }
    } else {
        rec.insert("package".to_string(), Value::Str(text));
        rec.insert("file".to_string(), Value::Str(file));
    }
    Ok(Value::Record(rec))
}

fn bi_pkg_verify(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let package = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "pkg_verify",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    crate::safety::reject_option_like("pkg_verify", std::slice::from_ref(&package))?;
    let pm = detect_package_manager();

    let output = match pm {
        "apt" => {
            let mut cmd = crate::safety::child_command("dpkg");
            cmd.args(["-V", &package]);
            // Verifying every installed file of a package can be slow.
            bounded_cmd_output("pkg_verify", "dpkg", cmd, TOOL_LONG_DEADLINE_SECS)?
        }
        other => return Err(pkg_unsupported("pkg_verify", other)),
    };

    // dpkg -V prints one line per file that fails verification.
    Ok(Value::Bool(
        output.status.success() && String::from_utf8_lossy(&output.stdout).trim().is_empty(),
    ))
}

/// `apt-cache depends` ("  Depends: libc6", "  |Depends: a" for an
/// alternative) or `pacman -Si` ("Depends On : a  b>=1") as records.
fn parse_pkg_deps(pm: &str, text: &str) -> Value {
    let mut out = Vec::new();
    let mut push = |kind: &str, package: &str, alternative: bool| {
        let mut r = BTreeMap::new();
        r.insert("kind".to_string(), Value::Str(kind.to_string()));
        r.insert("package".to_string(), Value::Str(package.to_string()));
        r.insert("alternative".to_string(), Value::Bool(alternative));
        out.push(Value::Record(r));
    };
    if pm == "pacman" {
        for line in text.lines() {
            let Some((key, val)) = line.split_once(':') else {
                continue;
            };
            let kind = match key.trim() {
                "Depends On" => "Depends",
                "Optional Deps" => "Optional",
                "Make Deps" => "MakeDepends",
                _ => continue,
            };
            if val.trim() == "None" {
                continue;
            }
            for dep in val.split_whitespace() {
                push(kind, dep, false);
            }
        }
    } else {
        for line in text.lines().filter(|l| l.starts_with(' ')) {
            let t = line.trim();
            let (alternative, t) = match t.strip_prefix('|') {
                Some(rest) => (true, rest),
                None => (false, t),
            };
            if let Some((kind, pkg)) = t.split_once(':') {
                push(kind.trim(), pkg.trim(), alternative);
            }
        }
    }
    Value::Array(out)
}

/// `apt-cache rdepends` (names under "Reverse Depends:", some repeated per
/// architecture as "name:arm64") or `pacman -Sii` ("Required By : a b") as a
/// de-duplicated list of package names.
fn parse_pkg_rdeps(pm: &str, package: &str, text: &str) -> Value {
    let mut names = std::collections::BTreeSet::new();
    if pm == "pacman" {
        for line in text.lines() {
            if let Some((key, val)) = line.split_once(':') {
                if key.trim() == "Required By" && val.trim() != "None" {
                    names.extend(val.split_whitespace().map(str::to_string));
                }
            }
        }
    } else {
        let mut listing = false;
        for line in text.lines() {
            if line.trim_end() == "Reverse Depends:" {
                listing = true;
            } else if listing && line.starts_with(' ') {
                let n = line.trim().trim_start_matches('|');
                let n = n.split(':').next().unwrap_or(n);
                if !n.is_empty() {
                    names.insert(n.to_string());
                }
            }
        }
    }
    // apt lists the package's other architectures ("coreutils:arm64") among
    // its reverse dependencies; with the suffix gone that is the package.
    names.remove(package);
    Value::Array(names.into_iter().map(Value::Str).collect())
}

fn bi_pkg_deps(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let package = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "pkg_deps",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    crate::safety::reject_option_like("pkg_deps", std::slice::from_ref(&package))?;
    let pm = detect_package_manager();

    let output = match pm {
        "apt" => {
            let mut cmd = crate::safety::child_command("apt-cache");
            cmd.args(["depends", &package]);
            bounded_cmd_output("pkg_deps", "apt-cache", cmd, TOOL_DEADLINE_SECS)?
        }
        "pacman" => {
            let mut cmd = crate::safety::child_command("pacman");
            cmd.args(["-Si", &package]);
            bounded_cmd_output("pkg_deps", "pacman", cmd, TOOL_DEADLINE_SECS)?
        }
        other => return Err(pkg_unsupported("pkg_deps", other)),
    };
    let program = match pm {
        "apt" => "apt-cache",
        "pacman" => "pacman",
        other => other,
    };
    if !output.status.success() {
        return Err(pkg_query_failure(
            "pkg_deps",
            "package",
            &package,
            pm,
            program,
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }

    // This returned the tool's text verbatim, a different format per
    // package manager, which is what typed output exists to replace.
    Ok(parse_pkg_deps(pm, &String::from_utf8_lossy(&output.stdout)))
}

fn bi_pkg_rdeps(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let package = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "pkg_rdeps",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    crate::safety::reject_option_like("pkg_rdeps", std::slice::from_ref(&package))?;
    let pm = detect_package_manager();

    let output = match pm {
        "apt" => {
            let mut cmd = crate::safety::child_command("apt-cache");
            cmd.args(["rdepends", &package]);
            bounded_cmd_output("pkg_rdeps", "apt-cache", cmd, TOOL_DEADLINE_SECS)?
        }
        "pacman" => {
            let mut cmd = crate::safety::child_command("pacman");
            cmd.args(["-Sii", &package]);
            bounded_cmd_output("pkg_rdeps", "pacman", cmd, TOOL_DEADLINE_SECS)?
        }
        other => return Err(pkg_unsupported("pkg_rdeps", other)),
    };
    let program = match pm {
        "apt" => "apt-cache",
        "pacman" => "pacman",
        other => other,
    };
    if !output.status.success() {
        return Err(pkg_query_failure(
            "pkg_rdeps",
            "package",
            &package,
            pm,
            program,
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }

    // This returned the tool's text verbatim, a different format per
    // package manager, which is what typed output exists to replace.
    Ok(parse_pkg_rdeps(
        pm,
        &package,
        &String::from_utf8_lossy(&output.stdout),
    ))
}

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

    #[test]
    fn dpkg_exit_one_is_no_match_for_owner_and_files() {
        assert!(pkg_no_match(
            "pkg_owner",
            "apt",
            Some(1),
            "dpkg-query: no path found matching pattern /nope"
        ));
        assert!(pkg_no_match(
            "pkg_files",
            "apt",
            Some(1),
            "dpkg-query: package 'nope' is not installed"
        ));
        // A dpkg fatal error (exit 2), or a killed process, is a failure.
        assert!(!pkg_no_match(
            "pkg_owner",
            "apt",
            Some(2),
            "dpkg-query: error: bad database"
        ));
        assert!(!pkg_no_match("pkg_owner", "apt", None, ""));
        // Exit 1 is not a no-match for the apt-cache queries.
        assert!(!pkg_no_match(
            "pkg_deps",
            "apt",
            Some(1),
            "E: Unable to locate package x"
        ));
    }

    #[test]
    fn apt_cache_no_packages_found_is_no_match() {
        assert!(pkg_no_match(
            "pkg_info",
            "apt",
            Some(100),
            "E: No packages found"
        ));
        assert!(pkg_no_match(
            "pkg_rdeps",
            "apt",
            Some(100),
            "E: No packages found"
        ));
        assert!(!pkg_no_match(
            "pkg_info",
            "apt",
            Some(100),
            "E: Could not open lock file"
        ));
    }

    #[test]
    fn pacman_search_with_no_match_is_empty_not_a_failure() {
        assert!(pkg_no_match("pkg_search", "pacman", Some(1), ""));
        assert!(!pkg_no_match(
            "pkg_search",
            "pacman",
            Some(1),
            "error: failed to open database"
        ));
        assert!(!pkg_no_match("pkg_search", "pacman", Some(2), ""));
    }

    #[test]
    fn pacman_queries_report_unknown_packages_and_unowned_files() {
        assert!(pkg_no_match(
            "pkg_info",
            "pacman",
            Some(1),
            "error: package 'nope' was not found"
        ));
        assert!(pkg_no_match(
            "pkg_deps",
            "pacman",
            Some(1),
            "error: package 'nope' was not found"
        ));
        assert!(pkg_no_match(
            "pkg_owner",
            "pacman",
            Some(1),
            "error: No package owns /nope"
        ));
        // A lock or database error is a failure, not an answer.
        assert!(!pkg_no_match(
            "pkg_info",
            "pacman",
            Some(1),
            "error: failed to lock database"
        ));
    }

    #[test]
    fn other_managers_no_match_messages() {
        assert!(pkg_no_match(
            "pkg_info",
            "brew",
            Some(1),
            "Error: No available formula with the name \"x\"."
        ));
        assert!(pkg_no_match(
            "pkg_info",
            "dnf",
            Some(1),
            "Error: No matching Packages to list"
        ));
        assert!(!pkg_no_match(
            "pkg_info",
            "winget",
            Some(1),
            "No package found matching input criteria."
        ));
    }

    #[test]
    fn a_no_match_is_e_not_found_and_a_failure_is_e_tool_failed() {
        let e = pkg_query_failure(
            "pkg_info",
            "package",
            "nope",
            "pacman",
            "pacman",
            Some(1),
            "error: package 'nope' was not found",
        )
        .to_string();
        assert!(e.contains("E_NOT_FOUND") && e.contains("nope"), "{e}");
        assert!(!e.contains("E_TOOL_FAILED"), "{e}");

        let e = pkg_query_failure(
            "pkg_owner",
            "file",
            "/x",
            "apt",
            "dpkg",
            Some(2),
            "dpkg-query: error: bad database",
        )
        .to_string();
        assert!(e.contains("E_TOOL_FAILED"), "{e}");
        assert!(e.contains("exited 2") && e.contains("bad database"), "{e}");
    }
}

/// pkg_changelog(package): apt-get changelog for a package, as text. Only apt is
/// supported. A changelog fetch reaches the network, and its output is bounded.
fn bi_pkg_changelog(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "pkg_changelog";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let package = k8s_need(B, "a package name", &args, 0, pkg_plain)?;
    // The package name is not a host, so the dispatcher does not judge it (see
    // EGRESS_JUDGED_BY_BODY). The destination is the configured repository, which
    // the arguments do not name: fail closed under an allowlist, as pkg_install does.
    crate::safety::check_egress_unknown(B, PKG_EGRESS_REASON)?;
    let program = match detect_package_manager() {
        "apt" => "apt-get",
        other => return Err(pkg_unsupported(B, other)),
    };
    let run = tool_run(
        B,
        program,
        None,
        &["changelog", package.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(B, run)?))
}

fn bi_pkg_hold(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::hold(args, input)
}

fn bi_pkg_unhold(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::unhold(args, input)
}

fn bi_pkg_autoremove(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_admin::autoremove(args, input)
}

/// The `limit` argument: absent is the default, otherwise an Int from 1 to 1000.
/// Checked on every OS, before the platform refusal, so a bad call is E_BAD_ARG
/// everywhere.
fn pkg_history_limit(args: &[Value], input: &Option<Value>) -> Result<usize> {
    linux_diagnostics::no_pipeline_input("pkg_history", input)?;
    match args {
        [] => Ok(pkg_query::HISTORY_DEFAULT),
        [Value::Int(n)] if (1..=pkg_query::HISTORY_MAX as i64).contains(n) => Ok(*n as usize),
        [Value::Int(n)] => Err(crate::safety::arg_err(format!(
            "pkg_history: limit must be from 1 to {}, got {n}",
            pkg_query::HISTORY_MAX
        ))),
        [other] => Err(crate::safety::bad_arg(
            "pkg_history",
            "an Int limit from 1 to 1000",
            other.type_name(),
        )),
        more => Err(crate::safety::arg_err(format!(
            "pkg_history takes at most one argument, got {}",
            more.len()
        ))),
    }
}

fn bi_pkg_history(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let limit = pkg_history_limit(&args, &input)?;
    pkg_history_read(limit)
}

/// macOS: the installs in /var/log/install.log, read whole up to the file-size
/// limit and parsed by pkg_query::parse_install_log. Only installs are read, so
/// removed is always empty. Each row has the apt row's shape, with end and
/// command null.
#[cfg(target_os = "macos")]
fn pkg_history_read(limit: usize) -> Result<Value> {
    let text = read_text_capped("pkg_history", pkg_query::INSTALL_LOG)?;
    let rows = pkg_query::parse_install_log(&text, limit);
    Ok(Value::Array(
        rows.into_iter().map(pkg_query::transaction_value).collect(),
    ))
}

#[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
fn pkg_history_read(_limit: usize) -> Result<Value> {
    // The apt history log is Linux's, the install log is macOS's and the
    // Windows Installer log is Windows'. Nothing is read here.
    Err(crate::safety::unimplemented(
        "pkg_history",
        "package history is read from the apt log on Linux, the install log on macOS and the Windows Installer log on Windows; NOTHING WAS READ",
        "ask the package manager directly (brew list)",
    ))
}

#[cfg(windows)]
fn pkg_history_read(limit: usize) -> Result<Value> {
    let script = WIN_PKG_HISTORY_SCRIPT.replace("__LIMIT__", &limit.to_string());
    Ok(Value::Array(win_event_rows("pkg_history", &script)?))
}

#[cfg(target_os = "linux")]
fn pkg_history_read(limit: usize) -> Result<Value> {
    let text = pkg_query::read_history_tail("pkg_history", pkg_query::HISTORY_LOG)?;
    let transactions = pkg_query::parse_history(&text, limit)
        .map_err(|e| pkg_query::parse_failure("pkg_history", "apt history log", e))?;
    Ok(Value::Array(
        transactions
            .into_iter()
            .map(pkg_query::transaction_value)
            .collect(),
    ))
}

// ============================================================================
// 390-399: Hardware & Device Info
// ============================================================================

fn bi_hw_cpu(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_sys_cpu_info(vec![], None)
}

fn bi_hw_memory(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_sys_mem_info(vec![], None)
}

fn bi_hw_disk(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_fs_df(vec![], None)
}

/// The GPU probe: one PowerShell pipeline. Win32_VideoController.AdapterRAM
/// is a uint32, so it cannot say more than 4 GiB. The driver's 64-bit size is
/// in the display class registry key: each adapter's DriverDesc equals its
/// Name, and HardwareInformation.qwMemorySize holds the size. The output is a
/// JSON array (or one object) of Name, AdapterRAM, DriverVersion and
/// QwMemorySize, which is null when no driver key matches.
#[cfg(target_os = "windows")]
const WIN_GPU_PROBE_SCRIPT: &str = r#"$ErrorActionPreference='SilentlyContinue'; $cls='HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}'; $drv=@(Get-ChildItem -LiteralPath $cls | ForEach-Object { Get-ItemProperty -Path $_.PSPath } | Where-Object { $_.DriverDesc } | ForEach-Object { [pscustomobject]@{ Desc=[string]$_.DriverDesc; Qw=$_.'HardwareInformation.qwMemorySize' } }); $rows=@(Get-CimInstance Win32_VideoController | ForEach-Object { $n=$_.Name; $m=@($drv | Where-Object { $_.Desc -eq $n })[0]; $q=$null; if ($m) { $q=$m.Qw }; if ($q -is [byte[]]) { if ($q.Length -ge 8) { $q=[BitConverter]::ToInt64($q,0) } else { $q=$null } }; [pscustomobject]@{ Name=$n; AdapterRAM=$_.AdapterRAM; DriverVersion=$_.DriverVersion; QwMemorySize=$q } }); ConvertTo-Json -InputObject $rows"#;

/// One display adapter from the probe. `vram_bytes` is the driver's 64-bit
/// size when it is positive, else the 32-bit AdapterRAM.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
#[derive(Debug, Clone, PartialEq)]
struct WinGpu {
    name: Option<String>,
    vram_bytes: Option<i64>,
    driver: Option<String>,
}

/// Parses the probe's JSON (an array, or one object) into adapters. Pure, so
/// it is compiled and tested on every platform.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn win_gpus_from_probe(json: &serde_json::Value) -> Vec<WinGpu> {
    let items: Vec<&serde_json::Value> = match json {
        serde_json::Value::Array(arr) => arr.iter().collect(),
        obj @ serde_json::Value::Object(_) => vec![obj],
        _ => vec![],
    };
    items
        .into_iter()
        .filter_map(|item| {
            let o = item.as_object()?;
            let text = |key: &str| o.get(key).and_then(|v| v.as_str()).map(str::to_string);
            let driver_size = o
                .get("QwMemorySize")
                .and_then(|v| v.as_i64())
                .filter(|n| *n > 0);
            let adapter_ram = o.get("AdapterRAM").and_then(|v| v.as_i64());
            Some(WinGpu {
                name: text("Name"),
                vram_bytes: driver_size.or(adapter_ram),
                driver: text("DriverVersion"),
            })
        })
        .collect()
}

/// The hw_gpu record for one adapter: {name, vram, driver}.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn win_gpu_record(g: &WinGpu) -> Value {
    let mut rec = BTreeMap::new();
    if let Some(name) = &g.name {
        rec.insert("name".to_string(), Value::Str(name.clone()));
    }
    if let Some(bytes) = g.vram_bytes {
        rec.insert("vram".to_string(), Value::Int(bytes));
    }
    if let Some(driver) = &g.driver {
        rec.insert("driver".to_string(), Value::Str(driver.clone()));
    }
    Value::Record(rec)
}

/// Runs the GPU probe. `None` when PowerShell fails or prints no JSON.
#[cfg(target_os = "windows")]
fn win_gpu_probe(builtin: &str) -> Result<Option<Vec<WinGpu>>> {
    let mut cmd = crate::safety::child_command("powershell");
    cmd.args(["-Command", WIN_GPU_PROBE_SCRIPT]);
    let output = bounded_cmd_output(builtin, "powershell", cmd, PROBE_DEADLINE_SECS)?;
    if !output.status.success() {
        return Ok(None);
    }
    let text = String::from_utf8_lossy(&output.stdout);
    Ok(serde_json::from_str::<serde_json::Value>(text.trim())
        .ok()
        .map(|json| win_gpus_from_probe(&json)))
}

fn bi_hw_gpu(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        if let Some(gpus) = win_gpu_probe("hw_gpu")? {
            return Ok(Value::Array(gpus.iter().map(win_gpu_record).collect()));
        }
    }
    #[cfg(target_os = "linux")]
    {
        // Use sh -c for proper shell pipeline expansion
        let mut cmd = crate::safety::child_command("sh");
        cmd.args(["-c", "lspci | grep -iE 'vga|3d|display'"]);
        let output = bounded_cmd_output("hw_gpu", "sh", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            let gpus: Vec<Value> = text
                .lines()
                .filter_map(|line| {
                    let mut rec = std::collections::BTreeMap::new();
                    // Format: "01:00.0 VGA compatible controller: NVIDIA Corporation ..."
                    if let Some(desc_start) = line.find(": ") {
                        rec.insert(
                            "name".to_string(),
                            Value::Str(line[desc_start + 2..].to_string()),
                        );
                    } else {
                        rec.insert("name".to_string(), Value::Str(line.to_string()));
                    }
                    Some(Value::Record(rec))
                })
                .collect();
            return Ok(Value::Array(gpus));
        }
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("system_profiler");
        cmd.args(["SPDisplaysDataType", "-json"]);
        // A failing system_profiler, or output that is not the expected JSON,
        // used to answer Null ("no GPU"). Both are errors now.
        let output = bounded_cmd_output("hw_gpu", "system_profiler", cmd, PROBE_DEADLINE_SECS)?;
        let status = output.status.code();
        let json_str = probe_stdout("hw_gpu", "system_profiler", output)?;
        let json: serde_json::Value = serde_json::from_str(&json_str).map_err(|e| {
            crate::safety::tool_failed(
                "hw_gpu",
                "system_profiler SPDisplaysDataType -json",
                status,
                &format!("its output was not JSON: {e}"),
            )
        })?;
        let Some(displays) = json.get("SPDisplaysDataType").and_then(|v| v.as_array()) else {
            return Err(crate::safety::tool_failed(
                "hw_gpu",
                "system_profiler SPDisplaysDataType -json",
                status,
                "its output had no SPDisplaysDataType list",
            ));
        };
        let gpus: Vec<Value> = displays
            .iter()
            .filter_map(|d| {
                let o = d.as_object()?;
                let mut rec = std::collections::BTreeMap::new();
                if let Some(v) = o.get("sppci_model") {
                    rec.insert("name".to_string(), json_to_value(v.clone()));
                }
                if let Some(v) = o.get("spdisplays_vram") {
                    rec.insert("vram".to_string(), json_to_value(v.clone()));
                }
                if let Some(v) = o.get("sppci_vendor") {
                    rec.insert("vendor".to_string(), json_to_value(v.clone()));
                }
                Some(Value::Record(rec))
            })
            .collect();
        return Ok(Value::Array(gpus));
    }
    Ok(Value::Null)
}

fn bi_hw_network(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_net_interfaces(vec![], None)
}

fn bi_hw_usb(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-Command",
            "Get-PnpDevice -Class USB | Select-Object FriendlyName,Status | ConvertTo-Json",
        ]);
        let output = bounded_cmd_output("hw_usb", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                let items = match &json {
                    serde_json::Value::Array(arr) => arr.clone(),
                    obj @ serde_json::Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                let devices: Vec<Value> = items
                    .iter()
                    .filter_map(|obj| {
                        let o = obj.as_object()?;
                        let mut rec = std::collections::BTreeMap::new();
                        if let Some(v) = o.get("FriendlyName") {
                            rec.insert("name".to_string(), json_to_value(v.clone()));
                        }
                        if let Some(v) = o.get("Status") {
                            rec.insert("status".to_string(), json_to_value(v.clone()));
                        }
                        Some(Value::Record(rec))
                    })
                    .collect();
                return Ok(Value::Array(devices));
            }
        }
    }
    #[cfg(target_os = "linux")]
    {
        let cmd = crate::safety::child_command("lsusb");
        let output = bounded_cmd_output("hw_usb", "lsusb", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let devices: Vec<Value> = String::from_utf8_lossy(&output.stdout)
                .lines()
                .map(|line| {
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("name".to_string(), Value::Str(line.to_string()));
                    Value::Record(rec)
                })
                .collect();
            return Ok(Value::Array(devices));
        }
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("system_profiler");
        cmd.args(["SPUSBDataType", "-json"]);
        let output = bounded_cmd_output("hw_usb", "system_profiler", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                if let Some(items) = json.get("SPUSBDataType").and_then(|v| v.as_array()) {
                    let devices: Vec<Value> = items
                        .iter()
                        .filter_map(|item| {
                            let o = item.as_object()?;
                            let mut rec = std::collections::BTreeMap::new();
                            if let Some(v) = o.get("_name") {
                                rec.insert("name".to_string(), json_to_value(v.clone()));
                            }
                            if let Some(v) = o.get("manufacturer") {
                                rec.insert("vendor".to_string(), json_to_value(v.clone()));
                            }
                            Some(Value::Record(rec))
                        })
                        .collect();
                    return Ok(Value::Array(devices));
                }
            }
        }
    }
    // A failed query answered null.
    Err(crate::safety::tool_failed(
        "lsusb",
        "the device query",
        None,
        "it failed or printed nothing usable",
    ))
}

fn bi_hw_pci(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "linux")]
    {
        let cmd = crate::safety::child_command("lspci");
        let output = bounded_cmd_output("hw_pci", "lspci", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let devices: Vec<Value> = String::from_utf8_lossy(&output.stdout)
                .lines()
                .filter_map(|line| {
                    let mut rec = std::collections::BTreeMap::new();
                    if let Some(pos) = line.find(' ') {
                        rec.insert("address".to_string(), Value::Str(line[..pos].to_string()));
                        rec.insert("name".to_string(), Value::Str(line[pos + 1..].to_string()));
                    } else {
                        rec.insert("name".to_string(), Value::Str(line.to_string()));
                    }
                    Some(Value::Record(rec))
                })
                .collect();
            return Ok(Value::Array(devices));
        }
    }
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-Command",
            "Get-PnpDevice | Select-Object FriendlyName,Class | ConvertTo-Json",
        ]);
        let output = bounded_cmd_output("hw_pci", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                let items = match &json {
                    serde_json::Value::Array(arr) => arr.clone(),
                    obj @ serde_json::Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                let devices: Vec<Value> = items
                    .iter()
                    .filter_map(|obj| {
                        let o = obj.as_object()?;
                        let mut rec = std::collections::BTreeMap::new();
                        if let Some(v) = o.get("FriendlyName") {
                            rec.insert("name".to_string(), json_to_value(v.clone()));
                        }
                        if let Some(v) = o.get("Class") {
                            rec.insert("class".to_string(), json_to_value(v.clone()));
                        }
                        Some(Value::Record(rec))
                    })
                    .collect();
                return Ok(Value::Array(devices));
            }
        }
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("system_profiler");
        cmd.args(["SPPCIDataType", "-json"]);
        let output = bounded_cmd_output("hw_pci", "system_profiler", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                if let Some(items) = json.get("SPPCIDataType").and_then(|v| v.as_array()) {
                    let devices: Vec<Value> = items
                        .iter()
                        .filter_map(|item| {
                            let o = item.as_object()?;
                            let mut rec = std::collections::BTreeMap::new();
                            if let Some(v) = o.get("sppci_name") {
                                rec.insert("name".to_string(), json_to_value(v.clone()));
                            }
                            if let Some(v) = o.get("sppci_vendor") {
                                rec.insert("vendor".to_string(), json_to_value(v.clone()));
                            }
                            Some(Value::Record(rec))
                        })
                        .collect();
                    return Ok(Value::Array(devices));
                }
            }
        }
    }
    // A failed query answered null.
    Err(crate::safety::tool_failed(
        "lspci",
        "the device query",
        None,
        "it failed or printed nothing usable",
    ))
}

fn bi_hw_audio(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if !args.is_empty() {
        return Err(crate::safety::bad_arg(
            "hw_audio",
            "no arguments",
            &format!("{} argument(s)", args.len()),
        ));
    }
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-Command",
            "Get-CimInstance Win32_SoundDevice | Select-Object Name,Status | ConvertTo-Json",
        ]);
        let output = bounded_cmd_output("hw_audio", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                let items = match &json {
                    serde_json::Value::Array(arr) => arr.clone(),
                    obj @ serde_json::Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                let devices: Vec<Value> = items
                    .iter()
                    .filter_map(|obj| {
                        let o = obj.as_object()?;
                        let mut rec = std::collections::BTreeMap::new();
                        if let Some(v) = o.get("Name") {
                            rec.insert("name".to_string(), json_to_value(v.clone()));
                        }
                        if let Some(v) = o.get("Status") {
                            rec.insert("status".to_string(), json_to_value(v.clone()));
                        }
                        Some(Value::Record(rec))
                    })
                    .collect();
                return Ok(Value::Array(devices));
            }
        }
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("aplay");
        cmd.args(["-l"]);
        let output = bounded_cmd_output("hw_audio", "aplay", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let devices: Vec<Value> = String::from_utf8_lossy(&output.stdout)
                .lines()
                .filter(|line| line.starts_with("card "))
                .map(|line| {
                    let mut rec = std::collections::BTreeMap::new();
                    rec.insert("name".to_string(), Value::Str(line.to_string()));
                    Value::Record(rec)
                })
                .collect();
            return Ok(Value::Array(devices));
        }
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("system_profiler");
        cmd.args(["SPAudioDataType", "-json"]);
        let output = bounded_cmd_output("hw_audio", "system_profiler", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                if let Some(items) = json.get("SPAudioDataType").and_then(|v| v.as_array()) {
                    let devices: Vec<Value> = items
                        .iter()
                        .filter_map(|item| {
                            let o = item.as_object()?;
                            let mut rec = std::collections::BTreeMap::new();
                            if let Some(v) = o.get("_name") {
                                rec.insert("name".to_string(), json_to_value(v.clone()));
                            }
                            if let Some(v) = o.get("coreaudio_default_audio_output_device") {
                                rec.insert("default_output".to_string(), json_to_value(v.clone()));
                            }
                            Some(Value::Record(rec))
                        })
                        .collect();
                    return Ok(Value::Array(devices));
                }
            }
        }
    }
    // Reached only when the query above did not yield a list. That used to be
    // Ok(Null), which reads as "no audio devices" and hid a failed query.
    #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
    {
        Err(crate::safety::tool_failed(
            "hw_audio",
            "the audio device query",
            None,
            "it failed or printed nothing usable",
        ))
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            "hw_audio",
            "audio device listing is not implemented on this operating system",
            "list audio devices with the platform's own tool",
        ))
    }
}

/// The charge percentage in a sysfs `capacity` file. Anything that is not an
/// integer is refused as an unreadable file, never read as 0%.
#[cfg(any(target_os = "linux", test))]
fn battery_capacity_from(path: &str, text: &str) -> Result<i64> {
    text.trim().parse::<i64>().map_err(|_| {
        let cause = std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("`{}` is not a percentage", text.trim()),
        );
        crate::safety::fs_error("hw_battery", path, &cause)
    })
}

/// Maps Win32_Battery.BatteryStatus (Microsoft's documented codes) to the
/// status string hw_battery reports on Windows. 2 is "ac": on AC power and not
/// charging, which is what a UPS reports. The Linux branch reads sysfs and
/// reports "not charging" for the same state.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn windows_battery_status(code: i64) -> &'static str {
    match code {
        1 => "discharging",
        2 => "ac",
        3 => "full",
        4 => "low",
        5 => "critical",
        6..=9 => "charging",
        11 => "partially_charged",
        _ => "unknown",
    }
}

/// The hw_battery record from the Win32_Battery probe JSON (an object, or the
/// first element of an array). `name` is Win32_Battery's Name when present, so
/// a UPS can be told from a laptop battery.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn windows_battery_from_probe(json: &serde_json::Value) -> Option<Value> {
    let obj = match json {
        serde_json::Value::Object(o) => o,
        serde_json::Value::Array(arr) => arr.first()?.as_object()?,
        _ => return None,
    };
    let mut rec = BTreeMap::new();
    if let Some(v) = obj.get("EstimatedChargeRemaining").and_then(|v| v.as_i64()) {
        rec.insert("capacity".to_string(), Value::Int(v));
    }
    let status = obj
        .get("BatteryStatus")
        .and_then(|v| v.as_i64())
        .map_or("unknown", windows_battery_status);
    rec.insert("status".to_string(), Value::Str(status.to_string()));
    if let Some(name) = obj
        .get("Name")
        .and_then(|v| v.as_str())
        .filter(|s| !s.trim().is_empty())
    {
        rec.insert("name".to_string(), Value::Str(name.to_string()));
    }
    Some(Value::Record(rec))
}

fn bi_hw_battery(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Returns Record {capacity: Int (%), status: String, name: String (Windows)}
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd
            .args(["-Command", "Get-CimInstance Win32_Battery | Select-Object Name,EstimatedChargeRemaining,BatteryStatus | ConvertTo-Json"]);
        let output = bounded_cmd_output("hw_battery", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                if let Some(rec) = windows_battery_from_probe(&json) {
                    return Ok(rec);
                }
            }
        }
    }
    #[cfg(target_os = "linux")]
    {
        let capacity_path = "/sys/class/power_supply/BAT0/capacity";
        let status_path = "/sys/class/power_supply/BAT0/status";
        let mut rec = std::collections::BTreeMap::new();
        // No BAT0 is a host without that battery. A capacity that is not a
        // number used to be read as 0%, which is a real and alarming answer.
        match std::fs::read_to_string(capacity_path) {
            Ok(text) => {
                rec.insert(
                    "capacity".to_string(),
                    Value::Int(battery_capacity_from(capacity_path, &text)?),
                );
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(crate::safety::fs_error("hw_battery", capacity_path, &e)),
        }
        if let Ok(status) = std::fs::read_to_string(status_path) {
            rec.insert(
                "status".to_string(),
                Value::Str(status.trim().to_lowercase()),
            );
        }
        if !rec.is_empty() {
            return Ok(Value::Record(rec));
        }
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("pmset");
        cmd.args(["-g", "batt"]);
        let output = bounded_cmd_output("hw_battery", "pmset", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            let mut rec = std::collections::BTreeMap::new();
            // Format: "... XX%; charging/discharging/charged; ..."
            for line in text.lines() {
                if let Some(pct_pos) = line.find('%') {
                    // Walk backwards from % to find the number
                    let before = &line[..pct_pos];
                    let num_str: String = before
                        .chars()
                        .rev()
                        .take_while(|c| c.is_ascii_digit())
                        .collect::<String>()
                        .chars()
                        .rev()
                        .collect();
                    if let Ok(cap) = num_str.parse::<i64>() {
                        rec.insert("capacity".to_string(), Value::Int(cap));
                    }
                    // Status is after %; like "charging" or "discharging"
                    let after = &line[pct_pos + 1..];
                    for part in after.split(';') {
                        let part = part.trim().to_lowercase();
                        if part.contains("charging")
                            || part.contains("charged")
                            || part.contains("discharging")
                        {
                            let status = if part.contains("discharging") {
                                "discharging"
                            } else if part.contains("charged") {
                                "full"
                            } else {
                                "charging"
                            };
                            rec.insert("status".to_string(), Value::Str(status.to_string()));
                            break;
                        }
                    }
                }
            }
            if !rec.is_empty() {
                return Ok(Value::Record(rec));
            }
        }
    }
    Ok(Value::Null)
}

fn bi_hw_sensors(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Returns consistent Array of Records {name: String, temp_c: Float}
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd
            .args(["-Command", "Get-CimInstance MSAcpi_ThermalZoneTemperature -Namespace root/wmi 2>$null | Select-Object InstanceName,CurrentTemperature | ConvertTo-Json"]);
        let output = bounded_cmd_output("hw_sensors", "powershell", cmd, PROBE_DEADLINE_SECS)?;
        if output.status.success() {
            let json_str = String::from_utf8_lossy(&output.stdout);
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
                let items = match &json {
                    serde_json::Value::Array(arr) => arr.clone(),
                    obj @ serde_json::Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                let sensors: Vec<Value> = items
                    .iter()
                    .filter_map(|obj| {
                        let o = obj.as_object()?;
                        let mut rec = std::collections::BTreeMap::new();
                        if let Some(v) = o.get("InstanceName") {
                            rec.insert("name".to_string(), json_to_value(v.clone()));
                        }
                        // WMI returns tenths of kelvin
                        if let Some(v) = o.get("CurrentTemperature").and_then(|v| v.as_f64()) {
                            rec.insert("temp_c".to_string(), Value::Float((v / 10.0) - 273.15));
                        }
                        Some(Value::Record(rec))
                    })
                    .collect();
                return Ok(Value::Array(sensors));
            }
        }
    }
    #[cfg(target_os = "linux")]
    {
        // Try /sys/class/thermal first for structured data
        let thermal_dir = std::path::Path::new("/sys/class/thermal");
        if thermal_dir.exists() {
            let mut sensors = Vec::new();
            if let Ok(entries) = std::fs::read_dir(thermal_dir) {
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.starts_with("thermal_zone") {
                        let temp_path = entry.path().join("temp");
                        let type_path = entry.path().join("type");
                        let mut rec = std::collections::BTreeMap::new();
                        let zone_name = std::fs::read_to_string(&type_path)
                            .unwrap_or_else(|_| name.clone())
                            .trim()
                            .to_string();
                        rec.insert("name".to_string(), Value::Str(zone_name));
                        if let Ok(temp_str) = std::fs::read_to_string(&temp_path) {
                            if let Ok(millideg) = temp_str.trim().parse::<f64>() {
                                rec.insert("temp_c".to_string(), Value::Float(millideg / 1000.0));
                            }
                        }
                        sensors.push(Value::Record(rec));
                    }
                }
            }
            if !sensors.is_empty() {
                return Ok(Value::Array(sensors));
            }
        }
    }
    #[cfg(target_os = "macos")]
    {
        // macOS doesn't expose thermal sensors easily without IOKit bindings;
        // use powermetrics or osx-cpu-temp if available, fallback to empty
        let mut sensors_cmd = crate::safety::child_command("sh");
        sensors_cmd.args(["-c", "which osx-cpu-temp && osx-cpu-temp"]);
        let output = bounded_cmd_output("hw_sensors", "sh", sensors_cmd, PROBE_DEADLINE_SECS);
        if let Ok(out) = output {
            if out.status.success() {
                let text = String::from_utf8_lossy(&out.stdout);
                let mut rec = std::collections::BTreeMap::new();
                rec.insert("name".to_string(), Value::Str("CPU".to_string()));
                // Parse "65.0°C" style output
                let temp_str: String = text
                    .chars()
                    .take_while(|c| c.is_ascii_digit() || *c == '.')
                    .collect();
                if let Ok(temp) = temp_str.parse::<f64>() {
                    rec.insert("temp_c".to_string(), Value::Float(temp));
                }
                return Ok(Value::Array(vec![Value::Record(rec)]));
            }
        }
    }
    Ok(Value::Null)
}

// ============================================================================
// 400-429: GUI Automation
// ============================================================================

/// Largest window title, prompt, message or path a GUI builtin takes.
const GUI_FIELD_MAX_BYTES: usize = 4096;
/// Deadline for a desktop dialog (zenity, osascript). A person answers it, so
/// it waits far longer than a probe, but a dialog nobody dismisses must still
/// end: the child is killed at this deadline and the call is a budget error.
const GUI_DIALOG_DEADLINE_SECS: u64 = 300;
/// Largest text `gui_type_text` types in one call.
const GUI_TYPE_MAX_BYTES: usize = 10_000;
/// Largest clipboard text one call reads or writes.
const CLIPBOARD_MAX_BYTES: usize = 8 * 1024 * 1024;
/// Longest key spec `gui_key_press` and `gui_key_combo` accept.
const GUI_KEY_MAX_BYTES: usize = 64;
/// Bound on a screen coordinate, in pixels, in either direction.
const GUI_COORD_LIMIT: i64 = 100_000;
/// The keys a key call names by word. A single letter or digit is also accepted.
const GUI_NAMED_KEYS: &[&str] = &[
    "enter",
    "tab",
    "esc",
    "space",
    "backspace",
    "delete",
    "home",
    "end",
    "pageup",
    "pagedown",
    "up",
    "down",
    "left",
    "right",
    "f1",
    "f2",
    "f3",
    "f4",
    "f5",
    "f6",
    "f7",
    "f8",
    "f9",
    "f10",
    "f11",
    "f12",
];

/// A String argument of a GUI or clipboard builtin: at most `max` bytes, free
/// of control characters other than newline and tab, and non-empty unless
/// `allow_empty`. Anything else is refused before a tool runs.
fn gui_text(
    name: &str,
    what: &str,
    value: &Value,
    max: usize,
    allow_empty: bool,
) -> Result<String> {
    let s = match value {
        Value::Str(s) => s,
        other => {
            return Err(crate::safety::bad_arg(
                name,
                &format!("{what}: String"),
                other.type_name(),
            ))
        }
    };
    if s.len() > max {
        return Err(crate::safety::bad_arg(
            name,
            &format!("{what} of at most {max} bytes"),
            &format!("{} bytes", s.len()),
        ));
    }
    if s.is_empty() && !allow_empty {
        return Err(crate::safety::bad_arg(
            name,
            &format!("{what}: a non-empty String"),
            "an empty String",
        ));
    }
    if s.chars().any(|c| c.is_control() && c != '\n' && c != '\t') {
        return Err(crate::safety::bad_arg(
            name,
            &format!("{what} without control characters"),
            "a control character",
        ));
    }
    Ok(s.clone())
}

/// The argument at `index`, which the signature makes required. A caller that
/// reaches here without it is refused, not allowed to panic.
fn gui_required<'a>(name: &str, args: &'a [Value], index: usize, what: &str) -> Result<&'a Value> {
    args.get(index)
        .ok_or_else(|| crate::safety::bad_arg(name, what, "nothing"))
}

/// Refuses pipeline input for a GUI or clipboard builtin that takes none.
fn refuse_piped_input(name: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            name,
            "no pipeline input",
            "piped input",
        ));
    }
    Ok(())
}

/// A screen coordinate or pointer position: an Int within `GUI_COORD_LIMIT`.
fn gui_coord(name: &str, what: &str, value: &Value) -> Result<i64> {
    match value {
        Value::Int(n) if (-GUI_COORD_LIMIT..=GUI_COORD_LIMIT).contains(n) => Ok(*n),
        Value::Int(n) => Err(crate::safety::bad_arg(
            name,
            &format!("{what} in -{GUI_COORD_LIMIT}..={GUI_COORD_LIMIT}"),
            &n.to_string(),
        )),
        other => Err(crate::safety::bad_arg(
            name,
            &format!("{what}: Int"),
            other.type_name(),
        )),
    }
}

/// A window size in pixels: an Int from 1 to `GUI_COORD_LIMIT`.
fn gui_size(name: &str, what: &str, value: &Value) -> Result<i64> {
    match value {
        Value::Int(n) if (1..=GUI_COORD_LIMIT).contains(n) => Ok(*n),
        Value::Int(n) => Err(crate::safety::bad_arg(
            name,
            &format!("{what} in 1..={GUI_COORD_LIMIT}"),
            &n.to_string(),
        )),
        other => Err(crate::safety::bad_arg(
            name,
            &format!("{what}: Int"),
            other.type_name(),
        )),
    }
}

/// The last kilobyte of a tool's stderr, for a coded error: a noisy tool
/// cannot flood the message.
fn gui_stderr_tail(output: &std::process::Output) -> String {
    let owned = String::from_utf8_lossy(&output.stderr).into_owned();
    let text = owned.trim();
    let mut start = text.len().saturating_sub(1024);
    while !text.is_char_boundary(start) {
        start += 1;
    }
    text[start..].to_string()
}

/// The answer of a desktop action whose tool reports only success or failure:
/// `true` when it worked. A failure is a coded tool error, never a `false`
/// that could just as well mean the target was not there.
fn gui_action(name: &str, tool: &str, output: &std::process::Output) -> Result<Value> {
    if output.status.success() {
        Ok(Value::Bool(true))
    } else {
        Err(crate::safety::tool_failed(
            name,
            tool,
            output.status.code(),
            &gui_stderr_tail(output),
        ))
    }
}

/// `gui_action` for a window operation. `missing` is the exit status the tool
/// or script uses when no window has the title: E_NOT_FOUND, not a failure.
fn gui_window_action(
    name: &str,
    tool: &str,
    title: &str,
    missing: i32,
    output: &std::process::Output,
) -> Result<Value> {
    if output.status.code() == Some(missing) {
        return Err(crate::safety::not_found(name, "window", title));
    }
    gui_action(name, tool, output)
}

/// A dialog that answers with a path or text on stdout. Exit 0 is the answer
/// (an empty one is Null); `cancel` is the exit status of a user who closed
/// the dialog, which is Null too. Any other exit is a coded tool failure.
fn gui_dialog_answer(
    name: &str,
    tool: &str,
    cancel: Option<i32>,
    output: &std::process::Output,
) -> Result<Value> {
    if output.status.success() {
        let answer = String::from_utf8_lossy(&output.stdout)
            .trim_end_matches(['\r', '\n'])
            .trim()
            .to_string();
        return Ok(if answer.is_empty() {
            Value::Null
        } else {
            Value::Str(answer)
        });
    }
    if cancel.is_some() && output.status.code() == cancel {
        return Ok(Value::Null);
    }
    Err(crate::safety::tool_failed(
        name,
        tool,
        output.status.code(),
        &gui_stderr_tail(output),
    ))
}

/// A confirmation dialog: `true` when it was acknowledged, `false` when the
/// user dismissed it (exit 1, which both zenity and osascript use for that).
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn gui_dialog_ack(name: &str, tool: &str, output: &std::process::Output) -> Result<Value> {
    if output.status.success() {
        return Ok(Value::Bool(true));
    }
    if output.status.code() == Some(1) {
        return Ok(Value::Bool(false));
    }
    Err(crate::safety::tool_failed(
        name,
        tool,
        output.status.code(),
        &gui_stderr_tail(output),
    ))
}

/// A JSON answer on stdout, as a Value. A failed run, or an answer that is
/// not JSON, is a coded tool failure.
#[cfg(any(target_os = "windows", target_os = "macos"))]
fn gui_json_answer(name: &str, tool: &str, output: &std::process::Output) -> Result<Value> {
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            name,
            tool,
            output.status.code(),
            &gui_stderr_tail(output),
        ));
    }
    let text = String::from_utf8_lossy(&output.stdout).into_owned();
    serde_json::from_str::<serde_json::Value>(text.trim())
        .map(json_to_value)
        .map_err(|e| {
            crate::safety::tool_failed(
                name,
                tool,
                Some(0),
                &format!("its answer was not JSON: {e}"),
            )
        })
}

/// Runs a PowerShell script with no profile, no prompts, and errors that
/// stop the script (so a failed step exits nonzero instead of passing).
#[cfg(target_os = "windows")]
fn gui_powershell(name: &str, script: &str) -> Result<std::process::Output> {
    let full = format!("$ErrorActionPreference = 'Stop'\n{script}");
    let mut cmd = crate::safety::child_command("powershell");
    cmd.args(["-NoProfile", "-NonInteractive", "-Command", &full]);
    bounded_cmd_output(name, "powershell", cmd, TOOL_DEADLINE_SECS)
}

/// A key named by a key call: its modifiers, then one key.
#[derive(Clone, Copy)]
enum GuiMod {
    Ctrl,
    Alt,
    Shift,
}

struct GuiKey {
    mods: Vec<GuiMod>,
    key: String,
}

/// Parses `ctrl+shift+t`, `enter`, `a`, `f5` and the like. Modifiers come
/// first, then exactly one key: a letter, a digit, or a name from
/// `GUI_NAMED_KEYS`. Anything else is refused before a tool runs.
fn parse_gui_key(name: &str, spec: &str) -> Result<GuiKey> {
    const EXPECTED: &str = "a key such as enter, a, f5 or ctrl+shift+t";
    if spec.len() > GUI_KEY_MAX_BYTES {
        return Err(crate::safety::bad_arg(
            name,
            EXPECTED,
            &format!("{} bytes", spec.len()),
        ));
    }
    let lowered = spec.to_ascii_lowercase();
    let mut tokens: Vec<&str> = lowered.split('+').map(str::trim).collect();
    let key = tokens.pop().unwrap_or("");
    let mut mods = Vec::new();
    for token in tokens {
        mods.push(match token {
            "ctrl" | "control" => GuiMod::Ctrl,
            "alt" => GuiMod::Alt,
            "shift" => GuiMod::Shift,
            _ => return Err(crate::safety::bad_arg(name, EXPECTED, spec)),
        });
    }
    let single = key.chars().count() == 1 && key.chars().all(|c| c.is_ascii_alphanumeric());
    if !single && !GUI_NAMED_KEYS.contains(&key) {
        return Err(crate::safety::bad_arg(name, EXPECTED, spec));
    }
    Ok(GuiKey {
        mods,
        key: key.to_string(),
    })
}

/// The SendKeys spelling of a parsed key.
#[cfg(target_os = "windows")]
fn gui_sendkeys(key: &GuiKey) -> String {
    let mut out = String::new();
    for m in &key.mods {
        out.push_str(match m {
            GuiMod::Ctrl => "^",
            GuiMod::Alt => "%",
            GuiMod::Shift => "+",
        });
    }
    let key_text = match key.key.as_str() {
        "pageup" => "{PGUP}".to_string(),
        "pagedown" => "{PGDN}".to_string(),
        named if GUI_NAMED_KEYS.contains(&named) => format!("{{{}}}", named.to_ascii_uppercase()),
        single => single.to_string(),
    };
    out.push_str(&key_text);
    out
}

/// The SendKeys spelling of literal text: every character SendKeys treats as
/// syntax is sent as itself.
#[cfg(target_os = "windows")]
fn gui_sendkeys_text(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '{' => out.push_str("{{}"),
            '}' => out.push_str("{}}"),
            '+' | '^' | '%' | '~' | '(' | ')' | '[' | ']' => {
                out.push('{');
                out.push(c);
                out.push('}');
            }
            '\n' => out.push_str("{ENTER}"),
            '\t' => out.push_str("{TAB}"),
            other => out.push(other),
        }
    }
    out
}

/// The xdotool spelling of a parsed key, e.g. `ctrl+shift+t` or `Return`.
#[cfg(target_os = "linux")]
fn gui_xdotool_key(key: &GuiKey) -> String {
    let mut parts: Vec<String> = key
        .mods
        .iter()
        .map(|m| match m {
            GuiMod::Ctrl => "ctrl".to_string(),
            GuiMod::Alt => "alt".to_string(),
            GuiMod::Shift => "shift".to_string(),
        })
        .collect();
    let key_name = match key.key.as_str() {
        "enter" => "Return".to_string(),
        "tab" => "Tab".to_string(),
        "esc" => "Escape".to_string(),
        "space" => "space".to_string(),
        "backspace" => "BackSpace".to_string(),
        "delete" => "Delete".to_string(),
        "home" => "Home".to_string(),
        "end" => "End".to_string(),
        "pageup" => "Prior".to_string(),
        "pagedown" => "Next".to_string(),
        "up" => "Up".to_string(),
        "down" => "Down".to_string(),
        "left" => "Left".to_string(),
        "right" => "Right".to_string(),
        named if GUI_NAMED_KEYS.contains(&named) => named.to_ascii_uppercase(),
        single => single.to_string(),
    };
    parts.push(key_name);
    parts.join("+")
}

/// The Windows button codes for a mouse button, as (down, up).
#[cfg(target_os = "windows")]
fn gui_mouse_codes(button: &str) -> (u32, u32) {
    match button {
        "right" => (0x0008, 0x0010),
        "middle" => (0x0020, 0x0040),
        _ => (0x0002, 0x0004),
    }
}

/// The button of a click: "left", "right" or "middle", or 1, 2 or 3 (left,
/// middle, right, as xdotool numbers them). Absent means left.
fn gui_button(name: &str, args: &[Value], index: usize) -> Result<&'static str> {
    match args.get(index) {
        None => Ok("left"),
        Some(Value::Str(s)) => match s.as_str() {
            "left" => Ok("left"),
            "right" => Ok("right"),
            "middle" => Ok("middle"),
            _ => Err(crate::safety::bad_arg(
                name,
                "button: \"left\", \"right\" or \"middle\" (or 1, 2 or 3)",
                s,
            )),
        },
        Some(Value::Int(1)) => Ok("left"),
        Some(Value::Int(2)) => Ok("middle"),
        Some(Value::Int(3)) => Ok("right"),
        Some(other) => Err(crate::safety::bad_arg(
            name,
            "button: \"left\", \"right\" or \"middle\" (or 1, 2 or 3)",
            other.type_name(),
        )),
    }
}

/// Escapes a window title for xdotool's regular-expression `--name`.
#[cfg(target_os = "linux")]
fn gui_regex_escape(text: &str) -> String {
    let mut out = String::with_capacity(text.len() * 2);
    for c in text.chars() {
        if ".^$*+?()[]{}|\\".contains(c) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// Clipboard text as a String, refused above `CLIPBOARD_MAX_BYTES` rather than
/// returned in part.
fn clipboard_answer(name: &str, bytes: &[u8]) -> Result<Value> {
    if bytes.len() > CLIPBOARD_MAX_BYTES {
        return Err(crate::safety::budget_exceeded(
            name,
            format!(
                "the clipboard holds {} bytes of text, more than the {CLIPBOARD_MAX_BYTES} this call returns",
                bytes.len()
            ),
            "read the clipboard with a platform tool that streams it",
        ));
    }
    Ok(Value::Str(String::from_utf8_lossy(bytes).into_owned()))
}

/// The osascript (JavaScript) behind the macOS window builtins. `argv[0]` picks
/// the operation: `list`, or a window operation whose target is `argv[1]`, the
/// exact window title, and whose numbers follow it. The title and numbers are
/// only ever arguments, never script text. A window that no System Events
/// process has exits 3, the not-found status the builtins map to E_NOT_FOUND.
/// Accessibility refusals (-1719, -25211) are thrown, so they reach the caller
/// as E_OS_DENIED rather than as a false "no such window".
#[cfg(target_os = "macos")]
const MACOS_WINDOW_ADMIN_JXA: &str = r#"ObjC.import('stdlib');
ObjC.import('AppKit');
ObjC.import('CoreGraphics');
ObjC.import('ApplicationServices');
function denied(e) {
    return /-1719|-25211|assistive access/.test(String(e));
}
// The owner pids of on-screen ordinary windows titled exactly `title`.
function ownersOf(title) {
    var all = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo(17, 0))) || [];
    var pids = [];
    for (var k = 0; k < all.length; k++) {
        if (all[k].kCGWindowLayer === 0 && all[k].kCGWindowName === title) {
            pids.push(all[k].kCGWindowOwnerPID);
        }
    }
    return pids;
}
// The first System Events window whose name is exactly `title`, as
// {proc, win}; null when no window has that name. The processes that own a
// window of that title in CGWindowList are asked first; every process is the
// fallback. Errors other than an Accessibility refusal skip a process, and
// are logged to stderr so a miss can be told from a refusal.
function findWindow(se, title) {
    var procs = [];
    var owners = ownersOf(title);
    for (var o = 0; o < owners.length; o++) {
        try {
            procs = procs.concat(se.processes.whose({unixId: owners[o]})());
        } catch (e) {
            if (denied(e)) throw e;
            console.log('pid ' + owners[o] + ': ' + e);
        }
    }
    var asked = procs.length;
    procs = procs.concat(se.processes());
    // Trust was checked before this ran, so a refusal here is one process
    // refusing, not ae being untrusted. From an owner of a window with this
    // title it is fatal, since the window is there; from any other process it
    // only skips that process. Treating every refusal as fatal made a title
    // no window has unanswerable whenever one such process was running: the
    // scan for a missing title is the one that reaches every process. The
    // log line avoids the refusal markers, which the caller reads as E_OS_DENIED.
    var skipped = 0;
    for (var i = 0; i < procs.length; i++) {
        var wins = [];
        try {
            wins = procs[i].windows();
        } catch (e) {
            if (denied(e) && i < asked) throw e;
            if (denied(e)) skipped++;
            if (i < asked) console.log('windows of owner: ' + e);
            continue;
        }
        if (i < asked) console.log('owner has ' + wins.length + ' System Events windows');
        for (var j = 0; j < wins.length; j++) {
            var name;
            try {
                name = wins[j].name();
            } catch (e) {
                if (denied(e) && i < asked) throw e;
                continue;
            }
            if (name === title) return {proc: procs[i], win: wins[j]};
        }
    }
    if (skipped > 0) console.log(skipped + ' processes without the window title refused scripting; skipped');
    return null;
}
function run(argv) {
    var op = argv[0];
    if (op === 'list') {
        // Option 17 is kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements;
        // 0 is kCGNullWindowID. Layer 0 is ordinary windows (not menus or the Dock).
        var all = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo(17, 0))) || [];
        var out = [];
        for (var k = 0; k < all.length; k++) {
            var w = all[k];
            if (w.kCGWindowLayer !== 0) continue;
            if (typeof w.kCGWindowName !== 'string' || w.kCGWindowName === '') continue;
            out.push({hwnd: w.kCGWindowNumber, title: w.kCGWindowName, pid: w.kCGWindowOwnerPID});
        }
        return JSON.stringify(out);
    }
    var title = argv[1];
    // Without Accessibility trust System Events answers every process with
    // no windows rather than an error, which would read as "no such window".
    if (!$.AXIsProcessTrusted()) {
        throw new Error('-25211 not allowed assistive access (AXIsProcessTrusted is false)');
    }
    var found = findWindow(Application('System Events'), title);
    if (found === null) {
        $.exit(3);
    }
    var win = found.win;
    switch (op) {
        case 'focus':
            found.proc.frontmost = true;
            win.actions.byName('AXRaise').perform();
            break;
        case 'minimize':
            win.attributes.byName('AXMinimized').value = true;
            break;
        case 'maximize':
            // System Events positions are top-left origin, measured from the
            // primary display; Cocoa's visibleFrame is bottom-left origin.
            var screen = $.NSScreen.mainScreen || $.NSScreen.screens.objectAtIndex(0);
            var vf = screen.visibleFrame;
            var primary = $.NSScreen.screens.objectAtIndex(0).frame;
            win.position = [
                Math.round(vf.origin.x),
                Math.round(primary.size.height - (vf.origin.y + vf.size.height))
            ];
            win.size = [Math.round(vf.size.width), Math.round(vf.size.height)];
            break;
        case 'close':
            var buttons = win.buttons();
            var close = null;
            for (var b = 0; b < buttons.length; b++) {
                if (buttons[b].subrole() === 'AXCloseButton') {
                    close = buttons[b];
                    break;
                }
            }
            if (close === null) throw new Error('the window has no close button');
            close.click();
            break;
        case 'move':
            win.position = [Number(argv[2]), Number(argv[3])];
            break;
        case 'resize':
            win.size = [Number(argv[2]), Number(argv[3])];
            break;
        default:
            throw new Error('unknown window operation ' + op);
    }
    return 'ok';
}
"#;

/// Runs a JavaScript body with `/usr/bin/osascript -l JavaScript -e`, with
/// `argv` as its arguments. The arguments are never script text. An
/// Accessibility refusal (-1719, -25211) is E_OS_DENIED with `reason` and
/// `hint`; any other failure is left to the caller to report.
#[cfg(target_os = "macos")]
fn gui_macos_jxa(
    name: &str,
    script: &str,
    argv: &[&str],
    reason: &str,
    hint: &str,
) -> Result<std::process::Output> {
    let mut cmd = crate::safety::child_command("/usr/bin/osascript");
    cmd.args(["-l", "JavaScript", "-e", script]);
    cmd.args(argv);
    let output = bounded_cmd_output(name, "osascript", cmd, TOOL_DEADLINE_SECS)?;
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !output.status.success()
        && ["-1719", "-25211", "not allowed assistive access"]
            .iter()
            .any(|marker| stderr.contains(marker))
    {
        return Err(crate::safety::os_denied(name, reason, hint));
    }
    Ok(output)
}

/// Runs `MACOS_WINDOW_ADMIN_JXA` with `/usr/bin/osascript`: `op`, then the
/// operands as argv. Accessibility refusals are E_OS_DENIED with a hint.
#[cfg(target_os = "macos")]
fn gui_macos_window_admin(name: &str, op: &str, operands: &[&str]) -> Result<std::process::Output> {
    let mut argv: Vec<&str> = vec![op];
    argv.extend_from_slice(operands);
    gui_macos_jxa(
        name,
        MACOS_WINDOW_ADMIN_JXA,
        &argv,
        "System Events is not allowed to control windows: Accessibility access is not granted to the process running ae",
        "grant Accessibility in System Settings > Privacy & Security > Accessibility to the terminal or app that runs ae, then retry",
    )
}

/// The osascript (JavaScript) behind the macOS input builtins. `argv[0]` picks
/// the operation: `move x y`, `click button`, `drag x1 y1 x2 y2`, `scroll
/// notches`, `pos`, `key code flags`, `combo code flags`, `type text`, `active`
/// or `screen`. Every number and name is validated in Rust before this runs,
/// and the text is only ever an argument. Each event goes through the HID event
/// tap. Posting events needs Accessibility, so the operations that post are
/// refused first, with the -25211 marker that maps to E_OS_DENIED, and nothing
/// is sent.
#[cfg(target_os = "macos")]
const MACOS_INPUT_ADMIN_JXA: &str = r#"ObjC.import('stdlib');
ObjC.import('AppKit');
ObjC.import('CoreGraphics');
ObjC.import('ApplicationServices');
// No ObjC.bindFunction: a signature the bridge rejects raises an NSException
// that JavaScript cannot catch, and osascript dies before any operation runs
// (run 40845668146). Only bridged functions are used, each checked first, so
// a missing one is a named failure of that operation alone.
function need(name) {
    if (typeof $[name] !== 'function') {
        throw new Error('-1 ' + name + ' is not available to JavaScript for Automation on this macOS');
    }
    return $[name];
}
var TRUST_NEEDED = {move: 1, click: 1, drag: 1, scroll: 1, key: 1, combo: 1, type: 1};
function post(ev) {
    $.CGEventPost($.kCGHIDEventTap, ev);
}
function here() {
    var p = $.CGEventGetLocation($.CGEventCreate(null));
    return {x: p.x, y: p.y};
}
function mouse(type, x, y, button) {
    post($.CGEventCreateMouseEvent(null, type, {x: x, y: y}, button));
}
function clickAt(button) {
    var p = here();
    if (button === 'right') {
        mouse($.kCGEventRightMouseDown, p.x, p.y, $.kCGMouseButtonRight);
        mouse($.kCGEventRightMouseUp, p.x, p.y, $.kCGMouseButtonRight);
    } else if (button === 'middle') {
        mouse($.kCGEventOtherMouseDown, p.x, p.y, $.kCGMouseButtonCenter);
        mouse($.kCGEventOtherMouseUp, p.x, p.y, $.kCGMouseButtonCenter);
    } else {
        mouse($.kCGEventLeftMouseDown, p.x, p.y, $.kCGMouseButtonLeft);
        mouse($.kCGEventLeftMouseUp, p.x, p.y, $.kCGMouseButtonLeft);
    }
}
// A virtual key with its modifier flags set on the event, pressed or released.
function keyEvent(code, flags, down) {
    var ev = $.CGEventCreateKeyboardEvent(null, code, down);
    $.CGEventSetFlags(ev, flags);
    post(ev);
}
// Types a chunk of at most 20 UTF-16 units as one keyboard event pair. The
// bridged CGEventKeyboardSetUnicodeString takes no usable UniChar buffer: a
// JavaScript array or Uint16Array is accepted and sets no text, so each chunk
// typed keycode 0, "a" (runs 40854789936, 40857315810), and an untyped Ref is
// refused. Bound with a void * buffer, it takes the bytes of UTF-16 NSData
// (run 40858670214). The bind is lazy and inside the caller's error handling:
// at the top level a rejected signature raised an NSException that killed the
// whole script (4fe8a17). The events are posted only if NSEvent reads back
// exactly the chunk, so a bridge that changes fails loudly, not with "a"s.
var boundSetText = false;
function readBack(ev) {
    try {
        var back = $.NSEvent.eventWithCGEvent(ev);
        return back ? JSON.stringify(ObjC.unwrap(back.characters)) : 'no NSEvent';
    } catch (e) {
        return 'unreadable (' + e + ')';
    }
}
function typeChunk(s) {
    if (s.length === 0) return;
    if (!boundSetText) {
        ObjC.bindFunction('CGEventKeyboardSetUnicodeString',
            ['void', ['void *', 'unsigned long', 'void *']]);
        boundSetText = true;
    }
    var data = $(s).dataUsingEncoding($.NSUTF16LittleEndianStringEncoding);
    var down = $.CGEventCreateKeyboardEvent(null, 0, true);
    var up = $.CGEventCreateKeyboardEvent(null, 0, false);
    $.CGEventKeyboardSetUnicodeString(down, s.length, data.bytes);
    $.CGEventKeyboardSetUnicodeString(up, s.length, data.bytes);
    var got = readBack(down);
    if (got !== JSON.stringify(s)) {
        throw new Error('-1 the key event did not carry the text: it read back as ' + got);
    }
    post(down);
    post(up);
}
// The text split into code points, so a surrogate pair is never cut.
function codePoints(text) {
    var out = [];
    for (var i = 0; i < text.length; i++) {
        var c = text.charCodeAt(i);
        if (c >= 0xD800 && c <= 0xDBFF && i + 1 < text.length) {
            out.push(text.substr(i, 2));
            i++;
        } else {
            out.push(text.charAt(i));
        }
    }
    return out;
}
function typeText(text) {
    var chunk = '';
    var units = 0;
    var cps = codePoints(text);
    for (var k = 0; k < cps.length; k++) {
        var cp = cps[k];
        // Newline and tab are sent as the Return and Tab keys, as the other
        // platforms do, not as characters.
        if (cp === '\n' || cp === '\t') {
            typeChunk(chunk);
            chunk = '';
            units = 0;
            var code = cp === '\n' ? 36 : 48;
            keyEvent(code, 0, true);
            keyEvent(code, 0, false);
            continue;
        }
        if (units + cp.length > 20) {
            typeChunk(chunk);
            chunk = '';
            units = 0;
        }
        chunk += cp;
        units += cp.length;
    }
    typeChunk(chunk);
}
// The frontmost application, and the title of its first System Events window
// when Accessibility is granted (null otherwise).
function activeWindow() {
    var app = $.NSWorkspace.sharedWorkspace.frontmostApplication;
    if (!app) return {app: null, pid: null, title: null};
    var name = ObjC.unwrap(app.localizedName);
    var pid = app.processIdentifier;
    var title = null;
    if ($.AXIsProcessTrusted()) {
        try {
            var procs = Application('System Events').processes.whose({unixId: pid})();
            if (procs.length > 0) {
                var wins = procs[0].windows();
                if (wins.length > 0) title = wins[0].name();
            }
        } catch (e) {
            if (/-1719|-25211|assistive access/.test(String(e))) throw e;
        }
    }
    return {app: name, pid: pid, title: title};
}
function run(argv) {
    var op = argv[0];
    if (TRUST_NEEDED[op] && !$.AXIsProcessTrusted()) {
        throw new Error('-25211 not allowed assistive access (AXIsProcessTrusted is false)');
    }
    switch (op) {
        case 'move':
            mouse($.kCGEventMouseMoved, Number(argv[1]), Number(argv[2]), $.kCGMouseButtonLeft);
            return 'ok';
        case 'click':
            clickAt(argv[1]);
            return 'ok';
        case 'drag':
            var x1 = Number(argv[1]), y1 = Number(argv[2]);
            var x2 = Number(argv[3]), y2 = Number(argv[4]);
            mouse($.kCGEventMouseMoved, x1, y1, $.kCGMouseButtonLeft);
            mouse($.kCGEventLeftMouseDown, x1, y1, $.kCGMouseButtonLeft);
            mouse($.kCGEventLeftMouseDragged, x2, y2, $.kCGMouseButtonLeft);
            mouse($.kCGEventLeftMouseUp, x2, y2, $.kCGMouseButtonLeft);
            return 'ok';
        case 'scroll':
            // Positive notches scroll up, as on the other platforms.
            // CGEventCreateScrollWheelEvent2 is the non-variadic form the bridge
            // exposes: source, units (1 = line), wheel count, then three deltas.
            post(need('CGEventCreateScrollWheelEvent2')(null, 1, 1, Number(argv[1]), 0, 0));
            return 'ok';
        case 'pos':
            var p = here();
            return JSON.stringify({x: Math.round(p.x), y: Math.round(p.y)});
        case 'key':
        case 'combo':
            var code = Number(argv[1]);
            var flags = Number(argv[2]);
            keyEvent(code, flags, true);
            keyEvent(code, flags, false);
            return 'ok';
        case 'type':
            typeText(argv[1]);
            return 'ok';
        case 'active':
            return JSON.stringify(activeWindow());
        case 'screen':
            var screen = $.NSScreen.mainScreen || $.NSScreen.screens.objectAtIndex(0);
            var frame = screen.frame;
            return JSON.stringify({
                width: Math.round(frame.size.width),
                height: Math.round(frame.size.height)
            });
        default:
            throw new Error('unknown input operation ' + op);
    }
}
"#;

/// The macOS virtual keycode of a key name that `parse_gui_key` accepted. The
/// codes are the ANSI key positions of Carbon's HIToolbox `kVK_*` constants
/// (Events.h), which is the US layout, so a letter or digit names its key in
/// that layout. `delete` is the forward-delete key, as on Windows and Linux;
/// `backspace` is the key labelled delete on Mac keyboards.
#[cfg(target_os = "macos")]
fn macos_key_code(name: &str, key: &str) -> Result<u16> {
    Ok(match key {
        "a" => 0,
        "s" => 1,
        "d" => 2,
        "f" => 3,
        "h" => 4,
        "g" => 5,
        "z" => 6,
        "x" => 7,
        "c" => 8,
        "v" => 9,
        "b" => 11,
        "q" => 12,
        "w" => 13,
        "e" => 14,
        "r" => 15,
        "y" => 16,
        "t" => 17,
        "1" => 18,
        "2" => 19,
        "3" => 20,
        "4" => 21,
        "6" => 22,
        "5" => 23,
        "9" => 25,
        "7" => 26,
        "8" => 28,
        "0" => 29,
        "o" => 31,
        "u" => 32,
        "i" => 34,
        "p" => 35,
        "l" => 37,
        "j" => 38,
        "k" => 40,
        "n" => 45,
        "m" => 46,
        "enter" => 36,
        "tab" => 48,
        "space" => 49,
        "backspace" => 51,
        "esc" => 53,
        "delete" => 117,
        "home" => 115,
        "end" => 119,
        "pageup" => 116,
        "pagedown" => 121,
        "left" => 123,
        "right" => 124,
        "down" => 125,
        "up" => 126,
        "f1" => 122,
        "f2" => 120,
        "f3" => 99,
        "f4" => 118,
        "f5" => 96,
        "f6" => 97,
        "f7" => 98,
        "f8" => 100,
        "f9" => 101,
        "f10" => 109,
        "f11" => 103,
        "f12" => 111,
        _ => {
            return Err(crate::safety::bad_arg(
                name,
                "a key such as enter, a, f5 or ctrl+shift+t",
                key,
            ))
        }
    })
}

/// The CGEventFlags mask of a key's modifiers: Shift, Control and Option.
#[cfg(target_os = "macos")]
fn macos_key_flags(mods: &[GuiMod]) -> u64 {
    mods.iter().fold(0, |flags, m| {
        flags
            | match m {
                GuiMod::Shift => 0x0002_0000,
                GuiMod::Ctrl => 0x0004_0000,
                GuiMod::Alt => 0x0008_0000,
            }
    })
}

/// Runs `MACOS_INPUT_ADMIN_JXA`: `op`, then the operands as argv. Without
/// Accessibility the operations that post events are E_OS_DENIED.
#[cfg(target_os = "macos")]
fn gui_macos_input(name: &str, op: &str, operands: &[String]) -> Result<std::process::Output> {
    let mut argv: Vec<&str> = vec![op];
    argv.extend(operands.iter().map(String::as_str));
    gui_macos_jxa(
        name,
        MACOS_INPUT_ADMIN_JXA,
        &argv,
        "Accessibility access is not granted to the process running ae, so mouse and keyboard events are not sent",
        "grant Accessibility in System Settings > Privacy & Security > Accessibility to the terminal or app that runs ae, then retry",
    )
}

#[allow(unused_variables)]
fn bi_gui_list_windows(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("gui_list_windows", &args, &input)?;
    #[cfg(target_os = "windows")]
    {
        let script = r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
public class WindowHelper {
    [DllImport("user32.dll")]
    public static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
    [DllImport("user32.dll")]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    [DllImport("user32.dll")]
    public static extern bool IsWindowVisible(IntPtr hWnd);
    [DllImport("user32.dll")]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
    public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
    public static List<object> windows = new List<object>();
    public static bool EnumWindow(IntPtr hWnd, IntPtr lParam) {
        if (!IsWindowVisible(hWnd)) return true;
        StringBuilder title = new StringBuilder(256);
        GetWindowText(hWnd, title, 256);
        if (title.Length == 0) return true;
        uint pid;
        GetWindowThreadProcessId(hWnd, out pid);
        windows.Add(new { hwnd = hWnd.ToInt64(), title = title.ToString(), pid = pid });
        return true;
    }
}
"@
[WindowHelper]::windows.Clear()
[WindowHelper]::EnumWindows([WindowHelper+EnumWindowsProc]{ param($h,$l) [WindowHelper]::EnumWindow($h,$l) }, [IntPtr]::Zero) | Out-Null
ConvertTo-Json -InputObject @([WindowHelper]::windows)
"#;
        let output = gui_powershell("gui_list_windows", script)?;
        gui_json_answer("gui_list_windows", "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("wmctrl");
        cmd.arg("-l");
        let output = bounded_cmd_output("gui_list_windows", "wmctrl", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                "gui_list_windows",
                "wmctrl",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout).into_owned();
        let mut windows = Vec::new();
        for line in text.lines() {
            // `wmctrl -l` pads its columns: window id, desktop, host, then the
            // title to the end of the line.
            let mut rest = line.trim_start();
            let mut fields = [""; 3];
            let mut complete = true;
            for field in fields.iter_mut() {
                match rest.split_once(char::is_whitespace) {
                    Some((head, tail)) => {
                        *field = head;
                        rest = tail.trim_start();
                    }
                    None => {
                        complete = false;
                        break;
                    }
                }
            }
            if !complete {
                continue;
            }
            let mut rec = std::collections::BTreeMap::new();
            rec.insert("hwnd".to_string(), Value::Str(fields[0].to_string()));
            rec.insert("title".to_string(), Value::Str(rest.trim_end().to_string()));
            windows.push(Value::Record(rec));
        }
        Ok(Value::Array(windows))
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_window_admin("gui_list_windows", "list", &[])?;
        gui_json_answer("gui_list_windows", "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            "gui_list_windows",
            "listing windows is implemented on Windows and Linux; NOTHING WAS READ",
            "run this on Windows or Linux",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_focus_window(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_focus_window";
    refuse_piped_input(NAME, &input)?;
    let (label, handle) = match gui_required(NAME, &args, 0, "a window title or handle")? {
        Value::Int(h) if *h > 0 => (h.to_string(), Some(*h)),
        Value::Int(h) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "a window handle above 0",
                &h.to_string(),
            ))
        }
        v @ Value::Str(_) => (
            gui_text(NAME, "window title", v, GUI_FIELD_MAX_BYTES, false)?,
            None,
        ),
        other => {
            return Err(crate::safety::bad_arg(
                NAME,
                "Int or String",
                other.type_name(),
            ))
        }
    };
    #[cfg(target_os = "windows")]
    {
        let (is_handle, arg) = match handle {
            Some(h) => (1, crate::safety::ps_quote(&h.to_string())),
            None => (0, crate::safety::ps_quote(&label)),
        };
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowFocus {{
    [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}}
"@
$hwnd = if ({} -eq 1) {{ [IntPtr]::new([int64]{}) }} else {{ [WindowFocus]::FindWindow([NullString]::Value, {}) }}
if ($hwnd -eq [IntPtr]::Zero) {{ exit 3 }}
if (-not [WindowFocus]::SetForegroundWindow($hwnd)) {{ exit 4 }}
"#,
            is_handle,
            arg,
            arg
        );
        let output = gui_powershell(NAME, &script)?;
        gui_window_action(NAME, "powershell", &label, 3, &output)
    }
    #[cfg(target_os = "linux")]
    {
        let args: Vec<String> = match handle {
            Some(h) => vec!["-i".into(), "-a".into(), format!("0x{h:x}")],
            None => {
                crate::safety::reject_option_like(NAME, std::slice::from_ref(&label))?;
                vec!["-a".into(), label.clone()]
            }
        };
        let mut cmd = crate::safety::child_command("wmctrl");
        cmd.args(&args);
        let output = bounded_cmd_output(NAME, "wmctrl", cmd, TOOL_DEADLINE_SECS)?;
        gui_window_action(NAME, "wmctrl", &label, 1, &output)
    }
    #[cfg(target_os = "macos")]
    {
        if handle.is_some() {
            return Err(crate::safety::unimplemented(
                NAME,
                "focusing a window by its handle is not supported on macOS: handles are CGWindow numbers from gui_list_windows; NOTHING WAS DONE",
                "focus the window by its exact title",
            ));
        }
        let output = gui_macos_window_admin(NAME, "focus", &[label.as_str()])?;
        gui_window_action(NAME, "osascript", &label, 3, &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows or Linux",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_minimize_window(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_minimize_window";
    refuse_piped_input(NAME, &input)?;
    let title = gui_text(
        NAME,
        "window title",
        gui_required(NAME, &args, 0, "a window title")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowMin {{
    [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}}
"@
$hwnd = [WindowMin]::FindWindow([NullString]::Value, {})
if ($hwnd -eq [IntPtr]::Zero) {{ exit 3 }}
[WindowMin]::ShowWindow($hwnd, 6) | Out-Null
"#,
            crate::safety::ps_quote(&title)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_window_action(NAME, "powershell", &title, 3, &output)
    }
    #[cfg(target_os = "linux")]
    {
        crate::safety::reject_option_like(NAME, std::slice::from_ref(&title))?;
        let pattern = format!("^{}$", gui_regex_escape(&title));
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args([
            "search",
            "--limit",
            "1",
            "--name",
            &pattern,
            "windowminimize",
        ]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        gui_window_action(NAME, "xdotool", &title, 1, &output)
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_window_admin(NAME, "minimize", &[title.as_str()])?;
        gui_window_action(NAME, "osascript", &title, 3, &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows or Linux",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_maximize_window(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_maximize_window";
    refuse_piped_input(NAME, &input)?;
    let title = gui_text(
        NAME,
        "window title",
        gui_required(NAME, &args, 0, "a window title")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowMax {{
    [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}}
"@
$hwnd = [WindowMax]::FindWindow([NullString]::Value, {})
if ($hwnd -eq [IntPtr]::Zero) {{ exit 3 }}
[WindowMax]::ShowWindow($hwnd, 3) | Out-Null
"#,
            crate::safety::ps_quote(&title)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_window_action(NAME, "powershell", &title, 3, &output)
    }
    #[cfg(target_os = "linux")]
    {
        crate::safety::reject_option_like(NAME, std::slice::from_ref(&title))?;
        let mut cmd = crate::safety::child_command("wmctrl");
        cmd.args(["-r", &title, "-b", "add,maximized_vert,maximized_horz"]);
        let output = bounded_cmd_output(NAME, "wmctrl", cmd, TOOL_DEADLINE_SECS)?;
        gui_window_action(NAME, "wmctrl", &title, 1, &output)
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_window_admin(NAME, "maximize", &[title.as_str()])?;
        gui_window_action(NAME, "osascript", &title, 3, &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows or Linux",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_close_window(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_close_window";
    refuse_piped_input(NAME, &input)?;
    let title = gui_text(
        NAME,
        "window title",
        gui_required(NAME, &args, 0, "a window title")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowClose {{
    [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
    [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}}
"@
$hwnd = [WindowClose]::FindWindow([NullString]::Value, {})
if ($hwnd -eq [IntPtr]::Zero) {{ exit 3 }}
[WindowClose]::SendMessage($hwnd, 0x0010, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null
"#,
            crate::safety::ps_quote(&title)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_window_action(NAME, "powershell", &title, 3, &output)
    }
    #[cfg(target_os = "linux")]
    {
        crate::safety::reject_option_like(NAME, std::slice::from_ref(&title))?;
        let mut cmd = crate::safety::child_command("wmctrl");
        cmd.args(["-c", &title]);
        let output = bounded_cmd_output(NAME, "wmctrl", cmd, TOOL_DEADLINE_SECS)?;
        gui_window_action(NAME, "wmctrl", &title, 1, &output)
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_window_admin(NAME, "close", &[title.as_str()])?;
        gui_window_action(NAME, "osascript", &title, 3, &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows or Linux",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_move_window(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_move_window";
    refuse_piped_input(NAME, &input)?;
    let title = gui_text(
        NAME,
        "window title",
        gui_required(NAME, &args, 0, "a window title")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    let x = gui_coord(NAME, "x", gui_required(NAME, &args, 1, "an Int x")?)?;
    let y = gui_coord(NAME, "y", gui_required(NAME, &args, 2, "an Int y")?)?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowMove {{
    [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}}
"@
$hwnd = [WindowMove]::FindWindow([NullString]::Value, {})
if ($hwnd -eq [IntPtr]::Zero) {{ exit 3 }}
if (-not [WindowMove]::SetWindowPos($hwnd, [IntPtr]::Zero, {}, {}, 0, 0, 0x0001)) {{ exit 4 }}
"#,
            crate::safety::ps_quote(&title),
            x,
            y
        );
        let output = gui_powershell(NAME, &script)?;
        gui_window_action(NAME, "powershell", &title, 3, &output)
    }
    #[cfg(target_os = "linux")]
    {
        crate::safety::reject_option_like(NAME, std::slice::from_ref(&title))?;
        let mut cmd = crate::safety::child_command("wmctrl");
        cmd.args(["-r", &title, "-e", &format!("0,{x},{y},-1,-1")]);
        let output = bounded_cmd_output(NAME, "wmctrl", cmd, TOOL_DEADLINE_SECS)?;
        gui_window_action(NAME, "wmctrl", &title, 1, &output)
    }
    #[cfg(target_os = "macos")]
    {
        let (xs, ys) = (x.to_string(), y.to_string());
        let output =
            gui_macos_window_admin(NAME, "move", &[title.as_str(), xs.as_str(), ys.as_str()])?;
        gui_window_action(NAME, "osascript", &title, 3, &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows or Linux",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_resize_window(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_resize_window";
    refuse_piped_input(NAME, &input)?;
    let title = gui_text(
        NAME,
        "window title",
        gui_required(NAME, &args, 0, "a window title")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    let w = gui_size(NAME, "width", gui_required(NAME, &args, 1, "an Int width")?)?;
    let h = gui_size(
        NAME,
        "height",
        gui_required(NAME, &args, 2, "an Int height")?,
    )?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowResize {{
    [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}}
"@
$hwnd = [WindowResize]::FindWindow([NullString]::Value, {})
if ($hwnd -eq [IntPtr]::Zero) {{ exit 3 }}
if (-not [WindowResize]::SetWindowPos($hwnd, [IntPtr]::Zero, 0, 0, {}, {}, 0x0002)) {{ exit 4 }}
"#,
            crate::safety::ps_quote(&title),
            w,
            h
        );
        let output = gui_powershell(NAME, &script)?;
        gui_window_action(NAME, "powershell", &title, 3, &output)
    }
    #[cfg(target_os = "linux")]
    {
        crate::safety::reject_option_like(NAME, std::slice::from_ref(&title))?;
        let mut cmd = crate::safety::child_command("wmctrl");
        cmd.args(["-r", &title, "-e", &format!("0,-1,-1,{w},{h}")]);
        let output = bounded_cmd_output(NAME, "wmctrl", cmd, TOOL_DEADLINE_SECS)?;
        gui_window_action(NAME, "wmctrl", &title, 1, &output)
    }
    #[cfg(target_os = "macos")]
    {
        let (ws, hs) = (w.to_string(), h.to_string());
        let output =
            gui_macos_window_admin(NAME, "resize", &[title.as_str(), ws.as_str(), hs.as_str()])?;
        gui_window_action(NAME, "osascript", &title, 3, &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows or Linux",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_screenshot(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_screenshot";
    refuse_piped_input(NAME, &input)?;
    let path = match args.first() {
        None => {
            let ts = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            format!("screenshot_{}.png", ts)
        }
        Some(v) => gui_text(NAME, "screenshot path", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    // Where it writes is checked like any other write, and the path goes to
    // scrot/screencapture positionally.
    crate::safety::reject_option_like(NAME, std::slice::from_ref(&path))?;
    let path = guard_local_write(NAME, &path)?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
$bitmap = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size)
$bitmap.Save({})
$graphics.Dispose()
$bitmap.Dispose()
"#,
            crate::safety::ps_quote(&path)
        );
        let output = gui_powershell(NAME, &script)?;
        if output.status.success() {
            Ok(Value::Str(path))
        } else {
            // A failed capture answered null.
            Err(crate::safety::tool_failed(
                NAME,
                "powershell",
                output.status.code(),
                &gui_stderr_tail(&output),
            ))
        }
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("scrot");
        cmd.arg(&path);
        let output = bounded_cmd_output(NAME, "scrot", cmd, TOOL_DEADLINE_SECS)?;
        if output.status.success() {
            Ok(Value::Str(path))
        } else {
            Err(crate::safety::tool_failed(
                NAME,
                "scrot",
                output.status.code(),
                &gui_stderr_tail(&output),
            ))
        }
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("screencapture");
        cmd.args(["-x", &path]);
        let output = bounded_cmd_output(NAME, "screencapture", cmd, TOOL_DEADLINE_SECS)?;
        if output.status.success() {
            Ok(Value::Str(path))
        } else {
            Err(crate::safety::tool_failed(
                NAME,
                "screencapture",
                output.status.code(),
                &gui_stderr_tail(&output),
            ))
        }
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "screen capture is not implemented on this OS; NOTHING WAS CAPTURED",
            "use the platform's screenshot tool",
        ))
    }
}

/// The PowerShell that captures one window on Windows. It is a constant: the
/// title and the output path arrive in the AE_SHOT_TITLE and AE_SHOT_PATH
/// environment variables, never in the script text. The exit codes are the
/// contract: 3 no window has the title (E_NOT_FOUND), 4 the window is minimized
/// or has no size, 5 PrintWindow drew nothing, 6 the PNG could not be saved.
/// The process is per-monitor-DPI-unaware by default, which would measure the
/// window in scaled pixels and draw it smaller, so it declares itself aware
/// first and the rectangle and the bitmap are both in physical pixels.
#[cfg(target_os = "windows")]
const WINDOW_SHOT_SCRIPT: &str = r#"$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowShot {
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
    [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
    [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
    [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
    [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, uint nFlags);
}
"@
[void][WindowShot]::SetProcessDPIAware()
$title = [Environment]::GetEnvironmentVariable('AE_SHOT_TITLE')
$out = [Environment]::GetEnvironmentVariable('AE_SHOT_PATH')
$hwnd = [WindowShot]::FindWindow([NullString]::Value, $title)
if ($hwnd -eq [IntPtr]::Zero) { exit 3 }
if ([WindowShot]::IsIconic($hwnd)) {
    [Console]::Error.WriteLine('the window is minimized, so it has no picture to capture')
    exit 4
}
$rect = New-Object 'WindowShot+RECT'
if (-not [WindowShot]::GetWindowRect($hwnd, [ref]$rect)) {
    [Console]::Error.WriteLine('GetWindowRect did not measure the window')
    exit 4
}
$width = $rect.Right - $rect.Left
$height = $rect.Bottom - $rect.Top
if ($width -lt 1 -or $height -lt 1) {
    [Console]::Error.WriteLine("the window measures ${width}x${height}")
    exit 4
}
try {
    $bitmap = New-Object System.Drawing.Bitmap($width, $height)
    try {
        $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
        try {
            $hdc = $graphics.GetHdc()
            try {
                $drawn = [WindowShot]::PrintWindow($hwnd, $hdc, 2)
            } finally {
                $graphics.ReleaseHdc($hdc)
            }
        } finally {
            $graphics.Dispose()
        }
        if (-not $drawn) {
            [Console]::Error.WriteLine('PrintWindow did not draw the window')
            exit 5
        }
        $bitmap.Save($out, [System.Drawing.Imaging.ImageFormat]::Png)
    } finally {
        $bitmap.Dispose()
    }
} catch {
    [Console]::Error.WriteLine($_.Exception.Message)
    exit 6
}
exit 0
"#;

/// The JavaScript for osascript that finds a window's CGWindowID by its exact
/// title. The title arrives in AE_SHOT_TITLE. Without Screen Recording
/// permission macOS withholds every other process's window titles, so a title
/// that is not found while no other process's window has a title answers
/// `denied`, not a false `missing`. (CGPreflightScreenCaptureAccess is not
/// reachable from JXA.) Otherwise it answers `missing`, or `id <n>`.
#[cfg(target_os = "macos")]
const MACOS_WINDOW_ID_JXA: &str = r#"ObjC.import('CoreGraphics');
ObjC.import('Foundation');
function run() {
    var title = ObjC.unwrap($.NSProcessInfo.processInfo.environment.objectForKey('AE_SHOT_TITLE'));
    var me = $.NSProcessInfo.processInfo.processIdentifier;
    // Option 0 is kCGWindowListOptionAll; relative 0 is kCGNullWindowID. The
    // answer is a CFArrayRef, which deepUnwrap reads only once it is cast to
    // an object.
    var windows = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo(0, 0))) || [];
    var named = 0;
    for (var i = 0; i < windows.length; i++) {
        var w = windows[i];
        if (w.kCGWindowName === title) { return 'id ' + w.kCGWindowNumber; }
        if (w.kCGWindowName !== undefined && w.kCGWindowOwnerPID !== me) { named++; }
    }
    return named === 0 ? 'denied' : 'missing';
}
"#;

/// The answer of a capture tool that wrote `path`: the file must exist and
/// begin with the PNG signature, or the capture is a coded failure. A tool that
/// exits 0 having written nothing is not a capture.
#[cfg(any(target_os = "windows", target_os = "macos"))]
fn gui_png_answer(name: &str, tool: &str, path: String) -> Result<Value> {
    let bytes = fs::read(&path).map_err(|e| {
        crate::safety::tool_failed(
            name,
            tool,
            Some(0),
            &format!("it wrote no readable file at {path}: {e}"),
        )
    })?;
    if image_mime_of(&bytes) != Some("image/png") {
        return Err(crate::safety::tool_failed(
            name,
            tool,
            Some(0),
            "its output was not a PNG image",
        ));
    }
    Ok(Value::Str(path))
}

/// `gui_screenshot_window(title, path?)`: capture the window whose title is
/// exactly `title` as a PNG at `path` (default `window_<seconds>.png`) and
/// answer the path. The path is checked like any other write. Linux X11:
/// xwininfo finds the window, ImageMagick's `import` captures it to stdout,
/// and this shell writes the file itself, so `import` never interprets the
/// path (it would run a name that begins with `|` as a command). Windows:
/// user32 FindWindow matches the exact title and PrintWindow draws it (see
/// `WINDOW_SHOT_SCRIPT`). macOS: the title is resolved to a CGWindowID and
/// `screencapture -l` captures that window; no Screen Recording permission is
/// E_OS_DENIED, never a blank PNG.
fn bi_gui_screenshot_window(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_screenshot_window";
    refuse_piped_input(NAME, &input)?;
    let title = gui_text(
        NAME,
        "window title",
        gui_required(NAME, &args, 0, "a window title")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    if args.len() > 2 {
        return Err(crate::safety::bad_arg(
            NAME,
            "at most two arguments: the window title and the PNG path",
            &format!("{} arguments", args.len()),
        ));
    }
    let path = match args.get(1) {
        None => {
            let ts = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            format!("window_{ts}.png")
        }
        Some(v) => gui_text(NAME, "screenshot path", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    #[cfg(target_os = "linux")]
    {
        if !display_env_set("DISPLAY") {
            if display_env_set("WAYLAND_DISPLAY") {
                return Err(crate::safety::unimplemented(
                    NAME,
                    "capturing one window is implemented for X11 only; under Wayland NOTHING WAS CAPTURED",
                    "gui_screenshot(path) captures the whole screen",
                ));
            }
            return Err(crate::safety::no_ui(NAME));
        }
        let path = guard_local_write(NAME, &path)?;
        let mut find = crate::safety::child_command("xwininfo");
        find.args(["-name", &title]);
        let found = bounded_cmd_output(NAME, "xwininfo", find, PROBE_DEADLINE_SECS)?;
        let stdout = String::from_utf8_lossy(&found.stdout);
        let stderr = String::from_utf8_lossy(&found.stderr);
        if !found.status.success() {
            if stderr.contains("No window with name") {
                return Err(crate::safety::not_found(NAME, "window", &title));
            }
            return Err(crate::safety::tool_failed(
                NAME,
                "xwininfo",
                found.status.code(),
                &gui_stderr_tail(&found),
            ));
        }
        // "xwininfo: Window id: 0x20001d "title"": the id is the hex word
        // after "Window id:".
        let id = stdout
            .lines()
            .find_map(|l| l.split_once("Window id:").map(|(_, rest)| rest.trim()))
            .and_then(|rest| rest.split_whitespace().next())
            .filter(|id| {
                id.strip_prefix("0x").is_some_and(|hex| {
                    !hex.is_empty() && hex.bytes().all(|b| b.is_ascii_hexdigit())
                })
            })
            .map(str::to_string)
            .ok_or_else(|| {
                crate::safety::tool_failed(
                    NAME,
                    "xwininfo",
                    Some(0),
                    "its output named no window id",
                )
            })?;
        let mut capture = crate::safety::child_command("import");
        capture.args(["-window", &id, "png:-"]);
        let shot = bounded_cmd_output(NAME, "import", capture, TOOL_DEADLINE_SECS)?;
        if !shot.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "import",
                shot.status.code(),
                &gui_stderr_tail(&shot),
            ));
        }
        if image_mime_of(&shot.stdout) != Some("image/png") {
            return Err(crate::safety::tool_failed(
                NAME,
                "import",
                Some(0),
                "its output was not a PNG image",
            ));
        }
        crate::safety::refuse_hard_linked_write(NAME, &path)?;
        crate::tx::snapshot(&path); // record pre-capture state if a transaction is active
        {
            use std::io::Write as _;
            let mut file = crate::safety::open_in_place(NAME, std::path::Path::new(&path), false)
                .map_err(|e| crate::safety::in_place_error(NAME, &path, e))?;
            file.write_all(&shot.stdout)
                .map_err(|e| crate::safety::fs_error(NAME, &path, &e))?;
        }
        Ok(Value::Str(path))
    }
    #[cfg(target_os = "windows")]
    {
        let path = guard_local_write(NAME, &path)?;
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-NoProfile",
            "-NonInteractive",
            "-Command",
            WINDOW_SHOT_SCRIPT,
        ]);
        cmd.env("AE_SHOT_TITLE", &title).env("AE_SHOT_PATH", &path);
        crate::tx::snapshot(&path); // record pre-capture state if a transaction is active
        let shot = bounded_cmd_output(NAME, "powershell", cmd, TOOL_DEADLINE_SECS)?;
        match shot.status.code() {
            Some(0) => gui_png_answer(NAME, "powershell", path),
            Some(3) => Err(crate::safety::not_found(NAME, "window", &title)),
            code => Err(crate::safety::tool_failed(
                NAME,
                "powershell",
                code,
                &gui_stderr_tail(&shot),
            )),
        }
    }
    #[cfg(target_os = "macos")]
    {
        let path = guard_local_write(NAME, &path)?;
        let mut find = crate::safety::child_command("osascript");
        find.args(["-l", "JavaScript", "-e", MACOS_WINDOW_ID_JXA]);
        find.env("AE_SHOT_TITLE", &title);
        let found = bounded_cmd_output(NAME, "osascript", find, PROBE_DEADLINE_SECS)?;
        if !found.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "osascript",
                found.status.code(),
                &gui_stderr_tail(&found),
            ));
        }
        let answer = String::from_utf8_lossy(&found.stdout).trim().to_string();
        let id: u64 = match answer.as_str() {
            "denied" => {
                return Err(crate::safety::os_denied(
                    NAME,
                    "Screen Recording permission is not granted to the process running ae, so window titles and pixels are withheld",
                    "grant Screen Recording to the terminal or app that runs ish in System Settings > Privacy & Security, then retry",
                ))
            }
            "missing" => return Err(crate::safety::not_found(NAME, "window", &title)),
            other => other
                .strip_prefix("id ")
                .and_then(|n| n.parse().ok())
                .ok_or_else(|| {
                    crate::safety::tool_failed(
                        NAME,
                        "osascript",
                        Some(0),
                        "its output named no window id",
                    )
                })?,
        };
        crate::tx::snapshot(&path); // record pre-capture state if a transaction is active
        let mut capture = crate::safety::child_command("screencapture");
        capture.args(["-x", "-o", "-l", &id.to_string(), &path]);
        let shot = bounded_cmd_output(NAME, "screencapture", capture, TOOL_DEADLINE_SECS)?;
        if !shot.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "screencapture",
                shot.status.code(),
                &gui_stderr_tail(&shot),
            ));
        }
        gui_png_answer(NAME, "screencapture", path)
    }
    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    {
        let _ = (title, path);
        Err(crate::safety::unimplemented(
            NAME,
            "capturing a window by title is implemented on Linux (X11), Windows and macOS only; NOTHING WAS CAPTURED",
            "gui_screenshot(path) captures the whole screen",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_mouse_move(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_mouse_move";
    refuse_piped_input(NAME, &input)?;
    let x = gui_coord(NAME, "x", gui_required(NAME, &args, 0, "an Int x")?)?;
    let y = gui_coord(NAME, "y", gui_required(NAME, &args, 1, "an Int y")?)?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class MouseMove {{
    [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y);
}}
"@
if (-not [MouseMove]::SetCursorPos({}, {})) {{ exit 4 }}
"#,
            x,
            y
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args(["mousemove", &x.to_string(), &y.to_string()]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "xdotool", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_input(NAME, "move", &[x.to_string(), y.to_string()])?;
        gui_action(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows, Linux or macOS",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_mouse_click(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_mouse_click";
    refuse_piped_input(NAME, &input)?;
    let button = gui_button(NAME, &args, 0)?;
    #[cfg(target_os = "windows")]
    {
        let (down, up) = gui_mouse_codes(button);
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class MouseClick {{
    [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, UIntPtr dwExtraInfo);
}}
"@
[MouseClick]::mouse_event({}, 0, 0, 0, [UIntPtr]::Zero)
[MouseClick]::mouse_event({}, 0, 0, 0, [UIntPtr]::Zero)
"#,
            down,
            up
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let btn = match button {
            "right" => "3",
            "middle" => "2",
            _ => "1",
        };
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args(["click", btn]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "xdotool", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_input(NAME, "click", &[button.to_string()])?;
        gui_action(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows, Linux or macOS",
        ))
    }
}

fn bi_gui_mouse_double_click(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_input("gui_mouse_double_click", &input)?;
    // Each click validates the button again, so a bad button is refused before
    // the first click is sent.
    gui_button("gui_mouse_double_click", &args, 0)?;
    bi_gui_mouse_click(args.clone(), None)?;
    std::thread::sleep(std::time::Duration::from_millis(50));
    bi_gui_mouse_click(args, None)
}

#[allow(unused_variables)]
fn bi_gui_mouse_drag(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_mouse_drag";
    refuse_piped_input(NAME, &input)?;
    let x1 = gui_coord(NAME, "x1", gui_required(NAME, &args, 0, "an Int x1")?)?;
    let y1 = gui_coord(NAME, "y1", gui_required(NAME, &args, 1, "an Int y1")?)?;
    let x2 = gui_coord(NAME, "x2", gui_required(NAME, &args, 2, "an Int x2")?)?;
    let y2 = gui_coord(NAME, "y2", gui_required(NAME, &args, 3, "an Int y2")?)?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class MouseDrag {{
    [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y);
    [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, UIntPtr dwExtraInfo);
}}
"@
if (-not [MouseDrag]::SetCursorPos({}, {})) {{ exit 4 }}
[MouseDrag]::mouse_event(0x0002, 0, 0, 0, [UIntPtr]::Zero)
if (-not [MouseDrag]::SetCursorPos({}, {})) {{ exit 4 }}
[MouseDrag]::mouse_event(0x0004, 0, 0, 0, [UIntPtr]::Zero)
"#,
            x1,
            y1,
            x2,
            y2
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args([
            "mousemove",
            &x1.to_string(),
            &y1.to_string(),
            "mousedown",
            "1",
            "mousemove",
            &x2.to_string(),
            &y2.to_string(),
            "mouseup",
            "1",
        ]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "xdotool", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_input(
            NAME,
            "drag",
            &[
                x1.to_string(),
                y1.to_string(),
                x2.to_string(),
                y2.to_string(),
            ],
        )?;
        gui_action(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows, Linux or macOS",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_mouse_scroll(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_mouse_scroll";
    refuse_piped_input(NAME, &input)?;
    // Notches: positive scrolls up, negative down. Bounded, so the wheel delta
    // below cannot overflow.
    let amount = match args.first() {
        None => 3,
        Some(Value::Int(n)) if (-100..=100).contains(n) => *n,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "amount: Int in -100..=100 (default 3)",
                &other.to_display_string(),
            ))
        }
    };
    #[cfg(target_os = "windows")]
    {
        // One notch is WHEEL_DELTA (120); a negative delta is its two's complement.
        let wheel = (amount * 120) as i32 as u32;
        let script = crate::ps_script!(
            r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class MouseScroll {{
    [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, UIntPtr dwExtraInfo);
}}
"@
[MouseScroll]::mouse_event(0x0800, 0, 0, {}, [UIntPtr]::Zero)
"#,
            wheel
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let dir = if amount > 0 { "4" } else { "5" };
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args(["click", "--repeat", &amount.unsigned_abs().to_string(), dir]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "xdotool", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_input(NAME, "scroll", &[amount.to_string()])?;
        gui_action(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows, Linux or macOS",
        ))
    }
}

fn bi_gui_mouse_position(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_mouse_position";
    no_args_or_input(NAME, &args, &input)?;
    #[cfg(target_os = "windows")]
    {
        let script = r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class MousePos {
    [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT lpPoint);
    public struct POINT { public int X; public int Y; }
}
"@
$point = New-Object MousePos+POINT
if (-not [MousePos]::GetCursorPos([ref]$point)) { exit 4 }
@{x=$point.X;y=$point.Y} | ConvertTo-Json
"#;
        let output = gui_powershell(NAME, script)?;
        gui_json_answer(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.arg("getmouselocation");
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "xdotool",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        // "x:123 y:456 screen:0 window:789"
        let text = String::from_utf8_lossy(&output.stdout).into_owned();
        let mut rec = std::collections::BTreeMap::new();
        for part in text.split_whitespace() {
            if let Some((k, v)) = part.split_once(':') {
                if k == "x" || k == "y" {
                    let n: i64 = v.parse().map_err(|_| {
                        crate::safety::tool_failed(
                            NAME,
                            "xdotool",
                            Some(0),
                            &format!("its answer had no usable {k}: {}", text.trim()),
                        )
                    })?;
                    rec.insert(k.to_string(), Value::Int(n));
                }
            }
        }
        if rec.len() != 2 {
            return Err(crate::safety::tool_failed(
                NAME,
                "xdotool",
                Some(0),
                &format!("its answer had no x and y: {}", text.trim()),
            ));
        }
        Ok(Value::Record(rec))
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_input(NAME, "pos", &[])?;
        gui_json_answer(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "reading the pointer is implemented on Windows, Linux and macOS; NOTHING WAS READ",
            "run this on Windows, Linux or macOS",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_key_press(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_key_press";
    refuse_piped_input(NAME, &input)?;
    let spec = gui_text(
        NAME,
        "key",
        gui_required(NAME, &args, 0, "a key name")?,
        GUI_KEY_MAX_BYTES,
        false,
    )?;
    let key = parse_gui_key(NAME, &spec)?;
    #[cfg(target_os = "windows")]
    {
        let keys = gui_sendkeys(&key);
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait({})
"#,
            crate::safety::ps_quote(&keys)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args(["key", &gui_xdotool_key(&key)]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "xdotool", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let code = macos_key_code(NAME, &key.key)?;
        let flags = macos_key_flags(&key.mods);
        let output = gui_macos_input(NAME, "key", &[code.to_string(), flags.to_string()])?;
        gui_action(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows, Linux or macOS",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_key_combo(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_key_combo";
    refuse_piped_input(NAME, &input)?;
    // The keys join into one spec: ("ctrl", "shift", "t") is ctrl+shift+t.
    let mut parts = Vec::with_capacity(args.len());
    for (i, arg) in args.iter().enumerate() {
        parts.push(gui_text(
            NAME,
            &format!("key {}", i + 1),
            arg,
            GUI_KEY_MAX_BYTES,
            false,
        )?);
    }
    if parts.is_empty() {
        return Err(crate::safety::bad_arg(NAME, "at least one key", "nothing"));
    }
    let key = parse_gui_key(NAME, &parts.join("+"))?;
    #[cfg(target_os = "windows")]
    {
        let keys = gui_sendkeys(&key);
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait({})
"#,
            crate::safety::ps_quote(&keys)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args(["key", &gui_xdotool_key(&key)]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "xdotool", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let code = macos_key_code(NAME, &key.key)?;
        let flags = macos_key_flags(&key.mods);
        let output = gui_macos_input(NAME, "combo", &[code.to_string(), flags.to_string()])?;
        gui_action(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows, Linux or macOS",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_type_text(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_type_text";
    refuse_piped_input(NAME, &input)?;
    let text = gui_text(
        NAME,
        "text",
        gui_required(NAME, &args, 0, "the text to type")?,
        GUI_TYPE_MAX_BYTES,
        false,
    )?;
    #[cfg(target_os = "windows")]
    {
        let keys = gui_sendkeys_text(&text);
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait({})
"#,
            crate::safety::ps_quote(&keys)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args(["type", "--", &text]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "xdotool", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_input(NAME, "type", &[text])?;
        gui_action(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "desktop automation is not implemented on this platform; NOTHING WAS DONE",
            "run this on Windows, Linux or macOS",
        ))
    }
}

fn bi_gui_get_active_window(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_get_active_window";
    no_args_or_input(NAME, &args, &input)?;
    #[cfg(target_os = "windows")]
    {
        let script = r#"
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Text;
public class ActiveWindow {
    [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
}
"@
$hwnd = [ActiveWindow]::GetForegroundWindow()
$title = New-Object System.Text.StringBuilder 256
[ActiveWindow]::GetWindowText($hwnd, $title, 256) | Out-Null
@{hwnd=$hwnd.ToInt64();title=$title.ToString()} | ConvertTo-Json
"#;
        let output = gui_powershell(NAME, script)?;
        gui_json_answer(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("xdotool");
        cmd.args(["getactivewindow", "getwindowname"]);
        let output = bounded_cmd_output(NAME, "xdotool", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "xdotool",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        let title = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let mut rec = std::collections::BTreeMap::new();
        rec.insert("title".to_string(), Value::Str(title));
        Ok(Value::Record(rec))
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_input(NAME, "active", &[])?;
        gui_json_answer(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "reading the active window is implemented on Windows, Linux and macOS; NOTHING WAS READ",
            "run this on Windows, Linux or macOS",
        ))
    }
}

fn bi_gui_screen_size(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_screen_size";
    no_args_or_input(NAME, &args, &input)?;
    #[cfg(target_os = "windows")]
    {
        let script = r#"
Add-Type -AssemblyName System.Windows.Forms
$screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
@{width=$screen.Width;height=$screen.Height} | ConvertTo-Json
"#;
        let output = gui_powershell(NAME, script)?;
        gui_json_answer(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let cmd = crate::safety::child_command("xdpyinfo");
        let output = bounded_cmd_output(NAME, "xdpyinfo", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "xdpyinfo",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout).into_owned();
        // "  dimensions:    1920x1080 pixels (508x285 millimeters)"
        for line in text.lines() {
            if line.contains("dimensions:") {
                if let Some((w, h)) = line
                    .split_whitespace()
                    .nth(1)
                    .and_then(|dims| dims.split_once('x'))
                {
                    if let (Ok(w), Ok(h)) = (w.parse::<i64>(), h.parse::<i64>()) {
                        let mut rec = std::collections::BTreeMap::new();
                        rec.insert("width".to_string(), Value::Int(w));
                        rec.insert("height".to_string(), Value::Int(h));
                        return Ok(Value::Record(rec));
                    }
                }
            }
        }
        Err(crate::safety::tool_failed(
            NAME,
            "xdpyinfo",
            Some(0),
            "its answer had no dimensions line",
        ))
    }
    #[cfg(target_os = "macos")]
    {
        let output = gui_macos_input(NAME, "screen", &[])?;
        gui_json_answer(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "reading the screen size is implemented on Windows, Linux and macOS; NOTHING WAS READ",
            "run this on Windows, Linux or macOS",
        ))
    }
}

/// Options accepted by `gui_find_image`, after validation.
#[cfg(feature = "native")]
struct FindImageOptions {
    tolerance: u8,
    all: bool,
    limit: usize,
}

#[cfg(feature = "native")]
fn find_image_options(value: Option<&Value>) -> Result<FindImageOptions> {
    let mut opts = FindImageOptions {
        tolerance: 0,
        all: false,
        limit: 100,
    };
    let Some(value) = value else {
        return Ok(opts);
    };
    let Value::Record(map) = value else {
        return Err(crate::safety::bad_arg(
            "gui_find_image",
            "options: Record",
            value.type_name(),
        ));
    };
    for (key, value) in map {
        match (key.as_str(), value) {
            ("tolerance", Value::Int(n)) if (0..=255i64).contains(n) => opts.tolerance = *n as u8,
            ("all", Value::Bool(b)) => opts.all = *b,
            ("limit", Value::Int(n)) if (1..=1000i64).contains(n) => opts.limit = *n as usize,
            ("tolerance", _) | ("all", _) | ("limit", _) => {
                return Err(crate::safety::arg_err(format!(
                    "gui_find_image: option {key} has the wrong value; \
                     tolerance is an Int in 0..=255, all a Bool, limit an Int in 1..=1000"
                )))
            }
            _ => {
                return Err(crate::safety::arg_err(format!(
                    "gui_find_image: unknown option {key}"
                )))
            }
        }
    }
    Ok(opts)
}

/// Resolve one image path through the same read guards `cat` uses, then read
/// only its header. Returns the validated path and its (width, height).
#[cfg(feature = "native")]
fn find_image_header(path: &str) -> Result<(std::path::PathBuf, u32, u32)> {
    if !std::path::Path::new(path).exists() {
        return Err(crate::safety::not_found("gui_find_image", "file", path));
    }
    let validated = validate_read_path(path)?;
    let meta = fs::metadata(&validated)
        .map_err(|e| crate::safety::fs_error("gui_find_image", &validated, &e))?;
    if !meta.is_file() {
        return Err(crate::safety::arg_err(format!(
            "gui_find_image: `{path}` is not a regular file"
        )));
    }
    let reader = image::io::Reader::open(&validated)
        .and_then(|r| r.with_guessed_format())
        .map_err(|e| crate::safety::fs_error("gui_find_image", &validated, &e))?;
    let (w, h) = reader.into_dimensions().map_err(|e| {
        crate::safety::arg_err(format!(
            "gui_find_image: `{path}` is not a PNG, JPEG, GIF or WebP image that can be read ({e})"
        ))
    })?;
    Ok((validated, w, h))
}

/// Decode one already-validated image to RGBA8.
#[cfg(feature = "native")]
fn find_image_decode(path: &std::path::Path, shown: &str) -> Result<image::RgbaImage> {
    let reader = image::io::Reader::open(path)
        .and_then(|r| r.with_guessed_format())
        .map_err(|e| crate::safety::fs_error("gui_find_image", path, &e))?;
    let img = reader.decode().map_err(|e| {
        crate::safety::arg_err(format!("gui_find_image: `{shown}` failed to decode ({e})"))
    })?;
    Ok(img.to_rgba8())
}

/// `gui_find_image(haystack, needle, options?)`: template matching over image
/// files. Pure computation over pixels; it reads the two files and writes
/// nothing. See `signature.rs` for the contract.
#[cfg(feature = "native")]
fn bi_gui_find_image(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use image_match::{self as im, Frame, MatchError};

    const BUILTIN: &str = "gui_find_image";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "a direct call; pipeline input is not accepted",
            "pipeline input",
        ));
    }
    if args.len() < 2 || args.len() > 3 {
        return Err(crate::safety::arg_err(format!(
            "gui_find_image takes a haystack, a needle and optional options; got {} arguments",
            args.len()
        )));
    }
    let mut paths = Vec::with_capacity(2);
    for arg in &args[..2] {
        match arg {
            Value::Str(s) => paths.push(s.clone()),
            other => {
                return Err(crate::safety::bad_arg(
                    BUILTIN,
                    "a String path to an image file",
                    other.type_name(),
                ))
            }
        }
    }
    crate::safety::reject_option_like(BUILTIN, &paths)?;
    let opts = find_image_options(args.get(2))?;

    // Headers first: every refusal below happens before any pixel is decoded.
    let (hay_path, hw, hh) = find_image_header(&paths[0])?;
    let (needle_path, nw, nh) = find_image_header(&paths[1])?;
    for (shown, w, h) in [(&paths[0], hw, hh), (&paths[1], nw, nh)] {
        let pixels = u64::from(w) * u64::from(h);
        if pixels > im::MAX_PIXELS {
            return Err(crate::safety::budget_exceeded(
                BUILTIN,
                format!(
                    "`{shown}` is {w}x{h} = {pixels} pixels, above the {} pixel limit; not decoded",
                    im::MAX_PIXELS
                ),
                "use a smaller image",
            ));
        }
    }
    match im::plan(hw, hh, nw, nh) {
        Ok(_) => {}
        Err(MatchError::NeedleTooLarge { haystack, needle }) => {
            return Err(crate::safety::arg_err(format!(
                "gui_find_image: needle {}x{} does not fit in haystack {}x{}",
                needle.0, needle.1, haystack.0, haystack.1
            )))
        }
        Err(MatchError::WorkExceeded { work }) => {
            let shown = work.map_or("more than 2^64".to_string(), |w| w.to_string());
            return Err(crate::safety::budget_exceeded(
                BUILTIN,
                format!(
                    "worst case {shown} pixel comparisons exceeds the {} limit",
                    im::MAX_WORK
                ),
                "use a smaller needle or haystack, or a smaller search area",
            ));
        }
        Err(_) => {
            return Err(crate::safety::arg_err(
                "gui_find_image: an image has a zero dimension",
            ))
        }
    }

    let hay = find_image_decode(&hay_path, &paths[0])?;
    let needle = find_image_decode(&needle_path, &paths[1])?;
    let hits = im::find_matches(
        Frame {
            width: hay.width(),
            height: hay.height(),
            rgba: hay.as_raw(),
        },
        Frame {
            width: needle.width(),
            height: needle.height(),
            rgba: needle.as_raw(),
        },
        opts.tolerance,
        opts.all,
        opts.limit,
    )
    .map_err(|e| crate::safety::arg_err(format!("gui_find_image: match refused ({e:?})")))?;

    let record = |h: &im::Hit| {
        let mut rec = BTreeMap::new();
        rec.insert("x".to_string(), Value::Int(i64::from(h.x)));
        rec.insert("y".to_string(), Value::Int(i64::from(h.y)));
        rec.insert("width".to_string(), Value::Int(i64::from(nw)));
        rec.insert("height".to_string(), Value::Int(i64::from(nh)));
        Value::Record(rec)
    };
    if opts.all {
        Ok(Value::Array(hits.iter().map(record).collect()))
    } else {
        Ok(hits.first().map_or(Value::Null, record))
    }
}

#[cfg(not(feature = "native"))]
fn bi_gui_find_image(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Without the `image` crate there is no decoder, so no answer is given.
    Err(crate::safety::unimplemented(
        "gui_find_image",
        "image decoding needs the `native` feature; NOTHING WAS DONE",
        "build with the default `native` feature",
    ))
}

fn bi_gui_ocr(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_ocr";
    refuse_piped_input(NAME, &input)?;
    let image_path = gui_text(
        NAME,
        "image path",
        gui_required(NAME, &args, 0, "an image path")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    crate::safety::reject_option_like(NAME, std::slice::from_ref(&image_path))?;
    // A read is guarded like any other read: inside the workspace in agent mode.
    let image_path = guard_local_read(NAME, &image_path)?;
    let mut cmd = crate::safety::child_command("tesseract");
    cmd.args([&image_path, "stdout"]);
    let output = bounded_cmd_output(NAME, "tesseract", cmd, TOOL_DEADLINE_SECS)?;
    if output.status.success() {
        Ok(Value::Str(
            String::from_utf8_lossy(&output.stdout).into_owned(),
        ))
    } else {
        Err(crate::safety::tool_failed(
            NAME,
            "tesseract",
            output.status.code(),
            &gui_stderr_tail(&output),
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_notify(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_notify";
    refuse_piped_input(NAME, &input)?;
    let title = match args.first() {
        None => "Notification".to_string(),
        Some(v) => gui_text(NAME, "title", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    let message = match args.get(1) {
        None => String::new(),
        Some(v) => gui_text(NAME, "message", v, GUI_FIELD_MAX_BYTES, true)?,
    };
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
$template = [Windows.UI.Notifications.ToastTemplateType]::ToastText02
$xml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent($template)
$text = $xml.GetElementsByTagName("text")
$text[0].AppendChild($xml.CreateTextNode({})) | Out-Null
$text[1].AppendChild($xml.CreateTextNode({})) | Out-Null
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("IronShell").Show($toast)
"#,
            crate::safety::ps_quote(&title),
            crate::safety::ps_quote(&message)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        // `--` ends notify-send's options, so a title or message that begins
        // with a dash is text.
        let mut cmd = crate::safety::child_command("notify-send");
        cmd.args(["--", &title, &message]);
        let output = bounded_cmd_output(NAME, "notify-send", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "notify-send", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("osascript");
        cmd.args([
            "-e",
            &crate::applescript!(
                "display notification {} with title {}",
                crate::safety::applescript_quote(&message),
                crate::safety::applescript_quote(&title)
            ),
        ]);
        let output = bounded_cmd_output(NAME, "osascript", cmd, TOOL_DEADLINE_SECS)?;
        gui_action(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "notifications are not implemented on this platform; NOTHING WAS SHOWN",
            "run this on Windows, Linux or macOS",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_dialog_message(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_dialog_message";
    refuse_piped_input(NAME, &input)?;
    let message = gui_text(
        NAME,
        "message",
        gui_required(NAME, &args, 0, "the message to show")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    let title = match args.get(1) {
        None => "Message".to_string(),
        Some(v) => gui_text(NAME, "title", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    crate::safety::refuse_if_headless(NAME)?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show({}, {})
"#,
            crate::safety::ps_quote(&message),
            crate::safety::ps_quote(&title)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_action(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("zenity");
        cmd.args(["--info", "--title", &title, "--text", &message]);
        let output = bounded_cmd_output(NAME, "zenity", cmd, GUI_DIALOG_DEADLINE_SECS)?;
        gui_dialog_ack(NAME, "zenity", &output)
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("osascript");
        cmd.args([
            "-e",
            &crate::applescript!(
                "display dialog {} with title {}",
                crate::safety::applescript_quote(&message),
                crate::safety::applescript_quote(&title)
            ),
        ]);
        let output = bounded_cmd_output(NAME, "osascript", cmd, GUI_DIALOG_DEADLINE_SECS)?;
        gui_dialog_ack(NAME, "osascript", &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "dialogs are not implemented on this platform; NOTHING WAS SHOWN",
            "run this on Windows, Linux or macOS",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_dialog_input(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_dialog_input";
    refuse_piped_input(NAME, &input)?;
    let prompt = match args.first() {
        None => "Enter value:".to_string(),
        Some(v) => gui_text(NAME, "prompt", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    let title = match args.get(1) {
        None => "Input".to_string(),
        Some(v) => gui_text(NAME, "title", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    crate::safety::refuse_if_headless(NAME)?;
    #[cfg(target_os = "windows")]
    {
        // The VisualBasic InputBox returns "" on cancel, so an empty answer is Null.
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.Interaction]::InputBox({}, {})
"#,
            crate::safety::ps_quote(&prompt),
            crate::safety::ps_quote(&title)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_dialog_answer(NAME, "powershell", None, &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("zenity");
        cmd.args(["--entry", "--title", &title, "--text", &prompt]);
        let output = bounded_cmd_output(NAME, "zenity", cmd, GUI_DIALOG_DEADLINE_SECS)?;
        gui_dialog_answer(NAME, "zenity", Some(1), &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "input dialogs are implemented on Windows and Linux; NOTHING WAS ASKED",
            "use input_read_line on the terminal",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_dialog_file_open(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_dialog_file_open";
    refuse_piped_input(NAME, &input)?;
    let title = match args.first() {
        None => "Open File".to_string(),
        Some(v) => gui_text(NAME, "title", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    crate::safety::refuse_if_headless(NAME)?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName System.Windows.Forms
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.Title = {}
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {{ $dialog.FileName }}
"#,
            crate::safety::ps_quote(&title)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_dialog_answer(NAME, "powershell", None, &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("zenity");
        cmd.args(["--file-selection", "--title", &title]);
        let output = bounded_cmd_output(NAME, "zenity", cmd, GUI_DIALOG_DEADLINE_SECS)?;
        gui_dialog_answer(NAME, "zenity", Some(1), &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "file dialogs are implemented on Windows and Linux; NOTHING WAS SHOWN",
            "pass the path as an argument instead",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_dialog_file_save(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_dialog_file_save";
    refuse_piped_input(NAME, &input)?;
    let title = match args.first() {
        None => "Save File".to_string(),
        Some(v) => gui_text(NAME, "title", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    crate::safety::refuse_if_headless(NAME)?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName System.Windows.Forms
$dialog = New-Object System.Windows.Forms.SaveFileDialog
$dialog.Title = {}
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {{ $dialog.FileName }}
"#,
            crate::safety::ps_quote(&title)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_dialog_answer(NAME, "powershell", None, &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("zenity");
        cmd.args(["--file-selection", "--save", "--title", &title]);
        let output = bounded_cmd_output(NAME, "zenity", cmd, GUI_DIALOG_DEADLINE_SECS)?;
        gui_dialog_answer(NAME, "zenity", Some(1), &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "file dialogs are implemented on Windows and Linux; NOTHING WAS SHOWN",
            "pass the path as an argument instead",
        ))
    }
}

#[allow(unused_variables)]
fn bi_gui_dialog_folder(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_dialog_folder";
    refuse_piped_input(NAME, &input)?;
    let title = match args.first() {
        None => "Select Folder".to_string(),
        Some(v) => gui_text(NAME, "title", v, GUI_FIELD_MAX_BYTES, false)?,
    };
    crate::safety::refuse_if_headless(NAME)?;
    #[cfg(target_os = "windows")]
    {
        let script = crate::ps_script!(
            r#"
Add-Type -AssemblyName System.Windows.Forms
$dialog = New-Object System.Windows.Forms.FolderBrowserDialog
$dialog.Description = {}
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {{ $dialog.SelectedPath }}
"#,
            crate::safety::ps_quote(&title)
        );
        let output = gui_powershell(NAME, &script)?;
        gui_dialog_answer(NAME, "powershell", None, &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("zenity");
        cmd.args(["--file-selection", "--directory", "--title", &title]);
        let output = bounded_cmd_output(NAME, "zenity", cmd, GUI_DIALOG_DEADLINE_SECS)?;
        gui_dialog_answer(NAME, "zenity", Some(1), &output)
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "folder dialogs are implemented on Windows and Linux; NOTHING WAS SHOWN",
            "pass the path as an argument instead",
        ))
    }
}

fn bi_gui_wait(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_wait";
    refuse_piped_input(NAME, &input)?;
    // A negative Int became u64::MAX milliseconds: gui_wait(-1) slept forever.
    let ms = match args.first() {
        None => 1000,
        Some(Value::Int(n)) if (0..=3_600_000).contains(n) => *n as u64,
        Some(Value::Float(f)) if (0.0..=3_600_000.0).contains(f) => *f as u64,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "milliseconds from 0 to 3600000",
                &other.to_display_string(),
            ))
        }
    };
    std::thread::sleep(std::time::Duration::from_millis(ms));
    Ok(Value::Bool(true))
}

fn bi_gui_color_picker(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "gui_color_picker";
    no_args_or_input(NAME, &args, &input)?;
    crate::safety::refuse_if_headless(NAME)?;
    #[cfg(target_os = "windows")]
    {
        // Cancelled, the dialog prints nothing: Null.
        let script = r#"
Add-Type -AssemblyName System.Windows.Forms
$dialog = New-Object System.Windows.Forms.ColorDialog
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
    @{r=$dialog.Color.R;g=$dialog.Color.G;b=$dialog.Color.B;hex=('#' + $dialog.Color.R.ToString('X2') + $dialog.Color.G.ToString('X2') + $dialog.Color.B.ToString('X2'))} | ConvertTo-Json
}
"#;
        let output = gui_powershell(NAME, script)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "powershell",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        if String::from_utf8_lossy(&output.stdout).trim().is_empty() {
            return Ok(Value::Null);
        }
        gui_json_answer(NAME, "powershell", &output)
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("zenity");
        cmd.arg("--color-selection");
        let output = bounded_cmd_output(NAME, "zenity", cmd, GUI_DIALOG_DEADLINE_SECS)?;
        if output.status.code() == Some(1) {
            return Ok(Value::Null);
        }
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "zenity",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        // zenity answers "rgb(255,0,0)".
        let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let parsed: Option<(i64, i64, i64)> = text
            .strip_prefix("rgb(")
            .and_then(|t| t.strip_suffix(')'))
            .and_then(|t| {
                let mut it = t.split(',').map(|p| p.trim().parse::<i64>());
                match (it.next(), it.next(), it.next(), it.next()) {
                    (Some(Ok(r)), Some(Ok(g)), Some(Ok(b)), None) => Some((r, g, b)),
                    _ => None,
                }
            });
        let Some((r, g, b)) = parsed else {
            return Err(crate::safety::tool_failed(
                NAME,
                "zenity",
                Some(0),
                &format!("its answer was not rgb(r,g,b): {text}"),
            ));
        };
        let mut rec = std::collections::BTreeMap::new();
        rec.insert("r".to_string(), Value::Int(r));
        rec.insert("g".to_string(), Value::Int(g));
        rec.insert("b".to_string(), Value::Int(b));
        rec.insert(
            "hex".to_string(),
            Value::Str(format!("#{r:02X}{g:02X}{b:02X}")),
        );
        Ok(Value::Record(rec))
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "the colour picker is implemented on Windows and Linux; NOTHING WAS SHOWN",
            "run this on Windows or Linux",
        ))
    }
}

// ============================================================================
// 430-459: Web Automation
// ============================================================================

/// Largest response body a `web_*` builtin buffers or returns. A longer body is
/// `E_BUDGET_EXCEEDED`: the caller gets an error, never a prefix.
const WEB_BODY_MAX: usize = 8 * 1024 * 1024;
/// Largest file `web_download` will write.
const WEB_DOWNLOAD_MAX: u64 = 512 * 1024 * 1024;
/// Most elements `web_scrape` returns for one selector.
const WEB_SCRAPE_MAX_MATCHES: usize = 1000;
/// Wall-clock limit for one request, handed to curl.
const WEB_MAX_TIME_SECS: &str = "30";
/// Redirects followed before a request is refused. Other request paths that
/// follow redirects by hand share this ceiling.
pub(crate) const WEB_MAX_REDIRS: usize = 10;
/// Where curl's `-w` report starts in a hop's stdout: the status and the
/// `Location` it did not follow. Plain ASCII, so it survives any argv encoding.
const WEB_HOP_MARK: &str = "\nISH-HOP-7c41 ";
/// Trailing bytes of curl's stderr kept for an error message.
const WEB_STDERR_TAIL: usize = 4 * 1024;
const WEB_URL_EXPECTED: &str = "an absolute http or https URL such as https://example.com";

/// Refuse piped input for a `web_*` builtin, which takes none.
fn web_no_input(builtin: &str, input: &Option<Value>) -> Result<()> {
    match input {
        None => Ok(()),
        Some(v) => Err(crate::safety::bad_arg(
            builtin,
            "no piped input; pass the arguments directly",
            v.type_name(),
        )),
    }
}

/// A string argument at `idx`, or `E_BAD_ARG` naming what was expected.
fn web_text_arg<'a>(
    builtin: &str,
    args: &'a [Value],
    idx: usize,
    expected: &str,
) -> Result<&'a str> {
    match args.get(idx) {
        Some(Value::Str(s)) | Some(Value::Uri(s)) => Ok(s.as_str()),
        other => Err(crate::safety::bad_arg(
            builtin,
            expected,
            other.map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

/// Parse an absolute `http` or `https` URL and return its normalised text.
///
/// Refused before any effect: control characters (a newline ends a shell
/// command and an HTTP header), every other scheme (`file:` would make curl
/// read the local disk outside the file guards, and `ftp:`, `gopher:` and
/// `dict:` reach protocols nothing here audits), and text `url` cannot parse.
/// The normalised text is what gets passed to curl, so both agree on the target.
fn web_http_url(builtin: &str, text: &str) -> Result<String> {
    // A leading `-` is an option to curl, which can read a config file.
    crate::safety::reject_option_like(builtin, &[text.to_string()])?;
    if text.chars().any(|c| c.is_control()) {
        return Err(crate::safety::bad_arg(
            builtin,
            WEB_URL_EXPECTED,
            "text with a control character",
        ));
    }
    let parsed = url::Url::parse(text).map_err(|e| {
        crate::safety::bad_arg(builtin, WEB_URL_EXPECTED, &format!("{text:?} ({e})"))
    })?;
    if !matches!(parsed.scheme(), "http" | "https") {
        return Err(crate::safety::bad_arg(
            builtin,
            WEB_URL_EXPECTED,
            &format!("a {} URL", parsed.scheme()),
        ));
    }
    Ok(parsed.to_string())
}

/// A coded `E_TOOL_FAILED` for a web request that could not be completed.
fn web_failure(builtin: &str, message: String, hint: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::ToolFailed,
        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(),
    })
}

/// What one curl run produced.
struct WebRun {
    status: std::process::ExitStatus,
    /// stdout, up to `WEB_BODY_MAX` bytes.
    body: Vec<u8>,
    /// stdout was longer than `WEB_BODY_MAX`.
    over: bool,
    /// The last `WEB_STDERR_TAIL` bytes of stderr.
    stderr: Vec<u8>,
}

/// How long past curl's own `--max-time` the shell waits before it kills
/// curl's process tree itself: curl's timer does not cover a stalled DNS
/// resolver thread or a curl that never starts its transfer.
const WEB_KILL_GRACE_SECS: u64 = 15;

/// Run curl with `args` as an argv, never through a shell. The caller's last
/// argument is the URL.
///
/// A caller that passes `-L` gets redirects followed, but not by curl: curl
/// would follow them past the egress allowlist and the SSRF check, which saw
/// only the first URL. Each hop runs without `-L`, curl reports the status and
/// the `Location` it did not follow, and [`crate::safety::guard_redirect`]
/// judges the next URL before it is requested. With `-I`, every hop's headers
/// are returned, as curl's own `-L -I` printed them.
fn web_curl(builtin: &str, args: &[&str]) -> Result<WebRun> {
    if !args.iter().any(|a| matches!(*a, "-L" | "--location")) {
        return web_curl_once(builtin, args);
    }
    let heads = args.iter().any(|a| matches!(*a, "-I" | "--head"));
    let mut argv: Vec<String> = args
        .iter()
        .filter(|a| !matches!(**a, "-L" | "--location"))
        .map(|a| a.to_string())
        .collect();
    // curl keeps only the last `-w`, so a caller's own format (web_check_url
    // prints the status) goes in front of the hop report rather than lost.
    let mut caller_format = String::new();
    if let Some(i) = argv.iter().position(|a| a == "-w") {
        if i + 1 < argv.len() - 1 {
            caller_format = argv.remove(i + 1);
            argv.remove(i);
        }
    }
    let report = format!("{caller_format}{WEB_HOP_MARK}%{{response_code}} %{{redirect_url}}");
    let at = argv.len() - 1;
    argv.splice(at..at, ["-w".to_string(), report]);
    let mut earlier = Vec::new();
    for _ in 0..=WEB_MAX_REDIRS {
        let url = argv.last().cloned().unwrap_or_default();
        let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
        let mut run = web_curl_once(builtin, &refs)?;
        let next = web_take_hop(&mut run.body);
        if heads {
            earlier.append(&mut run.body);
        }
        let next = match next {
            Some((code, next)) if (300..400).contains(&code) && !next.is_empty() => next,
            _ => {
                if heads {
                    run.body = earlier;
                }
                return Ok(run);
            }
        };
        if !run.status.success() || run.over {
            return Ok(run);
        }
        crate::safety::guard_redirect(builtin, &url, &next)?;
        let next = web_http_url(builtin, &next)?;
        *argv.last_mut().expect("the URL is the last argument") = next;
    }
    Err(crate::safety::budget_exceeded(
        builtin,
        format!("more than {WEB_MAX_REDIRS} redirects"),
        "request the final URL directly",
    ))
}

/// Remove curl's `-w` report from the end of a hop's stdout and return the
/// status and the redirect target it names. None when the report is missing,
/// as it is when the body was cut at the size cap.
fn web_take_hop(body: &mut Vec<u8>) -> Option<(u16, String)> {
    let mark = WEB_HOP_MARK.as_bytes();
    let at = body.windows(mark.len()).rposition(|w| w == mark)?;
    let report = String::from_utf8_lossy(&body[at + mark.len()..]).into_owned();
    body.truncate(at);
    let (code, next) = report.split_once(' ').unwrap_or((report.as_str(), ""));
    Some((code.trim().parse().ok()?, next.trim().to_string()))
}

/// One curl run, with no redirect followed.
///
/// Every run is limited to http and https and to a wall-clock limit. curl's
/// `--max-time` is the first limit; [`run_tree`] enforces a second one,
/// killing curl's tree and abandoning its pipes, so the call cannot outlive
/// it. stdout is kept only up to `WEB_BODY_MAX`; a longer body is reported,
/// not truncated.
fn web_curl_once(builtin: &str, args: &[&str]) -> Result<WebRun> {
    // The URL is the last argument. It is checked here, which every curl
    // transfer goes through, after the approval gate and the budget. curl is
    // told to connect to the address the check accepted, so a second DNS
    // answer cannot send the transfer to another host.
    let Some((url, rest)) = args.split_last() else {
        return Err(crate::safety::arg_err(format!("{builtin}: no URL")));
    };
    let checked = crate::security::check_http_url(builtin, url)?;
    let mut argv = vec![
        "-sS",
        "--proto",
        "=http,https",
        "--max-time",
        WEB_MAX_TIME_SECS,
    ];
    argv.extend_from_slice(rest);
    let pin = checked.curl_resolve();
    if let Some(pin) = pin.as_deref() {
        argv.extend_from_slice(&["--resolve", pin]);
    }
    argv.push(*url);
    let limit = WEB_MAX_TIME_SECS.parse::<u64>().unwrap_or(30) + WEB_KILL_GRACE_SECS;
    let run = run_tree(
        "curl",
        &argv,
        |_| {},
        None,
        std::time::Duration::from_secs(limit),
        Keep::Head(WEB_BODY_MAX),
        Keep::Tail(WEB_STDERR_TAIL),
    )
    .map_err(|e| match e {
        TreeError::Spawn(e) => crate::safety::spawn_error(builtin, "curl", &e),
        TreeError::Wait(e) => web_failure(
            builtin,
            format!("could not wait for curl: {e}"),
            "retry the call",
        ),
    })?;
    let status = match run.status {
        Some(status) if !run.timed_out => status,
        _ => {
            return Err(crate::safety::budget_exceeded(
                builtin,
                format!("curl did not finish within {limit} s and was stopped"),
                "the server is slow or unreachable; retry later or request a smaller resource",
            ))
        }
    };
    Ok(WebRun {
        status,
        body: run.stdout,
        over: run.stdout_truncated,
        stderr: run.stderr,
    })
}

/// The body of a run that completed. A body over the cap is
/// `E_BUDGET_EXCEEDED`; a nonzero exit is `E_TOOL_FAILED` carrying curl's own
/// message, which for `--fail` names the HTTP status.
fn web_body(builtin: &str, run: WebRun) -> Result<Vec<u8>> {
    if run.over {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("the response is longer than {WEB_BODY_MAX} bytes"),
            "request a smaller resource; this shell returns no truncated body",
        ));
    }
    if !run.status.success() {
        return Err(web_tool_failed(builtin, &run));
    }
    Ok(run.body)
}

fn web_tool_failed(builtin: &str, run: &WebRun) -> anyhow::Error {
    crate::safety::tool_failed(
        builtin,
        "curl",
        run.status.code(),
        &String::from_utf8_lossy(&run.stderr),
    )
}

fn web_text(body: Vec<u8>) -> Value {
    Value::Str(String::from_utf8_lossy(&body).into_owned())
}

fn web_json_value(builtin: &str, body: &[u8]) -> Result<Value> {
    serde_json::from_slice::<serde_json::Value>(body)
        .map(json_to_value)
        .map_err(|e| {
            web_failure(
                builtin,
                format!("the response is not JSON: {e}"),
                "use web_fetch for a response that is not JSON",
            )
        })
}

/// A request body as text: a String goes as it is, any other value as JSON.
fn web_request_body(builtin: &str, value: &Value) -> Result<String> {
    match value {
        Value::Str(s) => Ok(s.clone()),
        other => serde_json::to_string(&value_to_json(other.clone())).map_err(|e| {
            crate::safety::bad_arg(builtin, "a value that encodes as JSON", &e.to_string())
        }),
    }
}

/// GET `url` and return the body as text. The caller has validated the URL and
/// guarded it. An HTTP error status is a coded failure: an error page is not
/// the resource that was asked for.
fn web_get_body(builtin: &str, url: &str) -> Result<Value> {
    // Every caller has already checked the URL; this keeps a later caller from
    // handing curl an option instead.
    crate::safety::reject_option_like(builtin, &[url.to_string()])?;
    let run = web_curl(builtin, &["-L", "--fail", url])?;
    Ok(web_text(web_body(builtin, run)?))
}

fn bi_web_open_url(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_open_url", &input)?;
    let url = web_browser_target("web_open_url", &args)?;
    guard_network("web_open_url", &url)?;
    open_in_browser("web_open_url", &url)
}

fn bi_web_browser_open(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_browser_open", &input)?;
    let url = web_browser_target("web_browser_open", &args)?;
    open_in_browser("web_browser_open", &url)
}

/// The URL a browser builtin will hand to the desktop, checked before any
/// effect: an http or https URL, then the desktop-launcher checks, which refuse
/// option-like text and control characters.
fn web_browser_target(builtin: &str, args: &[Value]) -> Result<String> {
    let url = web_http_url(builtin, web_text_arg(builtin, args, 0, WEB_URL_EXPECTED)?)?;
    crate::safety::reject_unsafe_url(builtin, &url)?;
    Ok(url)
}

/// Launch the desktop's web handler on an already-checked URL. A launcher that
/// starts is `true`; one that cannot start, or exits with an error, is a coded
/// failure rather than `false`.
fn open_in_browser(builtin: &str, url: &str) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        // Not `cmd /C start`: `cmd` splits its command line on `&`, which is the
        // query-string separator, so no URL check can make that call safe.
        // `rundll32 url.dll,FileProtocolHandler` is the same ShellExecute
        // dispatch with no shell in front of it. Spawned, not waited on: a
        // browser runs until the user closes it.
        let mut browser = crate::safety::child_command("rundll32.exe");
        crate::safety::strip_ironshell_env(&mut browser);
        browser
            .args(["url.dll,FileProtocolHandler", url])
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
            .map_err(|e| crate::safety::spawn_error(builtin, "rundll32.exe", &e))?;
        return Ok(Value::Bool(true));
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("open");
        cmd.arg(url);
        return launcher_result(builtin, "open", crate::safety::output_with_timeout(cmd, 30));
    }
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("xdg-open");
        cmd.arg(url);
        return launcher_result(
            builtin,
            "xdg-open",
            crate::safety::output_with_timeout(cmd, 30),
        );
    }
    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
    {
        return Err(crate::safety::unimplemented(
            builtin,
            "opening a browser is not implemented on this platform; NOTHING WAS DONE",
            "open the URL with the system's browser",
        ));
    }
}

/// The outcome of a desktop launcher that was run to completion.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn launcher_result(
    builtin: &str,
    program: &str,
    ran: std::io::Result<std::process::Output>,
) -> Result<Value> {
    match ran {
        Ok(out) if out.status.success() => Ok(Value::Bool(true)),
        Ok(out) => Err(crate::safety::tool_failed(
            builtin,
            program,
            out.status.code(),
            &String::from_utf8_lossy(&out.stderr),
        )),
        Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Err(web_failure(
            builtin,
            format!("`{program}` did not return within 30 s"),
            "check the desktop's URL handler",
        )),
        Err(e) => Err(crate::safety::spawn_error(builtin, program, &e)),
    }
}

fn bi_web_fetch(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_fetch", &input)?;
    let url = web_http_url(
        "web_fetch",
        web_text_arg("web_fetch", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    guard_network("web_fetch", &url)?;
    web_get_body("web_fetch", &url)
}

// `web_get`, `web_browser_open`, `web_robots_txt` and `web_sitemap` are not in
// `safety::SELF_GUARDED`, so the dispatcher's central guard meters and gates
// them by name. Calling `guard_network` here as well would charge them twice.
fn bi_web_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_get", &input)?;
    let url = web_http_url(
        "web_get",
        web_text_arg("web_get", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    web_get_body("web_get", &url)
}

fn bi_web_post(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_post", &input)?;
    let url = web_http_url(
        "web_post",
        web_text_arg("web_post", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    let data = match args.get(1) {
        Some(v) => web_request_body("web_post", v)?,
        None => String::new(),
    };
    guard_network("web_post", &url)?;
    // `--data-raw`, not `-d`: curl's `-d` reads a value beginning with `@` as a
    // file name and sends that file's contents, which would be a local-file
    // read leaving the machine.
    let run = web_curl("web_post", &["-X", "POST", "--data-raw", &data, &url])?;
    Ok(web_text(web_body("web_post", run)?))
}

fn bi_web_json_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_json_get", &input)?;
    let url = web_http_url(
        "web_json_get",
        web_text_arg("web_json_get", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    guard_network("web_json_get", &url)?;
    let run = web_curl(
        "web_json_get",
        &["-L", "-H", "Accept: application/json", &url],
    )?;
    web_json_value("web_json_get", &web_body("web_json_get", run)?)
}

fn bi_web_json_post(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_json_post", &input)?;
    let url = web_http_url(
        "web_json_post",
        web_text_arg("web_json_post", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    let data = match args.get(1) {
        Some(v) => serde_json::to_string(&value_to_json(v.clone())).map_err(|e| {
            crate::safety::bad_arg(
                "web_json_post",
                "a value that encodes as JSON",
                &e.to_string(),
            )
        })?,
        None => "{}".to_string(),
    };
    guard_network("web_json_post", &url)?;
    let run = web_curl(
        "web_json_post",
        &[
            "-X",
            "POST",
            "-H",
            "Content-Type: application/json",
            "-H",
            "Accept: application/json",
            "--data-raw",
            &data,
            &url,
        ],
    )?;
    web_json_value("web_json_post", &web_body("web_json_post", run)?)
}

/// A selector `web_scrape` can honour: a bare tag name. Class and id selectors
/// (`.x`, `#x`) and combinators are refused, because the earlier code treated
/// `.x` as the tag `x` and answered with the wrong elements.
fn web_tag_selector(selector: &str) -> Result<String> {
    let mut chars = selector.chars();
    let starts_with_letter = chars.next().is_some_and(|c| c.is_ascii_alphabetic());
    if !starts_with_letter || !selector.chars().all(|c| c.is_ascii_alphanumeric()) {
        return Err(crate::safety::bad_arg(
            "web_scrape",
            "a tag name such as \"h1\" or \"a\"; class (.x), id (#x) and combined selectors are not supported",
            selector,
        ));
    }
    Ok(selector.to_ascii_lowercase())
}

/// The index of the next `<tag` opening at or after `from`, where the tag name
/// really ends (so `<a` does not match `<abbr`).
fn web_next_open(lower: &str, from: usize, open: &str) -> Option<usize> {
    let mut at = from;
    while let Some(rel) = lower[at..].find(open) {
        let idx = at + rel;
        if matches!(
            lower.as_bytes().get(idx + open.len()).copied(),
            Some(b'>' | b' ' | b'\t' | b'\n' | b'\r' | b'/')
        ) {
            return Some(idx);
        }
        at = idx + 1;
    }
    None
}

/// Every element named `tag`, from its opening tag to its matching closing
/// tag, nesting of the same name included. The search is over ASCII lowercase,
/// which keeps byte offsets identical to the original text.
fn web_scrape_elements(builtin: &str, html: &str, tag: &str) -> Result<Vec<Value>> {
    let lower = html.to_ascii_lowercase();
    let open = format!("<{tag}");
    let close = format!("</{tag}>");
    let mut found = Vec::new();
    let mut from = 0;
    while let Some(start) = web_next_open(&lower, from, &open) {
        let mut depth = 1usize;
        let mut cursor = start + open.len();
        let end = loop {
            let Some(rel) = lower[cursor..].find(&close) else {
                break None; // never closed: nothing after this opening can close it either
            };
            let close_at = cursor + rel;
            match web_next_open(&lower, cursor, &open) {
                Some(open_at) if open_at < close_at => {
                    depth += 1;
                    cursor = open_at + open.len();
                }
                _ => {
                    depth -= 1;
                    cursor = close_at + close.len();
                    if depth == 0 {
                        break Some(cursor);
                    }
                }
            }
        };
        match end {
            Some(end) => {
                if found.len() == WEB_SCRAPE_MAX_MATCHES {
                    return Err(crate::safety::budget_exceeded(
                        builtin,
                        format!("more than {WEB_SCRAPE_MAX_MATCHES} <{tag}> elements"),
                        "scrape a narrower page; this shell returns no partial list",
                    ));
                }
                found.push(Value::Str(html[start..end].to_string()));
                from = end;
            }
            None => break,
        }
    }
    Ok(found)
}

fn bi_web_scrape(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_scrape", &input)?;
    let url = web_http_url(
        "web_scrape",
        web_text_arg("web_scrape", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    let selector = match args.get(1) {
        None => None,
        Some(Value::Str(s)) => Some(web_tag_selector(s)?),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "web_scrape",
                "selector: String",
                other.type_name(),
            ))
        }
    };
    guard_network("web_scrape", &url)?;
    let run = web_curl("web_scrape", &["-L", "--fail", &url])?;
    let html = String::from_utf8_lossy(&web_body("web_scrape", run)?).into_owned();
    match selector {
        None => Ok(Value::Str(html)),
        Some(tag) => Ok(Value::Array(web_scrape_elements(
            "web_scrape",
            &html,
            &tag,
        )?)),
    }
}

/// The file name `web_download` uses when none is given: the last non-empty
/// path segment of the URL, or `download`.
fn web_download_name(url: &str) -> String {
    url::Url::parse(url)
        .ok()
        .and_then(|u| {
            u.path_segments()
                .and_then(|mut segments| segments.rfind(|s| !s.is_empty()).map(str::to_string))
        })
        .filter(|name| name != "." && name != "..")
        .unwrap_or_else(|| "download".to_string())
}

fn bi_web_download(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_download", &input)?;
    let url = web_http_url(
        "web_download",
        web_text_arg("web_download", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    let path = match args.get(1) {
        None => web_download_name(&url),
        Some(Value::Str(s)) if !s.is_empty() => s.clone(),
        Some(Value::Str(_)) => {
            return Err(crate::safety::bad_arg(
                "web_download",
                "a nonempty file path",
                "\"\"",
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "web_download",
                "path: String",
                other.type_name(),
            ))
        }
    };
    guard_network("web_download", &url)?;
    // A download writes a local file as well as fetching, so the path goes
    // through the same write jail `file_write` uses.
    let path = guard_local_write("web_download", &path)?;
    // curl wrote straight into the destination, so a dropped connection left a
    // truncated file where the old one had been, and a transaction could not
    // restore it. The download now lands in a temporary file beside the
    // destination (beside a symlink's target, as write_file_atomically does)
    // and is renamed over it only once curl succeeds.
    let requested = std::path::Path::new(&path);
    let target = match fs::symlink_metadata(requested) {
        Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(requested)
            .map_err(|e| crate::safety::fs_error("web_download", &path, &e))?,
        _ => requested.to_path_buf(),
    };
    let parent = target
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    let temporary = parent.join(format!(".ironshell_dl_{}", uuid::Uuid::new_v4()));
    let temporary_arg = temporary.to_string_lossy().to_string();
    let max = WEB_DOWNLOAD_MAX.to_string();
    let run = web_curl(
        "web_download",
        &[
            "-L",
            "--fail",
            "--max-filesize",
            &max,
            "-o",
            &temporary_arg,
            &url,
        ],
    );
    let run = match run {
        Ok(run) => run,
        Err(e) => {
            let _ = fs::remove_file(&temporary);
            return Err(e);
        }
    };
    // curl's exit status 63 is "maximum file size exceeded".
    if run.status.code() == Some(63) {
        let _ = fs::remove_file(&temporary);
        return Err(crate::safety::budget_exceeded(
            "web_download",
            format!("the file is larger than {WEB_DOWNLOAD_MAX} bytes"),
            "download a smaller file",
        ));
    }
    if !run.status.success() {
        let _ = fs::remove_file(&temporary);
        return Err(web_tool_failed("web_download", &run));
    }
    crate::tx::snapshot(&path);
    if let Err(e) = fs::rename(&temporary, &target) {
        let _ = fs::remove_file(&temporary);
        return Err(crate::safety::fs_error("web_download", &path, &e));
    }
    Ok(Value::Bool(true))
}

fn bi_web_parse_url(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let url = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "web_parse_url",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    let mut rec = std::collections::BTreeMap::new();

    // Simple URL parsing
    let mut remaining = url.as_str();

    // Protocol
    if let Some(idx) = remaining.find("://") {
        rec.insert(
            "protocol".to_string(),
            Value::Str(remaining[..idx].to_string()),
        );
        remaining = &remaining[idx + 3..];
    }

    // Host and port
    let host_end = remaining.find('/').unwrap_or(remaining.len());
    let host_part = &remaining[..host_end];
    if let Some(port_idx) = host_part.find(':') {
        rec.insert(
            "host".to_string(),
            Value::Str(host_part[..port_idx].to_string()),
        );
        rec.insert(
            "port".to_string(),
            Value::Str(host_part[port_idx + 1..].to_string()),
        );
    } else {
        rec.insert("host".to_string(), Value::Str(host_part.to_string()));
    }
    remaining = &remaining[host_end..];

    // Path and query
    if let Some(query_idx) = remaining.find('?') {
        rec.insert(
            "path".to_string(),
            Value::Str(remaining[..query_idx].to_string()),
        );
        let query = &remaining[query_idx + 1..];
        if let Some(hash_idx) = query.find('#') {
            rec.insert(
                "query".to_string(),
                Value::Str(query[..hash_idx].to_string()),
            );
            rec.insert(
                "hash".to_string(),
                Value::Str(query[hash_idx + 1..].to_string()),
            );
        } else {
            rec.insert("query".to_string(), Value::Str(query.to_string()));
        }
    } else if let Some(hash_idx) = remaining.find('#') {
        rec.insert(
            "path".to_string(),
            Value::Str(remaining[..hash_idx].to_string()),
        );
        rec.insert(
            "hash".to_string(),
            Value::Str(remaining[hash_idx + 1..].to_string()),
        );
    } else {
        rec.insert("path".to_string(), Value::Str(remaining.to_string()));
    }

    Ok(Value::Record(rec))
}

fn bi_web_encode_url(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let text = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Ok(Value::Str("".to_string())),
    };

    let mut encoded = String::new();
    for c in text.chars() {
        match c {
            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' | '~' => encoded.push(c),
            _ => {
                for b in c.to_string().bytes() {
                    encoded.push_str(&format!("%{:02X}", b));
                }
            }
        }
    }
    Ok(Value::Str(encoded))
}

fn bi_web_decode_url(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let text = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Ok(Value::Str("".to_string())),
    };

    let bytes = text.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'%' {
            if index + 2 >= bytes.len()
                || !bytes[index + 1].is_ascii_hexdigit()
                || !bytes[index + 2].is_ascii_hexdigit()
            {
                return Err(crate::safety::bad_arg(
                    "web_decode_url",
                    "two hexadecimal digits after each percent sign",
                    &text,
                ));
            }
            index += 3;
        } else {
            index += 1;
        }
    }
    let form_text = text.replace('+', " ");
    let decoded = urlencoding::decode(&form_text).map_err(|error| {
        crate::safety::bad_arg(
            "web_decode_url",
            "percent-encoded UTF-8",
            &error.to_string(),
        )
    })?;
    Ok(Value::Str(decoded.into_owned()))
}

fn bi_web_parse_query(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let query = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Ok(Value::Record(std::collections::BTreeMap::new())),
    };

    let mut rec = std::collections::BTreeMap::new();
    for pair in query.trim_start_matches('?').split('&') {
        if let Some((k, v)) = pair.split_once('=') {
            rec.insert(k.to_string(), Value::Str(v.to_string()));
        }
    }
    Ok(Value::Record(rec))
}

fn bi_web_build_query(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let rec = match args.first() {
        Some(Value::Record(r)) => r.clone(),
        _ => return Ok(Value::Str("".to_string())),
    };

    let pairs: Vec<String> = rec
        .iter()
        .map(|(k, v)| {
            format!(
                "{}={}",
                k,
                match v {
                    Value::Str(s) => s.clone(),
                    v => format!("{:?}", v),
                }
            )
        })
        .collect();

    Ok(Value::Str(pairs.join("&")))
}

/// The header record of the final response in a `curl -I -L` transcript. Each
/// redirect hop prints its own block starting with `HTTP/`, so the record is
/// reset at each one and only the block that answered is kept.
fn web_final_headers(text: &str) -> std::collections::BTreeMap<String, Value> {
    let mut rec = std::collections::BTreeMap::new();
    for line in text.lines() {
        let line = line.trim_end_matches('\r');
        if line.starts_with("HTTP/") {
            rec.clear();
        } else if let Some((k, v)) = line.split_once(':') {
            rec.insert(k.trim().to_lowercase(), Value::Str(v.trim().to_string()));
        }
    }
    rec
}

fn bi_web_headers(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_headers", &input)?;
    let url = web_http_url(
        "web_headers",
        web_text_arg("web_headers", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    guard_network("web_headers", &url)?;
    let run = web_curl("web_headers", &["-I", "-L", &url])?;
    let text = String::from_utf8_lossy(&web_body("web_headers", run)?).into_owned();
    Ok(Value::Record(web_final_headers(&text)))
}

fn bi_web_cookies(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_cookies", &input)?;
    let url = web_http_url(
        "web_cookies",
        web_text_arg("web_cookies", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    guard_network("web_cookies", &url)?;
    let run = web_curl("web_cookies", &["-I", "-L", &url])?;
    let text = String::from_utf8_lossy(&web_body("web_cookies", run)?).into_owned();
    // Every Set-Cookie line across the redirect hops, as the server sent it.
    let cookies = text
        .lines()
        .filter_map(|line| {
            let (name, value) = line.trim_end_matches('\r').split_once(':')?;
            name.trim()
                .eq_ignore_ascii_case("set-cookie")
                .then(|| Value::Str(value.trim().to_string()))
        })
        .collect();
    Ok(Value::Array(cookies))
}

/// Percent-encode text for a form: unreserved characters pass, every other
/// byte becomes `%XX`.
fn web_percent_encode(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for b in text.bytes() {
        match b {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// A form record as `application/x-www-form-urlencoded` text, keys in sorted
/// order. Values are encoded: a value containing `&` or `=` used to split into
/// extra fields, and a non-text value used to be sent as its Debug form.
fn web_form_encode(fields: &std::collections::BTreeMap<String, Value>) -> Result<String> {
    let mut pairs = Vec::with_capacity(fields.len());
    for (key, value) in fields {
        let text = match value {
            Value::Str(s) => s.clone(),
            Value::Int(n) => n.to_string(),
            Value::Float(f) => f.to_string(),
            Value::Bool(b) => b.to_string(),
            other => {
                return Err(crate::safety::bad_arg(
                    "web_form_submit",
                    &format!("field {key}: String, Int, Float or Bool"),
                    other.type_name(),
                ))
            }
        };
        pairs.push(format!(
            "{}={}",
            web_percent_encode(key),
            web_percent_encode(&text)
        ));
    }
    Ok(pairs.join("&"))
}

fn bi_web_form_submit(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_form_submit", &input)?;
    let url = web_http_url(
        "web_form_submit",
        web_text_arg("web_form_submit", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    let body = match args.get(1) {
        None => String::new(),
        // Already encoded, sent as it is.
        Some(Value::Str(s)) => s.clone(),
        Some(Value::Record(fields)) => web_form_encode(fields)?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "web_form_submit",
                "fields: Record, or an already-encoded String",
                other.type_name(),
            ))
        }
    };
    guard_network("web_form_submit", &url)?;
    let run = web_curl(
        "web_form_submit",
        &["-X", "POST", "--data-raw", &body, &url],
    )?;
    Ok(web_text(web_body("web_form_submit", run)?))
}

/// A form field name curl will take unquoted.
fn web_field_name_ok(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
}

fn bi_web_upload_file(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_upload_file", &input)?;
    let url = web_http_url(
        "web_upload_file",
        web_text_arg("web_upload_file", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    let path = web_text_arg("web_upload_file", &args, 1, "a local file path")?;
    // curl reads `;` and `"` inside `-F name=@path` as option separators, so a
    // path containing them would send under a different name or type.
    if path.is_empty() || path.contains(';') || path.contains('"') {
        return Err(crate::safety::bad_arg(
            "web_upload_file",
            "a nonempty file path without ';' or '\"' characters",
            path,
        ));
    }
    let field = match args.get(2) {
        None => "file".to_string(),
        Some(Value::Str(s)) if web_field_name_ok(s) => s.clone(),
        Some(Value::Str(s)) => {
            return Err(crate::safety::bad_arg(
                "web_upload_file",
                "a form field name of letters, digits, '_', '-' or '.'",
                s,
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "web_upload_file",
                "field: String",
                other.type_name(),
            ))
        }
    };
    guard_network("web_upload_file", &url)?;
    // The upload reads a local file, so it goes through the read guard that
    // `file_read` uses. The read is unjailed by design, as it is for `file_read`.
    let local = guard_local_read("web_upload_file", path)?;
    let form = format!("{field}=@{local}");
    let run = web_curl(
        "web_upload_file",
        &["-X", "POST", "--fail", "-F", &form, &url],
    )?;
    web_body("web_upload_file", run)?;
    Ok(Value::Bool(true))
}

/// Methods `web_rest_api` will send.
const WEB_METHODS: &[&str] = &["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];

/// An HTTP header name: RFC 9110 token characters, so a name cannot contain a
/// space, a colon, a control character, or a leading `@` that curl would read
/// as a file of headers.
fn web_header_name_ok(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c))
}

fn bi_web_rest_api(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_rest_api", &input)?;
    let method = match args.first() {
        Some(Value::Str(s)) => s.to_ascii_uppercase(),
        other => {
            return Err(crate::safety::bad_arg(
                "web_rest_api",
                "method: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    if !WEB_METHODS.contains(&method.as_str()) {
        return Err(crate::safety::bad_arg(
            "web_rest_api",
            &format!("method: one of {}", WEB_METHODS.join(", ")),
            &method,
        ));
    }
    let url = web_http_url(
        "web_rest_api",
        web_text_arg("web_rest_api", &args, 1, WEB_URL_EXPECTED)?,
    )?;
    let body = match args.get(2) {
        None => None,
        Some(v) => Some(
            serde_json::to_string(&value_to_json(v.clone())).map_err(|e| {
                crate::safety::bad_arg(
                    "web_rest_api",
                    "a value that encodes as JSON",
                    &e.to_string(),
                )
            })?,
        ),
    };

    // Headers are checked in full before any request is made. A value with a
    // CR or LF would start a new header line, so it is refused, not sent.
    let mut headers: Vec<String> = Vec::new();
    let mut has_content_type = false;
    match args.get(3) {
        None => {}
        Some(Value::Record(map)) => {
            for (name, value) in map {
                if !web_header_name_ok(name) {
                    return Err(crate::safety::bad_arg(
                        "web_rest_api",
                        "a header name of letters, digits and !#$%&'*+-.^_`|~",
                        name,
                    ));
                }
                let Value::Str(val) = value else {
                    return Err(crate::safety::bad_arg(
                        "web_rest_api",
                        &format!("header {name}: String"),
                        value.type_name(),
                    ));
                };
                if val.chars().any(|c| c.is_control()) {
                    return Err(crate::safety::bad_arg(
                        "web_rest_api",
                        &format!("header {name}: a value without control characters"),
                        "a value containing a CR, LF or other control character",
                    ));
                }
                if name.eq_ignore_ascii_case("content-type") {
                    has_content_type = true;
                }
                headers.push(format!("{name}: {val}"));
            }
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "web_rest_api",
                "headers: Record",
                other.type_name(),
            ))
        }
    }

    guard_network("web_rest_api", &url)?;
    let mut argv: Vec<&str> = vec!["-X", method.as_str()];
    for header in &headers {
        argv.push("-H");
        argv.push(header.as_str());
    }
    if let Some(data) = body.as_deref() {
        if !has_content_type {
            argv.extend(["-H", "Content-Type: application/json"]);
        }
        argv.extend(["--data-raw", data]);
    }
    argv.push(url.as_str());
    let run = web_curl("web_rest_api", &argv)?;
    let response = web_body("web_rest_api", run)?;
    match serde_json::from_slice::<serde_json::Value>(&response) {
        Ok(json) => Ok(json_to_value(json)),
        Err(_) => Ok(web_text(response)),
    }
}

/// Most messages one `web_websocket` exchange may set as `max_messages`.
const WS_MAX_MESSAGES: i64 = 1000;
/// Messages collected when `max_messages` is not given.
const WS_DEFAULT_MESSAGES: usize = 100;
/// Longest `timeout_secs` one exchange may ask for, and its default.
const WS_MAX_TIMEOUT_SECS: i64 = 120;
const WS_DEFAULT_TIMEOUT_SECS: u64 = 10;
/// Most payload, over all received messages, one exchange keeps.
const WS_PAYLOAD_MAX: usize = 8 * 1024 * 1024;
const WS_URL_EXPECTED: &str = "an absolute ws or wss URL such as wss://example.com/socket";

/// What one `web_websocket` call was asked to do, validated before anything
/// is opened.
struct WsPlan {
    url: String,
    send: Vec<String>,
    max_messages: usize,
    timeout: std::time::Duration,
}

fn ws_plan(args: &[Value]) -> Result<WsPlan> {
    const NAME: &str = "web_websocket";
    if args.len() > 3 {
        return Err(crate::safety::bad_arg(
            NAME,
            "at most three arguments: url, send, opts",
            &format!("{} arguments", args.len()),
        ));
    }
    let text = web_text_arg(NAME, args, 0, WS_URL_EXPECTED)?;
    if text.chars().any(|c| c.is_control()) {
        return Err(crate::safety::bad_arg(
            NAME,
            WS_URL_EXPECTED,
            "text with a control character",
        ));
    }
    let parsed = url::Url::parse(text)
        .map_err(|e| crate::safety::bad_arg(NAME, WS_URL_EXPECTED, &format!("{text:?} ({e})")))?;
    if !matches!(parsed.scheme(), "ws" | "wss") || parsed.host_str().is_none() {
        return Err(crate::safety::bad_arg(NAME, WS_URL_EXPECTED, text));
    }
    let send = match args.get(1) {
        None | Some(Value::Null) => Vec::new(),
        Some(Value::Str(s)) => vec![s.clone()],
        Some(Value::Array(items)) => items
            .iter()
            .map(|v| match v {
                Value::Str(s) => Ok(s.clone()),
                other => Err(crate::safety::bad_arg(
                    NAME,
                    "send: a String or an Array of Strings",
                    &format!("an Array holding {}", other.type_name()),
                )),
            })
            .collect::<Result<Vec<_>>>()?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "send: a String, an Array of Strings, or null",
                other.type_name(),
            ))
        }
    };
    let mut max_messages = WS_DEFAULT_MESSAGES;
    let mut timeout_secs = WS_DEFAULT_TIMEOUT_SECS;
    match args.get(2) {
        None | Some(Value::Null) => {}
        Some(Value::Record(map)) => {
            for (key, value) in map {
                match (key.as_str(), value) {
                    ("max_messages", Value::Int(n)) if (1..=WS_MAX_MESSAGES).contains(n) => {
                        max_messages = *n as usize
                    }
                    ("timeout_secs", Value::Int(n)) if (1..=WS_MAX_TIMEOUT_SECS).contains(n) => {
                        timeout_secs = *n as u64
                    }
                    ("max_messages", v) | ("timeout_secs", v) => {
                        return Err(crate::safety::bad_arg(
                            NAME,
                            &format!(
                                "{key}: max_messages is an Int in 1..={WS_MAX_MESSAGES}, \
                                 timeout_secs an Int in 1..={WS_MAX_TIMEOUT_SECS}"
                            ),
                            v.type_name(),
                        ))
                    }
                    _ => {
                        return Err(crate::safety::bad_arg(
                            NAME,
                            "opts keys max_messages and timeout_secs",
                            &format!("unknown option {key:?}"),
                        ))
                    }
                }
            }
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "opts: a Record or null",
                other.type_name(),
            ))
        }
    }
    Ok(WsPlan {
        url: parsed.to_string(),
        send,
        max_messages,
        timeout: std::time::Duration::from_secs(timeout_secs),
    })
}

/// `web_websocket(url, send?, opts?)`: one bounded exchange. A shell call
/// cannot hold a socket open between calls, so this connects, sends `send` as
/// text frames, collects messages until the server closes, `max_messages`
/// arrive or `timeout_secs` pass, then closes. The deadline covers the whole
/// exchange, connect and handshake included, through socket timeouts set to
/// the time that remains; reaching it while collecting is an answer
/// (`timed_out`), not an error.
#[cfg(feature = "native")]
fn bi_web_websocket(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use tungstenite::Message;
    const NAME: &str = "web_websocket";
    web_no_input(NAME, &input)?;
    let plan = ws_plan(&args)?;
    let started = std::time::Instant::now();
    let remaining = || plan.timeout.saturating_sub(started.elapsed());
    let failed = |what: &str, e: &dyn std::fmt::Display| {
        web_failure(
            NAME,
            format!("{what} {}: {e}", plan.url),
            "check the URL and that the server accepts WebSocket connections",
        )
    };
    let too_slow = |what: &str| {
        crate::safety::budget_exceeded(
            NAME,
            format!("{what} {} within {:?}", plan.url, plan.timeout),
            "the server is slow or unreachable; retry later or raise timeout_secs",
        )
    };

    let parsed = url::Url::parse(&plan.url).map_err(|e| failed("could not parse", &e))?;
    let host = parsed.host_str().unwrap_or_default().to_string();
    let port = parsed.port_or_known_default().unwrap_or(80);
    // The same address check as the HTTP builtins, under the HTTP name of the
    // scheme, and the connection goes to the addresses it accepted.
    let mut as_http = parsed.clone();
    as_http
        .set_scheme(if parsed.scheme() == "wss" {
            "https"
        } else {
            "http"
        })
        .map_err(|()| failed("could not check", &"the URL's scheme"))?;
    let checked = crate::security::check_http_url(NAME, as_http.as_str())?;
    let addrs: Vec<std::net::SocketAddr> = match checked.pin() {
        Some((_, pinned)) => pinned,
        None => std::net::ToSocketAddrs::to_socket_addrs(&(
            host.trim_start_matches('[').trim_end_matches(']'),
            port,
        ))
        .map_err(|e| failed("could not resolve", &e))?
        .collect(),
    };
    let mut last_err: Option<std::io::Error> = None;
    let mut tcp = None;
    for addr in addrs {
        let left = remaining();
        if left.is_zero() {
            break;
        }
        match std::net::TcpStream::connect_timeout(&addr, left) {
            Ok(s) => {
                tcp = Some(s);
                break;
            }
            Err(e) => last_err = Some(e),
        }
    }
    let Some(tcp) = tcp else {
        if remaining().is_zero() {
            return Err(too_slow("could not connect to"));
        }
        let e = last_err.map_or_else(|| "no address".to_string(), |e| e.to_string());
        return Err(failed("could not connect to", &e));
    };
    // The deadline is set on the socket itself, before the handshake and then
    // through the WebSocket's own stream. A `try_clone` would not do: on
    // Windows a duplicated handle's timeouts do not bound reads on the
    // original, so a silent server held the call for its own timeout.
    let set_deadline = |tcp: &std::net::TcpStream, left: std::time::Duration| -> Result<()> {
        let left = left.max(std::time::Duration::from_millis(1));
        tcp.set_read_timeout(Some(left))
            .and_then(|()| tcp.set_write_timeout(Some(left)))
            .map_err(|e| failed("could not set a deadline on", &e))
    };
    set_deadline(&tcp, remaining())?;

    let mut config = tungstenite::protocol::WebSocketConfig::default();
    config.max_message_size = Some(WS_PAYLOAD_MAX);
    config.max_frame_size = Some(WS_PAYLOAD_MAX);
    let is_timeout = |e: &tungstenite::Error| {
        matches!(e, tungstenite::Error::Io(io)
            if matches!(io.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut))
    };
    crate::tls::install_provider();
    let (mut socket, _response) =
        tungstenite::client_tls_with_config(plan.url.as_str(), tcp, Some(config), None).map_err(
            |e| match e {
                tungstenite::HandshakeError::Failure(e) if is_timeout(&e) => {
                    too_slow("could not finish the handshake with")
                }
                tungstenite::HandshakeError::Failure(e) => failed("the handshake failed with", &e),
                tungstenite::HandshakeError::Interrupted(_) => {
                    too_slow("could not finish the handshake with")
                }
            },
        )?;

    type WsSocket =
        tungstenite::WebSocket<tungstenite::stream::MaybeTlsStream<std::net::TcpStream>>;
    let deadline_socket = |socket: &WsSocket, left: std::time::Duration| -> Result<()> {
        match socket.get_ref() {
            tungstenite::stream::MaybeTlsStream::Plain(tcp) => set_deadline(tcp, left),
            tungstenite::stream::MaybeTlsStream::Rustls(tls) => set_deadline(&tls.sock, left),
            _ => Err(failed(
                "could not set a deadline on",
                &"an unexpected stream type",
            )),
        }
    };
    for text in &plan.send {
        deadline_socket(&socket, remaining())?;
        socket
            .send(Message::text(text.clone()))
            .map_err(|e| failed("could not send to", &e))?;
    }

    let mut messages = Vec::new();
    let mut received = 0usize;
    let mut closed_by_server = false;
    let mut timed_out = false;
    while messages.len() < plan.max_messages {
        let left = remaining();
        if left.is_zero() {
            timed_out = true;
            break;
        }
        deadline_socket(&socket, left)?;
        let message = match socket.read() {
            Ok(m) => m,
            Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => {
                closed_by_server = true;
                break;
            }
            Err(tungstenite::Error::Capacity(e)) => {
                return Err(crate::safety::budget_exceeded(
                    NAME,
                    format!("a message from {} is larger than allowed: {e}", plan.url),
                    "this shell keeps at most 8 MiB per exchange; ask the server for less",
                ))
            }
            Err(e) if is_timeout(&e) => {
                timed_out = true;
                break;
            }
            Err(e) => return Err(failed("could not read from", &e)),
        };
        let size = match &message {
            Message::Text(t) => t.len(),
            Message::Binary(b) => b.len(),
            _ => 0,
        };
        received = received.saturating_add(size);
        if received > WS_PAYLOAD_MAX {
            return Err(crate::safety::budget_exceeded(
                NAME,
                format!("{} sent more than {WS_PAYLOAD_MAX} bytes", plan.url),
                "this shell keeps at most 8 MiB per exchange and returns no truncated answer; lower max_messages",
            ));
        }
        match message {
            Message::Text(t) => messages.push(Value::Str(t.to_string())),
            Message::Binary(b) => {
                use base64::Engine;
                let mut rec = BTreeMap::new();
                rec.insert(
                    "binary".to_string(),
                    Value::Str(base64::engine::general_purpose::STANDARD.encode(&b)),
                );
                messages.push(Value::Record(rec));
            }
            Message::Close(_) => {
                closed_by_server = true;
                break;
            }
            Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => {}
        }
    }
    if !closed_by_server {
        // A polite close, bounded by a short deadline of its own: the answer
        // is already collected, so a failure here changes nothing.
        let _ = deadline_socket(&socket, std::time::Duration::from_millis(500));
        let _ = socket.close(None);
        let _ = socket.flush();
    }

    let mut out = BTreeMap::new();
    out.insert("messages".to_string(), Value::Array(messages));
    out.insert(
        "closed_by_server".to_string(),
        Value::Bool(closed_by_server),
    );
    out.insert("timed_out".to_string(), Value::Bool(timed_out));
    Ok(Value::Record(out))
}

#[cfg(not(feature = "native"))]
fn bi_web_websocket(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_websocket", &input)?;
    ws_plan(&args)?;
    Err(crate::safety::unimplemented(
        "web_websocket",
        "WebSocket support needs the `native` feature; NOTHING WAS OPENED",
        "build with the default `native` feature",
    ))
}

fn bi_web_graphql(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_graphql", &input)?;
    let url = web_http_url(
        "web_graphql",
        web_text_arg("web_graphql", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    let query = web_text_arg("web_graphql", &args, 1, "query: String")?;
    let variables = args
        .get(2)
        .map(|v| value_to_json(v.clone()))
        .unwrap_or(serde_json::Value::Null);
    let body = serde_json::json!({ "query": query, "variables": variables }).to_string();
    guard_network("web_graphql", &url)?;
    let run = web_curl(
        "web_graphql",
        &[
            "-X",
            "POST",
            "-H",
            "Content-Type: application/json",
            "--data-raw",
            &body,
            &url,
        ],
    )?;
    web_json_value("web_graphql", &web_body("web_graphql", run)?)
}

fn bi_web_check_url(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_check_url", &input)?;
    let url = web_http_url(
        "web_check_url",
        web_text_arg("web_check_url", &args, 0, WEB_URL_EXPECTED)?,
    )?;
    guard_network("web_check_url", &url)?;
    // The body goes to the null device; stdout carries only the status code.
    let sink = if cfg!(windows) { "NUL" } else { "/dev/null" };
    let run = web_curl(
        "web_check_url",
        &["-L", "-o", sink, "-w", "%{http_code}", &url],
    )?;
    let text = String::from_utf8_lossy(&web_body("web_check_url", run)?).into_owned();
    let code: u16 = text.trim().parse().map_err(|_| {
        web_failure(
            "web_check_url",
            format!("curl printed no HTTP status code: {:?}", text.trim()),
            "retry the call",
        )
    })?;
    // A transport failure is an error above, so `false` means the server
    // answered with an error status.
    Ok(Value::Bool((200..400).contains(&code)))
}

/// The origin (`scheme://host[:port]`) of an absolute http or https URL. A bare
/// host name is refused: guessing a scheme for it would request a host the
/// caller did not name.
fn web_site_root(builtin: &str, args: &[Value]) -> Result<String> {
    let text = web_text_arg(builtin, args, 0, WEB_URL_EXPECTED)?;
    let normalised = web_http_url(builtin, text)?;
    let parsed = url::Url::parse(&normalised)
        .map_err(|e| crate::safety::bad_arg(builtin, WEB_URL_EXPECTED, &e.to_string()))?;
    Ok(parsed.origin().ascii_serialization())
}

fn bi_web_robots_txt(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_robots_txt", &input)?;
    let url = format!("{}/robots.txt", web_site_root("web_robots_txt", &args)?);
    web_get_body("web_robots_txt", &url)
}

fn bi_web_sitemap(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_sitemap", &input)?;
    let url = format!("{}/sitemap.xml", web_site_root("web_sitemap", &args)?);
    web_get_body("web_sitemap", &url)
}

fn bi_web_extract_emails(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let text = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "web_extract_emails",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    let mut emails = Vec::new();
    let mut current = String::new();
    let mut in_email = false;

    for c in text.chars().chain(std::iter::once('\0')) {
        if c.is_alphanumeric() || c == '.' || c == '_' || c == '-' || c == '+' {
            current.push(c);
            if c == '@' {
                in_email = true;
            }
        } else if c == '@' {
            current.push(c);
            in_email = true;
        } else {
            if in_email && current.contains('@') && current.contains('.') {
                let email = current.trim_matches('.').to_string();
                if !emails.contains(&Value::Str(email.clone())) {
                    emails.push(Value::Str(email));
                }
            }
            current.clear();
            in_email = false;
        }
    }

    Ok(Value::Array(emails))
}

fn bi_web_extract_phones(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let text = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "web_extract_phones",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    let mut phones = Vec::new();
    let mut current = String::new();

    for c in text.chars().chain(std::iter::once('\0')) {
        if c.is_ascii_digit() || c == '+' || c == '-' || c == '(' || c == ')' || c == ' ' {
            current.push(c);
        } else {
            let digits: String = current.chars().filter(|c| c.is_ascii_digit()).collect();
            if digits.len() >= 7 && digits.len() <= 15 {
                phones.push(Value::Str(current.trim().to_string()));
            }
            current.clear();
        }
    }

    Ok(Value::Array(phones))
}

fn bi_web_html_to_text(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let html = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Ok(Value::Str("".to_string())),
    };

    Ok(Value::Str(strip_html_tags(&html)))
}

fn bi_web_html_to_markdown(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let html = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Ok(Value::Str("".to_string())),
    };

    // Simple HTML to Markdown conversion
    let mut md = html.clone();
    md = md.replace("<h1>", "# ").replace("</h1>", "\n");
    md = md.replace("<h2>", "## ").replace("</h2>", "\n");
    md = md.replace("<h3>", "### ").replace("</h3>", "\n");
    md = md.replace("<p>", "").replace("</p>", "\n\n");
    md = md
        .replace("<br>", "\n")
        .replace("<br/>", "\n")
        .replace("<br />", "\n");
    md = md.replace("<strong>", "**").replace("</strong>", "**");
    md = md.replace("<b>", "**").replace("</b>", "**");
    md = md.replace("<em>", "*").replace("</em>", "*");
    md = md.replace("<i>", "*").replace("</i>", "*");
    md = md.replace("<code>", "`").replace("</code>", "`");
    md = md.replace("<li>", "- ").replace("</li>", "\n");
    md = md.replace("<ul>", "").replace("</ul>", "\n");
    md = md.replace("<ol>", "").replace("</ol>", "\n");

    // Strip remaining tags
    md = strip_html_tags(&md);

    Ok(Value::Str(md))
}

fn bi_web_json_path(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let json_val = match args.first() {
        Some(v) => v.clone(),
        _ => return Ok(Value::Null),
    };
    let path = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => return Ok(json_val),
    };

    let mut current = json_val;
    for part in path
        .trim_start_matches('$')
        .trim_start_matches('.')
        .split('.')
    {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }

        // Array index?
        if part.contains('[') {
            if let Some((name, idx_str)) = part.split_once('[') {
                if !name.is_empty() {
                    current = match &current {
                        Value::Record(r) => r.get(name).cloned().unwrap_or(Value::Null),
                        _ => Value::Null,
                    };
                }
                let idx: usize = idx_str
                    .strip_suffix(']')
                    .and_then(|index| index.parse().ok())
                    .ok_or_else(|| {
                        crate::safety::bad_arg(
                            "web_json_path",
                            "a nonnegative array index followed by ]",
                            idx_str,
                        )
                    })?;
                current = match &current {
                    Value::Array(arr) => arr.get(idx).cloned().unwrap_or(Value::Null),
                    _ => Value::Null,
                };
            }
        } else {
            current = match &current {
                Value::Record(r) => r.get(part).cloned().unwrap_or(Value::Null),
                _ => Value::Null,
            };
        }
    }

    Ok(current)
}

/// Query markup with a subset of XPath. Pure: the parser and evaluator live in
/// `src/web_xpath.rs`, and this wrapper only checks arguments and maps refusals.
fn bi_web_xpath(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    web_no_input("web_xpath", &input)?;
    let html = web_text_arg("web_xpath", &args, 0, "html: String")?;
    let expression = web_text_arg("web_xpath", &args, 1, "expression: String")?;
    if args.len() > 2 {
        return Err(crate::safety::bad_arg(
            "web_xpath",
            "two arguments: html and expression",
            &format!("{} arguments", args.len()),
        ));
    }
    if html.len() > crate::web_xpath::MAX_HTML_BYTES {
        return Err(crate::safety::budget_exceeded(
            "web_xpath",
            format!(
                "html of {} bytes is over the {} MiB limit",
                html.len(),
                crate::web_xpath::MAX_HTML_BYTES / (1024 * 1024)
            ),
            "pass the part of the page that holds the match",
        ));
    }
    use crate::web_xpath::Refusal;
    match crate::web_xpath::evaluate(html, expression, WEB_SCRAPE_MAX_MATCHES) {
        Ok(found) => Ok(Value::Array(found.into_iter().map(Value::Str).collect())),
        Err(Refusal::Expression { got }) => Err(crate::safety::bad_arg(
            "web_xpath",
            "a supported XPath expression",
            &got,
        )),
        Err(Refusal::Depth) => Err(crate::safety::budget_exceeded(
            "web_xpath",
            format!(
                "element nesting deeper than {}",
                crate::web_xpath::MAX_DEPTH
            ),
            "the markup is nested too deeply to query; fix the source or extract a smaller part",
        )),
        Err(Refusal::Work) => Err(crate::safety::budget_exceeded(
            "web_xpath",
            format!(
                "an evaluation visiting more than {} nodes",
                crate::web_xpath::MAX_WORK
            ),
            "use a narrower expression: fewer // steps, or a path in a predicate over fewer nodes",
        )),
        Err(Refusal::TooManyResults { limit }) => Err(crate::safety::budget_exceeded(
            "web_xpath",
            format!("more than {limit} matches"),
            "use a narrower expression; this shell returns no partial list",
        )),
    }
}

// Helper function
fn strip_html_tags(html: &str) -> String {
    let mut result = String::new();
    let mut in_tag = false;

    for c in html.chars() {
        if c == '<' {
            in_tag = true;
        } else if c == '>' {
            in_tag = false;
        } else if !in_tag {
            result.push(c);
        }
    }

    // Clean up whitespace
    result.split_whitespace().collect::<Vec<_>>().join(" ")
}

// ============================================================================
// 460-479: Clipboard & Input
// ============================================================================

/// Whether an environment variable names a display: set and not empty.
#[cfg(target_os = "linux")]
fn display_env_set(var: &str) -> bool {
    std::env::var_os(var).is_some_and(|v| !v.is_empty())
}

/// The text clipboard builtins run xclip or xsel, which need an X display.
/// With none it is E_NO_UI; under Wayland with no XWayland display they
/// cannot reach the clipboard at all. Checked before any tool runs: xclip
/// with no display failed as E_TOOL_FAILED.
#[cfg(target_os = "linux")]
fn linux_x11_clipboard_display(name: &str) -> Result<()> {
    if display_env_set("DISPLAY") {
        return Ok(());
    }
    if display_env_set("WAYLAND_DISPLAY") {
        return Err(crate::safety::unimplemented(
            name,
            "the text clipboard is reached through X11 (xclip or xsel), and this Wayland session has no X display; NOTHING WAS DONE",
            "run with XWayland so DISPLAY is set",
        ));
    }
    Err(crate::safety::no_ui(name))
}

/// One clipboard tool run for the Linux clipboard builtins. `Ok(None)` when the
/// tool is not installed, so the caller can try the next one. Same deadline and
/// error mapping as bounded_cmd_output, which cannot tell an absent tool
/// (NotFound) apart from the other failures.
#[cfg(target_os = "linux")]
fn linux_clipboard_tool(
    name: &str,
    tool: &str,
    args: &[&str],
) -> Result<Option<std::process::Output>> {
    let mut cmd = crate::safety::child_command(tool);
    cmd.args(args);
    match crate::safety::output_with_timeout(cmd, TOOL_DEADLINE_SECS) {
        Ok(out) => Ok(Some(out)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(crate::safety::spawn_error(name, tool, &e)),
    }
}

/// The formats `clipboard_types` names, in the order it answers them.
#[cfg(any(target_os = "linux", target_os = "macos"))]
const CLIPBOARD_FORMATS: [&str; 4] = ["text", "image", "files", "audio"];

/// Which of `CLIPBOARD_FORMATS` a clipboard target or MIME type stands for, if
/// any. Everything else (TARGETS, TIMESTAMP, MULTIPLE, SAVE_TARGETS, ...) is
/// ignored.
#[cfg(target_os = "linux")]
fn clipboard_format_index(target: &str) -> Option<usize> {
    let t = target.trim().to_ascii_lowercase();
    if matches!(t.as_str(), "utf8_string" | "string" | "text") || t.starts_with("text/plain") {
        Some(0)
    } else if t.starts_with("image/") {
        Some(1)
    } else if matches!(t.as_str(), "text/uri-list" | "x-special/gnome-copied-files") {
        Some(2)
    } else if t.starts_with("audio/") {
        Some(3)
    } else {
        None
    }
}

/// The answer for a listing of targets or MIME types, one per line: the formats
/// it names, in `CLIPBOARD_FORMATS` order, each once.
#[cfg(target_os = "linux")]
fn clipboard_formats_of(listing: &[u8]) -> Value {
    let mut seen = [false; 4];
    for line in String::from_utf8_lossy(listing).lines() {
        if let Some(i) = clipboard_format_index(line) {
            seen[i] = true;
        }
    }
    Value::Array(
        CLIPBOARD_FORMATS
            .iter()
            .zip(seen)
            .filter(|(_, present)| *present)
            .map(|(name, _)| Value::Str(name.to_string()))
            .collect(),
    )
}

/// The AppleScript class codes `clipboard info` names, mapped to the formats
/// `clipboard_types` answers. Text is the plain-text classes only (utf8, ut16,
/// TEXT), as on Linux, where text/html alone does not count as text. Images are
/// PNG, TIFF, JPEG, GIF and BMP. Files are file URLs (furl) and aliases (alis).
/// Audio is mp3, M4A, WAVE and AIFF. Any other class is ignored.
#[cfg(target_os = "macos")]
fn macos_format_index(code: &str) -> Option<usize> {
    match code {
        "utf8" | "ut16" | "TEXT" => Some(0),
        "PNGf" | "TIFF" | "JPEG" | "GIFf" | "BMPf" => Some(1),
        "furl" | "alis" => Some(2),
        "mp3 " | "M4A " | "WAVE" | "AIFF" => Some(3),
        _ => None,
    }
}

/// The answer for an osascript `clipboard info` listing, which prints the flat
/// list of class and size pairs, e.g. `«class utf8», 5, «class PNGf», 1234`. An
/// empty clipboard prints nothing and answers []. Each format once, in
/// CLIPBOARD_FORMATS order.
#[cfg(target_os = "macos")]
fn macos_clipboard_formats_of(listing: &str) -> Value {
    let mut seen = [false; 4];
    let inner = listing.trim().trim_start_matches('{').trim_end_matches('}');
    for token in inner.split(", ") {
        let code = token
            .trim()
            .strip_prefix("«class ")
            .and_then(|t| t.strip_suffix('»'));
        if let Some(i) = code.and_then(macos_format_index) {
            seen[i] = true;
        }
    }
    Value::Array(
        CLIPBOARD_FORMATS
            .iter()
            .zip(seen)
            .filter(|(_, present)| *present)
            .map(|(name, _)| Value::Str(name.to_string()))
            .collect(),
    )
}

#[allow(unused_variables)]
fn bi_clipboard_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "clipboard_get";
    no_args_or_input(NAME, &args, &input)?;
    crate::safety::clipboard_read_gate(NAME)?;
    #[cfg(target_os = "windows")]
    {
        let output = gui_powershell(NAME, "Get-Clipboard")?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "Get-Clipboard",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout)
            .trim_end()
            .to_string();
        clipboard_answer(NAME, text.as_bytes())
    }
    #[cfg(target_os = "macos")]
    {
        let cmd = crate::safety::child_command("pbpaste");
        let output = bounded_cmd_output(NAME, "pbpaste", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "pbpaste",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        clipboard_answer(NAME, &output.stdout)
    }
    #[cfg(target_os = "linux")]
    {
        linux_x11_clipboard_display(NAME)?;
        // xclip reports an empty clipboard as "target not available": that is
        // the empty answer, not a failure.
        let read = |tool: &str, args: &[&str]| -> Result<Option<Vec<u8>>> {
            match linux_clipboard_tool(NAME, tool, args)? {
                None => Ok(None),
                Some(out) if out.status.success() => Ok(Some(out.stdout)),
                Some(out) => {
                    let stderr = String::from_utf8_lossy(&out.stderr);
                    if stderr.contains("not available") {
                        Ok(Some(Vec::new()))
                    } else {
                        Err(crate::safety::tool_failed(
                            NAME,
                            tool,
                            out.status.code(),
                            &gui_stderr_tail(&out),
                        ))
                    }
                }
            }
        };
        let bytes = match read("xclip", &["-selection", "clipboard", "-o"])? {
            Some(bytes) => bytes,
            None => read("xsel", &["--clipboard", "--output"])?.ok_or_else(|| {
                crate::safety::tool_missing(
                    NAME,
                    "xclip or xsel",
                    "install xclip or xsel to read the clipboard",
                )
            })?,
        };
        clipboard_answer(NAME, &bytes)
    }
    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "reading the clipboard is implemented on Windows, macOS and Linux; NOTHING WAS READ",
            "run this on Windows, macOS or Linux",
        ))
    }
}

fn bi_clipboard_set(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "clipboard_set";
    // The text comes either as the argument or from the pipe, never both. A
    // call with neither is refused: it used to answer false.
    let text = match args.first() {
        Some(v) => {
            if input.is_some() {
                return Err(crate::safety::bad_arg(
                    NAME,
                    "the text as the argument or as piped text, not both",
                    "both",
                ));
            }
            gui_text(NAME, "text", v, CLIPBOARD_MAX_BYTES, true)?
        }
        None => match input {
            Some(piped) => gui_text(NAME, "piped text", &piped, CLIPBOARD_MAX_BYTES, true)?,
            None => return Err(crate::safety::bad_arg(NAME, "the text to copy", "nothing")),
        },
    };

    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-NoProfile",
            "-NonInteractive",
            "-Command",
            &crate::ps_script!("Set-Clipboard -Value {}", crate::safety::ps_quote(&text)),
        ]);
        let output = bounded_cmd_output(NAME, "powershell", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "Set-Clipboard",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        Ok(Value::Bool(true))
    }
    #[cfg(target_os = "macos")]
    {
        let mut clip = crate::safety::child_command("pbcopy");
        crate::safety::strip_ironshell_env(&mut clip);
        let child = clip
            .stdin(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| crate::safety::spawn_error(NAME, "pbcopy", &e))?;
        let status = feed_stdin_and_wait(
            NAME,
            "pbcopy",
            child,
            text.as_bytes().to_vec(),
            TOOL_DEADLINE_SECS,
        )?;
        if !status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "pbcopy",
                status.code(),
                "it exited unsuccessfully",
            ));
        }
        Ok(Value::Bool(true))
    }
    #[cfg(target_os = "linux")]
    {
        linux_x11_clipboard_display(NAME)?;
        // xclip first, xsel when xclip is not installed. A tool that is
        // installed and fails is an error, whichever it is.
        let mut xclip = crate::safety::child_command("xclip");
        crate::safety::strip_ironshell_env(&mut xclip);
        let (tool, child) = match xclip
            .args(["-selection", "clipboard"])
            .stdin(std::process::Stdio::piped())
            .spawn()
        {
            Ok(child) => ("xclip", child),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => ("xsel", {
                let mut xsel = crate::safety::child_command("xsel");
                crate::safety::strip_ironshell_env(&mut xsel);
                xsel.args(["--clipboard", "--input"])
                    .stdin(std::process::Stdio::piped())
                    .spawn()
                    .map_err(|e| crate::safety::spawn_error(NAME, "xsel", &e))?
            }),
            Err(e) => return Err(crate::safety::spawn_error(NAME, "xclip", &e)),
        };
        let status = feed_stdin_and_wait(
            NAME,
            tool,
            child,
            text.as_bytes().to_vec(),
            TOOL_DEADLINE_SECS,
        )?;
        if !status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                tool,
                status.code(),
                "it exited unsuccessfully",
            ));
        }
        Ok(Value::Bool(true))
    }
    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "writing the clipboard is implemented on Windows, macOS and Linux; NOTHING WAS COPIED",
            "run this on Windows, macOS or Linux",
        ))
    }
}

fn bi_clipboard_clear(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("clipboard_clear", &args, &input)?;
    bi_clipboard_set(vec![Value::Str(String::new())], None)
}

fn bi_clipboard_has_text(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("clipboard_has_text", &args, &input)?;
    match bi_clipboard_get(vec![], None)? {
        Value::Str(s) => Ok(Value::Bool(!s.is_empty())),
        other => Err(crate::safety::bad_arg(
            "clipboard_has_text",
            "text from the clipboard",
            other.type_name(),
        )),
    }
}

#[allow(unused_variables)]
fn bi_clipboard_types(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("clipboard_types", &args, &input)?;
    // This always listed "text" -- on Linux and macOS without looking at the
    // clipboard at all, on Windows even when the clipboard was empty or held
    // an image. It now asks the clipboard what it holds.
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd
            .args([
                "-NoProfile",
                "-NonInteractive",
                "-STA",
                "-Command",
                "Add-Type -AssemblyName System.Windows.Forms; $c = [Windows.Forms.Clipboard]; @(if ($c::ContainsText()) {'text'}; if ($c::ContainsImage()) {'image'}; if ($c::ContainsFileDropList()) {'files'}; if ($c::ContainsAudio()) {'audio'}) -join ','",
            ]);
        let output = bounded_cmd_output("clipboard_types", "powershell", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                "clipboard_types",
                "powershell",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout);
        Ok(Value::Array(
            text.trim()
                .split(',')
                .filter(|t| !t.is_empty())
                .map(|t| Value::Str(t.to_string()))
                .collect(),
        ))
    }
    #[cfg(target_os = "linux")]
    {
        const NAME: &str = "clipboard_types";
        // With no display there is no clipboard to ask, and no tool would answer.
        if !display_env_set("DISPLAY") && !display_env_set("WAYLAND_DISPLAY") {
            return Err(crate::safety::no_ui(NAME));
        }
        // Wayland first when it is the session: wl-paste reads the clipboard the
        // desktop shows, where xclip would see only XWayland's copy.
        if display_env_set("WAYLAND_DISPLAY") {
            let out =
                linux_clipboard_tool(NAME, "wl-paste", &["--list-types"])?.ok_or_else(|| {
                    crate::safety::tool_missing(
                        NAME,
                        "wl-paste",
                        "install wl-clipboard to list the clipboard's formats",
                    )
                })?;
            if out.status.success() {
                return Ok(clipboard_formats_of(&out.stdout));
            }
            // wl-paste exits 1 and says "Nothing is copied" when no client offers data.
            if out.status.code() == Some(1)
                && String::from_utf8_lossy(&out.stderr).contains("Nothing is copied")
            {
                return Ok(Value::Array(Vec::new()));
            }
            return Err(crate::safety::tool_failed(
                NAME,
                "wl-paste",
                out.status.code(),
                &gui_stderr_tail(&out),
            ));
        }
        // X11: xclip lists the targets. xsel cannot, so it only says whether the
        // clipboard holds text.
        if let Some(out) = linux_clipboard_tool(
            NAME,
            "xclip",
            &["-selection", "clipboard", "-o", "-t", "TARGETS"],
        )? {
            if out.status.success() {
                return Ok(clipboard_formats_of(&out.stdout));
            }
            // xclip reports an empty clipboard as "target TARGETS not available".
            if String::from_utf8_lossy(&out.stderr).contains("not available") {
                return Ok(Value::Array(Vec::new()));
            }
            return Err(crate::safety::tool_failed(
                NAME,
                "xclip",
                out.status.code(),
                &gui_stderr_tail(&out),
            ));
        }
        let Some(out) = linux_clipboard_tool(NAME, "xsel", &["--clipboard", "--output"])? else {
            return Err(crate::safety::tool_missing(
                NAME,
                "xclip or xsel",
                "install xclip or xsel to list the clipboard's formats",
            ));
        };
        if !out.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                "xsel",
                out.status.code(),
                &gui_stderr_tail(&out),
            ));
        }
        Ok(if out.stdout.is_empty() {
            Value::Array(Vec::new())
        } else {
            Value::Array(vec![Value::Str("text".to_string())])
        })
    }
    #[cfg(target_os = "macos")]
    {
        // `clipboard info` lists the classes on the pasteboard. Nothing is read
        // beyond their names and sizes.
        let mut cmd = crate::safety::child_command("osascript");
        cmd.args(["-e", "clipboard info"]);
        let output = bounded_cmd_output("clipboard_types", "osascript", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            return Err(crate::safety::tool_failed(
                "clipboard_types",
                "osascript",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        Ok(macos_clipboard_formats_of(&String::from_utf8_lossy(
            &output.stdout,
        )))
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            "clipboard_types",
            "listing clipboard formats is implemented on Windows, macOS and Linux only; NOTHING WAS INSPECTED",
            "clipboard() reads the text on the clipboard",
        ))
    }
}

/// Most options one `input_select` or `input_multiselect` offers.
const INPUT_CHOICE_MAX_OPTIONS: usize = 1000;
/// Largest text `input_editor` starts with or answers.
const INPUT_EDITOR_MAX_BYTES: usize = 1024 * 1024;

/// One line from stdin, through the shared bounded reader. Closed stdin (EOF)
/// is `E_NO_UI`: it used to answer "", which read as a real answer.
fn read_answer(builtin: &str, prompt: &str) -> Result<String> {
    if !prompt.is_empty() {
        eprint!("{}", prompt);
    }
    stdin_lines::read_blocking(builtin)
}

/// Refuses piped input, and an argument count outside `min..=max`, before
/// anything is printed or read. `shape` is the signature the refusal names.
fn direct_args(
    name: &str,
    args: &[Value],
    piped: bool,
    min: usize,
    max: usize,
    shape: &str,
) -> Result<()> {
    if piped {
        return Err(crate::safety::bad_arg(
            name,
            "a direct call; the answer comes from the terminal, not piped input",
            "a piped value",
        ));
    }
    if !(min..=max).contains(&args.len()) {
        return Err(crate::safety::bad_arg(
            name,
            shape,
            &format!("{} argument(s)", args.len()),
        ));
    }
    Ok(())
}

/// A prompt: a String of at most `INPUT_TEXT_MAX_BYTES` bytes.
fn prompt_text(name: &str, value: &Value) -> Result<String> {
    match value {
        Value::Str(s) if s.len() <= INPUT_TEXT_MAX_BYTES => Ok(s.clone()),
        Value::Str(s) => Err(crate::safety::bad_arg(
            name,
            &format!("prompt of at most {INPUT_TEXT_MAX_BYTES} bytes"),
            &format!("{} bytes", s.len()),
        )),
        other => Err(crate::safety::bad_arg(
            name,
            "prompt: String",
            other.type_name(),
        )),
    }
}

/// The optional first argument as a prompt, or `default` when it is absent.
fn optional_prompt(name: &str, args: &[Value], default: &str) -> Result<String> {
    match args.first() {
        None => Ok(default.to_string()),
        Some(value) => prompt_text(name, value),
    }
}

/// An answer as a refusal shows it: its first 64 characters, quoted.
fn echo_answer(answer: &str) -> String {
    const SHOWN: usize = 64;
    if answer.chars().count() <= SHOWN {
        return format!("{answer:?}");
    }
    let head: String = answer.chars().take(SHOWN).collect();
    format!("{head:?}...")
}

/// Asks `question` until `accept` takes the answer. A rejected answer is
/// reported on stderr and asked again, at most `INPUT_MAX_ATTEMPTS` times. After
/// the last one the call refuses with E_BAD_ARG: no value is answered for an
/// answer that was not accepted.
fn ask_until<T>(
    name: &str,
    question: &str,
    expected: &str,
    mut accept: impl FnMut(&str) -> Option<T>,
) -> Result<T> {
    for _ in 0..INPUT_MAX_ATTEMPTS {
        let answer = read_answer(name, question)?;
        if let Some(value) = accept(&answer) {
            return Ok(value);
        }
        eprintln!("{name}: {} is not {expected}", echo_answer(&answer));
    }
    Err(crate::safety::bad_arg(
        name,
        expected,
        &format!("no valid answer in {INPUT_MAX_ATTEMPTS} attempts"),
    ))
}

/// The options a select offers: 1 through `INPUT_CHOICE_MAX_OPTIONS` values,
/// each a String of 1 through `INPUT_TEXT_MAX_BYTES` bytes, or an Int, Float
/// or Bool. Each comes back with the text its menu line shows; control
/// characters in that text are drawn as spaces.
fn choice_options(name: &str, value: &Value) -> Result<Vec<(Value, String)>> {
    let Value::Array(items) = value else {
        return Err(crate::safety::bad_arg(
            name,
            "options: Array of choices",
            value.type_name(),
        ));
    };
    if items.is_empty() || items.len() > INPUT_CHOICE_MAX_OPTIONS {
        return Err(crate::safety::bad_arg(
            name,
            &format!("1..={INPUT_CHOICE_MAX_OPTIONS} options"),
            &format!("{} option(s)", items.len()),
        ));
    }
    let mut out = Vec::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        let text = match item {
            Value::Str(s) if s.is_empty() || s.len() > INPUT_TEXT_MAX_BYTES => {
                return Err(crate::safety::bad_arg(
                    name,
                    &format!("option {}: 1 to {INPUT_TEXT_MAX_BYTES} bytes", i + 1),
                    &format!("{} bytes", s.len()),
                ));
            }
            Value::Str(s) => s.clone(),
            Value::Int(_) | Value::Float(_) | Value::Bool(_) => item.to_display_string(),
            other => {
                return Err(crate::safety::bad_arg(
                    name,
                    &format!("option {}: a String, Int, Float or Bool", i + 1),
                    other.type_name(),
                ));
            }
        };
        let shown: String = text
            .chars()
            .map(|c| if c.is_control() { ' ' } else { c })
            .collect();
        out.push((item.clone(), shown));
    }
    Ok(out)
}

/// A multi-select answer: 1-based numbers separated by commas, each in
/// `1..=count`, answered in the order given with repeats dropped. An empty
/// answer is the deliberate choice of nothing. Anything else is `None`.
fn parse_picks(answer: &str, count: usize) -> Option<Vec<usize>> {
    let text = answer.trim();
    let mut picks = Vec::new();
    if text.is_empty() {
        return Some(picks);
    }
    let mut seen = std::collections::BTreeSet::new();
    for token in text.split(',') {
        let n: usize = token.trim().parse().ok()?;
        if !(1..=count).contains(&n) {
            return None;
        }
        if seen.insert(n) {
            picks.push(n - 1);
        }
    }
    Some(picks)
}

/// A number answer: an Int when it parses as one, else a finite Float. NaN and
/// the infinities are not numbers an answer can give.
fn parse_number(text: &str) -> Option<Value> {
    if let Ok(n) = text.parse::<i64>() {
        return Some(Value::Int(n));
    }
    text.parse::<f64>()
        .ok()
        .filter(|f| f.is_finite())
        .map(Value::Float)
}

/// A date written `YYYY-MM-DD` that the calendar accepts, answered as its text.
fn parse_date(text: &str) -> Option<String> {
    let shaped = text.len() == 10
        && text.bytes().enumerate().all(|(i, b)| {
            if i == 4 || i == 7 {
                b == b'-'
            } else {
                b.is_ascii_digit()
            }
        });
    if !shaped {
        return None;
    }
    chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d")
        .ok()
        .map(|_| text.to_string())
}

/// `input_read_line(prompt?)`: one line from stdin, without its terminator.
fn bi_input_read_line(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_read_line";
    direct_args(
        NAME,
        &args,
        input.is_some(),
        0,
        1,
        "input_read_line(prompt?: String)",
    )?;
    let prompt = optional_prompt(NAME, &args, "")?;
    Ok(Value::Str(read_answer(NAME, &prompt)?))
}

/// `input_read_password(prompt?)`. Piped or closed stdin is read as any other
/// line, so a closed stdin is `E_NO_UI` and nothing is echoed. Only a terminal
/// gets a hidden read, through `read_terminal_password`.
fn bi_input_read_password(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_read_password";
    direct_args(
        NAME,
        &args,
        input.is_some(),
        0,
        1,
        "input_read_password(prompt?: String)",
    )?;
    let prompt = optional_prompt(NAME, &args, "Password: ")?;
    use std::io::IsTerminal;
    if !std::io::stdin().is_terminal() {
        return Ok(Value::Str(read_answer(NAME, &prompt)?));
    }
    Ok(Value::Str(read_terminal_password(NAME, &prompt)?))
}

/// A hidden read from a terminal on Windows: PowerShell's `Read-Host
/// -AsSecureString`. Only the line terminator is removed from the answer.
#[cfg(target_os = "windows")]
fn read_terminal_password(name: &str, prompt: &str) -> Result<String> {
    let ps_script = crate::ps_script!(
        r#"
$password = Read-Host -Prompt {} -AsSecureString
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
"#,
        crate::safety::ps_quote(prompt.trim_end_matches(": ").trim_end_matches(':'))
    );
    let mut shell = crate::safety::child_command("powershell");
    crate::safety::strip_ironshell_env(&mut shell);
    let output = shell
        .args(["-Command", &ps_script])
        .output()
        .map_err(|e| crate::safety::spawn_error(name, "powershell", &e))?;
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            name,
            "powershell",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout)
        .trim_end_matches(['\r', '\n'])
        .to_string())
}

/// A hidden read from a terminal on Unix: echo is off for the one line.
#[cfg(unix)]
fn read_terminal_password(name: &str, prompt: &str) -> Result<String> {
    eprint!("{prompt}");
    let mut stty = crate::safety::child_command("stty");
    crate::safety::strip_ironshell_env(&mut stty);
    let _ = stty.arg("-echo").status();
    let answer = stdin_lines::read_blocking(name);
    let mut stty = crate::safety::child_command("stty");
    crate::safety::strip_ironshell_env(&mut stty);
    let _ = stty.arg("echo").status();
    eprintln!();
    answer
}

/// Other platforms have no hidden read, so the line is read as any other.
#[cfg(not(any(unix, target_os = "windows")))]
fn read_terminal_password(name: &str, prompt: &str) -> Result<String> {
    read_answer(name, prompt)
}

/// `input_confirm(prompt?)`: `y` or `yes` answers true; `n`, `no` or an empty
/// answer answers false. Anything else is asked again.
fn bi_input_confirm(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_confirm";
    direct_args(
        NAME,
        &args,
        input.is_some(),
        0,
        1,
        "input_confirm(prompt?: String)",
    )?;
    let prompt = optional_prompt(NAME, &args, "Confirm? [y/N]: ")?;
    ask_until(
        NAME,
        &prompt,
        "y, yes, n, no or an empty answer",
        |answer| match answer.trim().to_lowercase().as_str() {
            "y" | "yes" => Some(true),
            "" | "n" | "no" => Some(false),
            _ => None,
        },
    )
    .map(Value::Bool)
}

/// `input_select(prompt, options)`: lists the options numbered, then answers
/// the one picked, as it was given. An answer that is not a number in 1..=N is
/// asked again; after the last attempt the call refuses with E_BAD_ARG.
fn bi_input_select(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_select";
    direct_args(
        NAME,
        &args,
        input.is_some(),
        2,
        2,
        "input_select(prompt: String, options: Array)",
    )?;
    let prompt = prompt_text(NAME, &args[0])?;
    let options = choice_options(NAME, &args[1])?;
    eprintln!("{prompt}");
    for (i, (_, text)) in options.iter().enumerate() {
        eprintln!("  {}. {text}", i + 1);
    }
    let count = options.len();
    let index = ask_until(
        NAME,
        "Choice: ",
        &format!("a number in 1..={count}"),
        |answer| {
            answer
                .trim()
                .parse::<usize>()
                .ok()
                .filter(|n| (1..=count).contains(n))
                .map(|n| n - 1)
        },
    )?;
    Ok(options[index].0.clone())
}

/// `input_multiselect(prompt, options)`: lists the options numbered, then
/// answers the picked ones, in the order given, as an Array. An empty answer
/// answers `[]`. An invalid answer is asked again; after the last attempt the
/// call refuses with E_BAD_ARG.
fn bi_input_multiselect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_multiselect";
    direct_args(
        NAME,
        &args,
        input.is_some(),
        2,
        2,
        "input_multiselect(prompt: String, options: Array)",
    )?;
    let prompt = prompt_text(NAME, &args[0])?;
    let options = choice_options(NAME, &args[1])?;
    eprintln!("{prompt}");
    for (i, (_, text)) in options.iter().enumerate() {
        eprintln!("  {}. {text}", i + 1);
    }
    let count = options.len();
    let picks = ask_until(
        NAME,
        "Choices: ",
        &format!("numbers in 1..={count} separated by commas, or an empty answer"),
        |answer| parse_picks(answer, count),
    )?;
    Ok(Value::Array(
        picks.into_iter().map(|i| options[i].0.clone()).collect(),
    ))
}

/// `input_number(prompt?)`: an Int or a finite Float. Other text is asked again;
/// after the last attempt the call refuses with E_BAD_ARG.
fn bi_input_number(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_number";
    direct_args(
        NAME,
        &args,
        input.is_some(),
        0,
        1,
        "input_number(prompt?: String)",
    )?;
    let prompt = optional_prompt(NAME, &args, "Enter number: ")?;
    ask_until(NAME, &prompt, "a number", |answer| {
        parse_number(answer.trim())
    })
}

/// `input_editor(initial?)`: opens the editor named by `EDITOR` on a temporary
/// file that starts as `initial`, waits for it to exit, and answers the text
/// saved. It needs a terminal on stdin and stdout; without one it refuses with
/// E_NO_UI and runs nothing. An editor that exits unsuccessfully is a coded
/// E_TOOL_FAILED.
fn bi_input_editor(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_editor";
    direct_args(
        NAME,
        &args,
        input.is_some(),
        0,
        1,
        "input_editor(initial?: String)",
    )?;
    let initial = match args.first() {
        None => String::new(),
        Some(Value::Str(s)) if s.len() <= INPUT_EDITOR_MAX_BYTES => s.clone(),
        Some(Value::Str(s)) => {
            return Err(crate::safety::bad_arg(
                NAME,
                &format!("initial text of at most {INPUT_EDITOR_MAX_BYTES} bytes"),
                &format!("{} bytes", s.len()),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "initial: String",
                other.type_name(),
            ))
        }
    };
    use std::io::IsTerminal;
    if !(std::io::stdin().is_terminal() && std::io::stdout().is_terminal()) {
        return Err(crate::safety::no_ui(NAME));
    }
    let editor = editor_program(NAME)?;
    let path = create_edit_file(NAME, &initial)?;
    let answer = run_editor(NAME, &editor, &path).and_then(|()| read_edit_file(NAME, &path));
    let _ = std::fs::remove_file(&path);
    answer.map(Value::Str)
}

/// The editor program: the `EDITOR` variable, or notepad on Windows and vi
/// elsewhere. It names one program, run without a shell, so its text is not
/// split into arguments. A value that starts with `-` is refused, since the
/// editor would read it as an option.
fn editor_program(name: &str) -> Result<String> {
    let configured = match std::env::var("EDITOR") {
        Ok(value) => value,
        Err(std::env::VarError::NotPresent) => String::new(),
        Err(std::env::VarError::NotUnicode(_)) => {
            return Err(crate::safety::bad_arg(
                name,
                "EDITOR as Unicode text naming one program",
                "non-Unicode bytes",
            ))
        }
    };
    let editor = match configured.trim() {
        "" if cfg!(target_os = "windows") => "notepad".to_string(),
        "" => "vi".to_string(),
        value => value.to_string(),
    };
    if editor.starts_with('-') {
        return Err(crate::safety::bad_arg(
            name,
            "EDITOR naming a program, not an option",
            &echo_answer(&editor),
        ));
    }
    if editor.chars().any(char::is_control) {
        return Err(crate::safety::bad_arg(
            name,
            "EDITOR without control characters",
            "a control character",
        ));
    }
    Ok(editor)
}

/// Writes `text` to a new file in the temporary directory, under a name no
/// other file holds. The file is created exclusively and, on Unix, readable
/// only by its owner.
fn create_edit_file(name: &str, text: &str) -> Result<std::path::PathBuf> {
    use std::io::Write;
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    for attempt in 0..16u32 {
        let path = std::env::temp_dir().join(format!(
            "ironshell_edit_{}_{stamp}_{attempt}.txt",
            std::process::id()
        ));
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        match options.open(&path) {
            Ok(mut file) => {
                if let Err(e) = file.write_all(text.as_bytes()) {
                    let _ = std::fs::remove_file(&path);
                    return Err(crate::safety::fs_error(name, &path, &e));
                }
                return Ok(path);
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(crate::safety::fs_error(name, &path, &e)),
        }
    }
    Err(crate::safety::fs_error(
        name,
        std::env::temp_dir(),
        &std::io::Error::other("no free temporary file name"),
    ))
}

/// Runs `editor` on `path` with the terminal inherited, without a shell.
fn run_editor(name: &str, editor: &str, path: &std::path::Path) -> Result<()> {
    let mut cmd = crate::safety::child_command(editor);
    crate::safety::strip_ironshell_env(&mut cmd);
    let status = cmd
        .arg(path)
        .status()
        .map_err(|e| crate::safety::spawn_error(name, editor, &e))?;
    if status.success() {
        return Ok(());
    }
    Err(crate::safety::tool_failed(
        name,
        editor,
        status.code(),
        "the editor exited without a successful status; nothing was answered",
    ))
}

/// The text saved in the temporary file, read through a bounded reader. A
/// file longer than `INPUT_EDITOR_MAX_BYTES` is refused, not truncated.
fn read_edit_file(name: &str, path: &std::path::Path) -> Result<String> {
    use std::io::Read;
    crate::security::check_read_jail(name, &path.to_string_lossy())?;
    let file = std::fs::File::open(path).map_err(|e| crate::safety::fs_error(name, path, &e))?;
    let mut bytes = Vec::new();
    file.take(INPUT_EDITOR_MAX_BYTES as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| crate::safety::fs_error(name, path, &e))?;
    if bytes.len() > INPUT_EDITOR_MAX_BYTES {
        return Err(crate::safety::budget_exceeded(
            name,
            format!(
                "an edited text of at most {} KiB",
                INPUT_EDITOR_MAX_BYTES / 1024
            ),
            "the text was not answered; save a shorter text",
        ));
    }
    String::from_utf8(bytes).map_err(|_| {
        crate::safety::fs_error(
            name,
            path,
            &std::io::Error::new(std::io::ErrorKind::InvalidData, "the text is not UTF-8"),
        )
    })
}

/// `input_timeout(prompt, timeout_ms)`: one stdin line, or null when
/// `timeout_ms` passes first. The line typed after the timeout is not lost;
/// it answers the next prompt.
fn bi_input_timeout(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const BUILTIN: &str = "input_timeout";
    const MAX_MS: i64 = 3_600_000;
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "no pipeline input",
            "a piped value",
        ));
    }
    let [prompt, timeout] = args.as_slice() else {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "input_timeout(prompt: String, timeout_ms: Int)",
            &format!("{} arguments", args.len()),
        ));
    };
    let Value::Str(prompt) = prompt else {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "a String prompt",
            &format!("{prompt:?}"),
        ));
    };
    let ms = match timeout {
        Value::Int(ms) if (1..=MAX_MS).contains(ms) => *ms,
        other => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "an Int timeout_ms from 1 through 3600000",
                &format!("{other:?}"),
            ))
        }
    };
    eprint!("{prompt}");
    match stdin_lines::read_line(BUILTIN, Some(std::time::Duration::from_millis(ms as u64)))? {
        Some(line) => Ok(Value::Str(line)),
        None => Ok(Value::Null),
    }
}

/// Asks for one of `choices`. An exact match wins; otherwise a prefix that
/// matches exactly one choice, ignoring case, wins. Anything else lists the
/// candidates (or says there are none) and asks again.
fn bi_input_autocomplete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_autocomplete";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "a direct call; the answer comes from the terminal, not piped input",
            "a piped value",
        ));
    }
    let [prompt, choices] = args.as_slice() else {
        return Err(crate::safety::bad_arg(
            NAME,
            "prompt: String, choices: Array of Strings",
            &format!("{} argument(s)", args.len()),
        ));
    };
    let Value::Str(prompt) = prompt else {
        return Err(crate::safety::bad_arg(
            NAME,
            "prompt: String",
            prompt.type_name(),
        ));
    };
    let Value::Array(choices) = choices else {
        return Err(crate::safety::bad_arg(
            NAME,
            "choices: Array of Strings",
            choices.type_name(),
        ));
    };
    if choices.is_empty() || choices.len() > INPUT_AUTOCOMPLETE_MAX_CHOICES {
        return Err(crate::safety::bad_arg(
            NAME,
            &format!("1..={INPUT_AUTOCOMPLETE_MAX_CHOICES} choices"),
            &format!("{} choice(s)", choices.len()),
        ));
    }
    let mut texts: Vec<&str> = Vec::with_capacity(choices.len());
    let mut seen = std::collections::BTreeSet::new();
    for (i, choice) in choices.iter().enumerate() {
        let Value::Str(text) = choice else {
            return Err(crate::safety::bad_arg(
                NAME,
                &format!("choice {}: a String", i + 1),
                choice.type_name(),
            ));
        };
        if text.is_empty() || text.len() > INPUT_TEXT_MAX_BYTES {
            return Err(crate::safety::bad_arg(
                NAME,
                &format!("choice {}: 1 to {INPUT_TEXT_MAX_BYTES} bytes", i + 1),
                &format!("{} bytes", text.len()),
            ));
        }
        if !seen.insert(text.as_str()) {
            return Err(crate::safety::bad_arg(
                NAME,
                "choices that are unique",
                &format!("duplicate {text:?}"),
            ));
        }
        texts.push(text.as_str());
    }

    for _ in 0..INPUT_AUTOCOMPLETE_MAX_ATTEMPTS {
        let answer = read_answer(NAME, prompt)?;
        if let Some(exact) = texts.iter().find(|c| **c == answer) {
            return Ok(Value::Str((*exact).to_string()));
        }
        let lower = answer.to_lowercase();
        let matches: Vec<&str> = texts
            .iter()
            .copied()
            .filter(|c| c.to_lowercase().starts_with(lower.as_str()))
            .collect();
        match matches.as_slice() {
            [only] => return Ok(Value::Str((*only).to_string())),
            [] => eprintln!("{NAME}: no match for {answer:?}"),
            many => {
                eprintln!("{NAME}: {} matches for {answer:?}:", many.len());
                for m in many.iter().take(INPUT_AUTOCOMPLETE_LIST) {
                    eprintln!("  {m}");
                }
                if many.len() > INPUT_AUTOCOMPLETE_LIST {
                    eprintln!("  ... and {} more", many.len() - INPUT_AUTOCOMPLETE_LIST);
                }
            }
        }
    }
    Err(crate::safety::bad_arg(
        NAME,
        "one of the choices, or a prefix that matches exactly one",
        &format!("no valid answer in {INPUT_AUTOCOMPLETE_MAX_ATTEMPTS} attempts"),
    ))
}

// ============================================================================
// 480-499: Security & Crypto
// ============================================================================

/// One-shot digest through IronCrypto, as lowercase hex. A refusal is the
/// coded `E_CRYPTO_FAILED` naming `builtin`.
fn ic_digest_hex<D: ironcrypto::core_types::traits::Digest>(
    builtin: &str,
    bytes: &[u8],
) -> Result<String> {
    let out = D::digest(bytes).map_err(|e| crate::safety::ic_failed(builtin, e))?;
    Ok(hex::encode(out))
}

/// One-shot MAC through IronCrypto, as lowercase hex.
fn ic_mac_hex<M: ironcrypto::core_types::traits::Mac>(
    builtin: &str,
    key: &[u8],
    data: &[u8],
) -> Result<String> {
    let tag = M::mac(key, data).map_err(|e| crate::safety::ic_failed(builtin, e))?;
    Ok(hex::encode(tag))
}

/// SHA-256 of `bytes` through IronCrypto, as raw bytes.
fn ic_sha256(builtin: &str, bytes: &[u8]) -> Result<[u8; 32]> {
    <ironcrypto::hash::Sha256 as ironcrypto::core_types::traits::Digest>::digest(bytes)
        .map_err(|e| crate::safety::ic_failed(builtin, e))
}

/// Hex digest of `bytes`, in-process.
///
/// These builtins shelled out -- `sha256sum`/`md5sum` on Unix, PowerShell on
/// Windows -- although `sha2`, `md5` and `sha1` are linked. Worse, a name the
/// match did not know fell through to SHA-256, so `crypto_hash(x, "blake3")`
/// returned a SHA-256 digest labelled as whatever was asked for.
fn digest_hex(builtin: &str, algo: &str, bytes: &[u8]) -> Result<String> {
    crate::safety::require_fips_hash(algo)?;
    let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
    Ok(match algo.to_ascii_lowercase().as_str() {
        // MD5: IronCrypto has none; a legacy digest the caller asked for (FIPS refuses it above).
        "md5" => format!("{:x}", md5::compute(bytes)),
        // SHA-1: IronCrypto has none, so it stays on the sha1 crate.
        "sha1" | "sha-1" => hex(&<sha1::Sha1 as sha1::Digest>::digest(bytes)),
        "sha256" | "sha-256" => ic_digest_hex::<ironcrypto::hash::Sha256>(builtin, bytes)?,
        "sha384" | "sha-384" => ic_digest_hex::<ironcrypto::hash::Sha384>(builtin, bytes)?,
        "sha512" | "sha-512" => ic_digest_hex::<ironcrypto::hash::Sha512>(builtin, bytes)?,
        other => {
            return Err(crate::safety::bad_arg(
                builtin,
                "algorithm md5, sha1, sha256, sha384 or sha512",
                &format!("{other:?}"),
            ))
        }
    })
}

/// `(subject, the arguments after it)`: piped, the subject is the input and
/// every argument is a parameter; called directly, it is the first argument.
/// These builtins took `args[0]` as the data even when a value was piped, so
/// `"x" | crypto_hash("md5")` hashed the string "md5".
fn subject_and_params(
    builtin: &str,
    args: &[Value],
    input: Option<Value>,
) -> Result<(String, Vec<Value>)> {
    let (subject, params) = match input {
        Some(v) => (Some(v), args.to_vec()),
        None => (args.first().cloned(), args.get(1..).unwrap_or(&[]).to_vec()),
    };
    match subject {
        Some(Value::Str(s)) => Ok((s, params)),
        other => Err(crate::safety::bad_arg(
            builtin,
            "a String (argument or piped input)",
            other.as_ref().map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

fn algo_param(builtin: &str, params: &[Value], default: &str) -> Result<String> {
    match params.first() {
        None => Ok(default.to_string()),
        Some(Value::Str(s)) => Ok(s.clone()),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            "algorithm: String",
            other.type_name(),
        )),
    }
}

/// The algorithm names `digest_hex` accepts, as `crypto_hash` spells them.
fn is_hash_algorithm(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "md5"
            | "sha1"
            | "sha-1"
            | "sha256"
            | "sha-256"
            | "sha384"
            | "sha-384"
            | "sha512"
            | "sha-512"
    )
}

fn bi_crypto_hash(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // `crypto.hash("sha256", data)`, the algorithm first, as AGENTS.md writes it.
    // Read as (data, algorithm) it was E_BAD_ARG "expected algorithm ..., got
    // \"abc\"". It is taken this way only when the first argument names an
    // algorithm and the second does not, so a call that already worked keeps
    // its meaning: `crypto_hash("md5", "sha256")` still hashes the text "md5".
    if input.is_none() {
        // A lone algorithm name is not data: `crypto.hash("sha256")` hashed the
        // text "sha256" and answered as if the caller's data had been hashed.
        if let [Value::Str(only)] = args.as_slice() {
            if is_hash_algorithm(only) {
                return Err(crate::safety::bad_arg_in(
                    "crypto_hash",
                    format!(
                        "crypto.hash: `{only}` is an algorithm name; pass the data too: crypto.hash(\"{only}\", data) or data | crypto.hash(\"{only}\")"
                    ),
                    "put the algorithm first and the data after it, or pipe the data in; to hash the text itself, spell the algorithm: crypto.hash(\"sha256\", \"sha256\")",
                ));
            }
        }
        if let [Value::Str(first), Value::Str(second)] = args.as_slice() {
            if is_hash_algorithm(first) && !is_hash_algorithm(second) {
                return Ok(Value::Str(digest_hex(
                    "crypto_hash",
                    first,
                    second.as_bytes(),
                )?));
            }
            // Neither order names an algorithm: say so, with both values, rather
            // than blaming the second one alone.
            if !is_hash_algorithm(first) && !is_hash_algorithm(second) {
                return Err(crate::safety::bad_arg_in(
                    "crypto_hash",
                    format!(
                        "crypto_hash: expected algorithm md5, sha1, sha256, sha384 or sha512, got neither {first:?} nor {second:?}"
                    ),
                    "put the algorithm first, as crypto.hash(\"sha256\", data), or last, as crypto.hash(data, \"sha256\")",
                ));
            }
        }
    }
    let (data, params) = subject_and_params("crypto_hash", &args, input)?;
    let algo = algo_param("crypto_hash", &params, "sha256")?;
    Ok(Value::Str(digest_hex(
        "crypto_hash",
        &algo,
        data.as_bytes(),
    )?))
}

/// `md5` and `sha256` shared `crypto_hash`'s dispatch row, and its default is
/// SHA-256, so `md5("hello")` returned the SHA-256 of "hello". Each now has
/// its own row with its algorithm fixed.
fn bi_named_hash(name: &str, args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (data, params) = subject_and_params(name, &args, input)?;
    if let Some(extra) = params.first() {
        return Err(crate::safety::bad_arg(
            name,
            &format!("only the data: {name} fixes its algorithm"),
            extra.type_name(),
        ));
    }
    Ok(Value::Str(digest_hex(name, name, data.as_bytes())?))
}

fn bi_crypto_hash_file(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "crypto_hash_file",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let algo = algo_param("crypto_hash_file", args.get(1..).unwrap_or(&[]), "sha256")?;
    let validated = crate::security::validate_read_path(&path)?;
    // A directory is hashed file by file, not as one read, which failed with
    // E_OS_DENIED and a permissions hint. Named here, before the read.
    if !crate::safety::names_a_remote_share(&path)
        && std::fs::metadata(&validated).is_ok_and(|m| m.is_dir())
    {
        return Err(crate::safety::bad_arg_with_hint(
            "crypto_hash_file",
            "a file path",
            "a directory",
            &format!(
                "'{path}' is a directory; hash its files with glob(\"{path}/**/*\") | map(...)"
            ),
        ));
    }
    let bytes = read_bytes_capped("crypto_hash_file", &validated)?;
    Ok(Value::Str(digest_hex("crypto_hash_file", &algo, &bytes)?))
}

fn bi_crypto_hmac(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    use hmac::{Hmac, Mac};
    let data = args
        .first()
        .ok_or_else(|| crate::safety::arg_err("crypto_hmac: data is required"))?;
    let data = expect_string("crypto_hmac", data)?;
    let key = args
        .get(1)
        .ok_or_else(|| crate::safety::arg_err("crypto_hmac: key is required"))?;
    let key = expect_string("crypto_hmac", key)?;
    let algo =
        algo_param("crypto_hmac", args.get(2..).unwrap_or(&[]), "sha256")?.to_ascii_lowercase();
    crate::safety::require_fips_hash(&algo)?;
    macro_rules! authenticate {
        ($digest:ty) => {{
            let mut mac = Hmac::<$digest>::new_from_slice(key.as_bytes())
                .map_err(|_| crate::safety::arg_err("crypto_hmac: invalid key"))?;
            mac.update(data.as_bytes());
            mac.finalize()
                .into_bytes()
                .iter()
                .map(|byte| format!("{byte:02x}"))
                .collect::<String>()
        }};
    }
    // HMAC-SHA-1 stays on the hmac crate: IronCrypto implements no SHA-1.
    let result = match algo.as_str() {
        "sha1" | "sha-1" => authenticate!(sha1::Sha1),
        "sha256" | "sha-256" => ic_mac_hex::<ironcrypto::mac::HmacSha256>(
            "crypto_hmac",
            key.as_bytes(),
            data.as_bytes(),
        )?,
        "sha384" | "sha-384" => ic_mac_hex::<ironcrypto::mac::HmacSha384>(
            "crypto_hmac",
            key.as_bytes(),
            data.as_bytes(),
        )?,
        "sha512" | "sha-512" => ic_mac_hex::<ironcrypto::mac::HmacSha512>(
            "crypto_hmac",
            key.as_bytes(),
            data.as_bytes(),
        )?,
        "md5" => {
            // HMAC-MD5 by hand (RFC 2104): IronCrypto has no MD5, and md5 0.7 predates the Digest trait.
            let shortened;
            let key = if key.len() > 64 {
                shortened = md5::compute(key.as_bytes()).0;
                &shortened[..]
            } else {
                key.as_bytes()
            };
            let mut inner_pad = [0x36; 64];
            let mut outer_pad = [0x5c; 64];
            for (i, byte) in key.iter().enumerate() {
                inner_pad[i] ^= byte;
                outer_pad[i] ^= byte;
            }
            let mut inner = md5::Context::new();
            inner.consume(inner_pad);
            inner.consume(data.as_bytes());
            let mut outer = md5::Context::new();
            outer.consume(outer_pad);
            outer.consume(inner.compute().0);
            format!("{:x}", outer.compute())
        }
        other => {
            return Err(crate::safety::bad_arg(
                "crypto_hmac",
                "algorithm md5, sha1, sha256, sha384 or sha512",
                other,
            ))
        }
    };
    Ok(Value::Str(result))
}

fn bi_crypto_uuid(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Str(uuid::Uuid::new_v4().to_string()))
}

fn bi_crypto_random_bytes(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let count = args
        .first()
        .map(|v| expect_int("crypto_random_bytes", v))
        .transpose()?
        .unwrap_or(32);
    if !(0..=1_048_576).contains(&count) {
        return Err(crate::safety::arg_err(
            "crypto_random_bytes: count must be in 0..1048576",
        ));
    }
    let mut bytes = vec![0u8; count as usize];
    crate::safety::ic_fill_random("crypto_random_bytes", &mut bytes)?;
    Ok(Value::Str(
        bytes.iter().map(|byte| format!("{byte:02x}")).collect(),
    ))
}

/// `length` characters drawn uniformly from `chars`.
///
/// `fill` supplies random bytes. Each character takes one 32-bit draw, and a
/// draw at or above the largest multiple of `chars.len()` that fits in 2^32 is
/// rejected, so no character is favoured by the modulo (a plain `% len` over a
/// 32-bit draw favours the first `2^32 % len` characters).
fn random_chars(
    chars: &[char],
    length: usize,
    mut fill: impl FnMut(&mut [u8]) -> Result<()>,
) -> Result<String> {
    let n = chars.len() as u64;
    if n == 0 || n > 1 << 32 {
        return Err(crate::safety::arg_err(
            "crypto_random_string: charset must hold between 1 and 2^32 characters",
        ));
    }
    let limit = (1u64 << 32) / n * n;
    let mut out = String::with_capacity(length);
    let mut produced = 0usize;
    let mut buf: Vec<u8> = Vec::new();
    let mut at = 0usize;
    while produced < length {
        if at + 4 > buf.len() {
            // Enough for every character still owed, even if none is rejected.
            buf = vec![0u8; 4 * (length - produced)];
            fill(&mut buf)?;
            at = 0;
        }
        let draw = u32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) as u64;
        at += 4;
        if draw < limit {
            out.push(chars[(draw % n) as usize]);
            produced += 1;
        }
    }
    Ok(out)
}

fn bi_crypto_random_string(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let length = args
        .first()
        .map(|v| expect_int("crypto_random_string", v))
        .transpose()?
        .unwrap_or(32);
    if !(0..=1_048_576).contains(&length) {
        return Err(crate::safety::arg_err(
            "crypto_random_string: length must be in 0..1048576",
        ));
    }
    let charset = args
        .get(1)
        .map(|v| expect_string("crypto_random_string", v))
        .transpose()?
        .unwrap_or("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
    let chars: Vec<char> = charset.chars().collect();
    if chars.is_empty() {
        return Err(crate::safety::arg_err(
            "crypto_random_string: charset must not be empty",
        ));
    }
    let result = random_chars(&chars, length as usize, |buf| {
        crate::safety::ic_fill_random("crypto_random_string", buf)
    })?;
    Ok(Value::Str(result))
}

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

    fn text(v: Result<Value>) -> String {
        match v {
            Ok(Value::Str(s)) => s,
            other => panic!("expected a String result, got {other:?}"),
        }
    }

    #[test]
    fn sha2_digests_match_fips_180_4() {
        // FIPS 180-4 example vectors, and the empty-message digests.
        let abc = b"abc";
        assert_eq!(
            digest_hex("t", "sha256", abc).unwrap(),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        assert_eq!(
            digest_hex("t", "sha384", abc).unwrap(),
            "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7"
        );
        assert_eq!(
            digest_hex("t", "sha512", abc).unwrap(),
            "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"
        );
        assert_eq!(
            digest_hex("t", "sha256", b"").unwrap(),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        assert_eq!(
            digest_hex("t", "sha384", b"").unwrap(),
            "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"
        );
        assert_eq!(
            digest_hex("t", "sha512", b"").unwrap(),
            "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
        );
    }

    #[test]
    fn hmac_sha2_matches_rfc_4231_cases_1_and_2() {
        let case1_key = "\u{0b}".repeat(20);
        let hmac = |data: &str, key: &str, algo: &str| {
            text(bi_crypto_hmac(
                vec![
                    Value::Str(data.to_string()),
                    Value::Str(key.to_string()),
                    Value::Str(algo.to_string()),
                ],
                None,
            ))
        };
        assert_eq!(
            hmac("Hi There", &case1_key, "sha256"),
            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
        );
        assert_eq!(
            hmac("Hi There", &case1_key, "sha384"),
            "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6"
        );
        assert_eq!(
            hmac("Hi There", &case1_key, "sha512"),
            "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
        );
        assert_eq!(
            hmac("what do ya want for nothing?", "Jefe", "sha256"),
            "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
        );
        assert_eq!(
            hmac("what do ya want for nothing?", "Jefe", "sha384"),
            "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5e69e2c78b3239ecfab21649"
        );
        assert_eq!(
            hmac("what do ya want for nothing?", "Jefe", "sha512"),
            "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
        );
    }

    #[test]
    fn random_chars_rejects_draws_that_modulo_would_bias() {
        // Three characters: 2^32 is not a multiple of 3, so the draw 0xFFFFFFFF
        // (which is 0 modulo 3, i.e. 'a') must be rejected, not mapped to 'a'.
        let mut stream = vec![0xff, 0xff, 0xff, 0xff, 4, 0, 0, 0, 5, 0, 0, 0].into_iter();
        let chars: Vec<char> = "abc".chars().collect();
        let out = random_chars(&chars, 2, |buf| {
            for b in buf.iter_mut() {
                *b = stream.next().unwrap_or(0);
            }
            Ok(())
        })
        .unwrap();
        assert_eq!(out, "bc");
    }

    #[test]
    fn random_string_uses_only_the_alphabet_at_the_requested_length() {
        let alphabet = "ABC";
        let out = text(bi_crypto_random_string(
            vec![Value::Int(3000), Value::Str(alphabet.to_string())],
            None,
        ));
        assert_eq!(out.chars().count(), 3000);
        assert!(out.chars().all(|c| alphabet.contains(c)), "{out}");
        // Each of three symbols should appear roughly 1000 times; a missing or
        // dominant symbol would mean the sampler is broken.
        for c in alphabet.chars() {
            let n = out.chars().filter(|&x| x == c).count();
            assert!((800..=1200).contains(&n), "{c} appeared {n} times");
        }
    }
}

fn bi_crypto_base64_encode(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // In-process. This piped the data through `base64` on Unix and PowerShell
    // on Windows: GNU base64 wraps at 76 columns and PowerShell does not, so a
    // long input encoded differently by OS, and any failure answered "".
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    let data = hex_subject("crypto_base64_encode", &args, input)?;
    Ok(Value::Str(STANDARD.encode(data.as_bytes())))
}

fn bi_crypto_base64_decode(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    let data = hex_subject("crypto_base64_decode", &args, input)?;
    // Wrapped input (as `base64` writes it) decodes: whitespace is not data.
    let compact: String = data.chars().filter(|c| !c.is_ascii_whitespace()).collect();
    // The URL-safe alphabet is another encoding: `-` and `_` are not base64, and
    // reading them as `+` and `/` would decode different bytes. It is refused,
    // with the one-step fix named.
    if compact.chars().any(|c| c == '-' || c == '_') {
        return Err(crate::safety::value_not_representable(
            "crypto_base64_decode",
            "crypto_base64_decode: expected standard base64, got the URL-safe alphabet (- or _)"
                .to_string(),
            "this is URL-safe base64: replace - with + and _ with /",
        ));
    }
    // Padding is part of the encoding, as Python's b64decode(validate=True)
    // requires: standard-alphabet input whose length is not a multiple of 4 is
    // refused, not guessed at. Other bad input keeps its error below.
    let alphabet_only = compact
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='));
    if alphabet_only && !compact.len().is_multiple_of(4) {
        return Err(crate::safety::value_not_representable(
            "crypto_base64_decode",
            format!(
                "crypto_base64_decode: expected base64 padded to a multiple of 4 characters, got {} characters",
                compact.len()
            ),
            "pad with = to a multiple of 4 characters",
        ));
    }
    let bytes = STANDARD.decode(compact.as_bytes()).map_err(|first| {
        crate::safety::bad_arg("crypto_base64_decode", "valid base64", &first.to_string())
    })?;
    // Bytes that are not text were replaced with U+FFFD, silently.
    String::from_utf8(bytes).map(Value::Str).map_err(|_| {
        crate::safety::bad_arg(
            "crypto_base64_decode",
            "base64 of UTF-8 text (these bytes are binary)",
            "non-UTF-8 bytes",
        )
    })
}

/// The string a hex builtin works on: the argument, else the piped value.
/// Both answered "" when there was none, which reads as "encoded nothing".
fn hex_subject(builtin: &str, args: &[Value], input: Option<Value>) -> Result<String> {
    match args.first().cloned().or(input) {
        Some(Value::Str(s)) => Ok(s),
        other => Err(crate::safety::bad_arg(
            builtin,
            "a String (argument or piped input)",
            other.as_ref().map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

fn bi_crypto_hex_encode(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let data = hex_subject("crypto_hex_encode", &args, input)?;
    let hex: String = data.bytes().map(|b| format!("{:02x}", b)).collect();
    Ok(Value::Str(hex))
}

fn bi_crypto_hex_decode(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // This sliced `data[i..i + 2]` on byte offsets: an odd length read past
    // the end and a non-ASCII character split a code point, and both
    // panicked. Invalid pairs were skipped, so "zz41" decoded to "A".
    let data = hex_subject("crypto_hex_decode", &args, input)?;
    let digits = data.as_bytes();
    if digits.len() % 2 != 0 || !digits.iter().all(u8::is_ascii_hexdigit) {
        return Err(crate::safety::bad_arg(
            "crypto_hex_decode",
            "hex digits in pairs",
            &format!("{:?}", data.chars().take(40).collect::<String>()),
        ));
    }
    let bytes: Vec<u8> = digits
        .chunks(2)
        .map(|p| u8::from_str_radix(std::str::from_utf8(p).unwrap_or("00"), 16).unwrap_or(0))
        .collect();
    // Bytes that are not text used to become U+FFFD, silently, as
    // base64_decode's did; they are refused the same way.
    String::from_utf8(bytes).map(Value::Str).map_err(|_| {
        crate::safety::bad_arg(
            "crypto_hex_decode",
            "hex of UTF-8 text (these bytes are binary)",
            "non-UTF-8 bytes",
        )
    })
}

/// The bytes of `s` that RFC 3986 keeps as they are: `A-Z a-z 0-9 - . _ ~`.
fn url_unreserved(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')
}

/// `url_encode(s)`: RFC 3986 percent-encoding of the UTF-8 bytes of `s`. Only
/// the unreserved characters are kept; everything else, a space and `/`
/// included, becomes `%XX` in upper-case hex.
fn bi_url_encode(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let data = hex_subject("url_encode", &args, input)?;
    let mut out = String::with_capacity(data.len());
    for b in data.bytes() {
        if url_unreserved(b) {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    Ok(Value::Str(out))
}

/// `url_decode(s)`: undo `url_encode`. A `%` that is not followed by two hex
/// digits is E_BAD_ARG, and so is a result that is not UTF-8. A `+` stays a
/// `+`; it is not turned into a space (that is a form-encoding rule, not RFC
/// 3986's).
fn bi_url_decode(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let data = hex_subject("url_decode", &args, input)?;
    let src = data.as_bytes();
    let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
    let mut bytes = Vec::with_capacity(src.len());
    let mut i = 0;
    while i < src.len() {
        if src[i] == b'%' {
            let pair = match (src.get(i + 1).copied(), src.get(i + 2).copied()) {
                (Some(h), Some(l)) => hex(h).zip(hex(l)),
                _ => None,
            };
            match pair {
                Some((h, l)) => bytes.push(h * 16 + l),
                None => {
                    let shown: String = data[i..].chars().take(3).collect();
                    return Err(crate::safety::bad_arg_with_hint(
                        "url_decode",
                        "`%` followed by two hex digits",
                        &format!("{shown:?} at byte {i}"),
                        "encode a literal percent sign as %25",
                    ));
                }
            }
            i += 3;
        } else {
            bytes.push(src[i]);
            i += 1;
        }
    }
    String::from_utf8(bytes).map(Value::Str).map_err(|_| {
        crate::safety::bad_arg(
            "url_decode",
            "percent-encoded UTF-8 text (these bytes are binary)",
            "non-UTF-8 bytes",
        )
    })
}

/// Envelope version tag for authenticated ciphertext. A ciphertext that does
/// not begin with this is from before AS-2026-04 was fixed and carries no
/// integrity protection; `bi_crypto_decrypt` refuses it unless the caller opts
/// in, so an attacker cannot strip the envelope to downgrade a modern
/// ciphertext onto the unauthenticated path.
const CRYPTO_ENVELOPE_V1: &str = "AE1";

/// Additional authenticated data for the original `AE1` envelope.
///
/// Frozen, through the IronShell rename too: 10.0.0 shipped ciphertext
/// authenticated under exactly these bytes, and changing them would make every
/// one of those ciphertexts undecryptable.
const CRYPTO_AAD: &[u8] = b"AetherShell-AE1";

/// AAD for the FIPS envelope, which carries its own version.
const CRYPTO_AAD_FIPS: &[u8] = b"AetherShell-AE1F";

/// Envelope version tag for ciphertext whose key was derived with PBKDF2
/// rather than Argon2id.
///
/// Argon2id is the better choice against offline cracking and stays the
/// default. It is also not FIPS-approved, which left `crypto.encrypt` with one
/// non-approved primitive in an otherwise approved chain (AS-2026-08). Under
/// `IRONSHELL_FIPS` the key is derived with PBKDF2-HMAC-SHA256 (SP 800-132)
/// instead and the envelope says so, so a deployment that must be
/// all-approved can be, without changing what anyone else gets.
const CRYPTO_ENVELOPE_V1_FIPS: &str = "AE1F";

/// Iterations for the PBKDF2 path.
///
/// Deliberately a constant rather than a field in the envelope: the header is
/// not authenticated until after key derivation, so a count carried in the
/// ciphertext would let an attacker demand an arbitrarily expensive derivation
/// before the tag could reject it. Changing this value means minting a new
/// version tag.
const CRYPTO_PBKDF2_ROUNDS: u32 = 600_000;

/// Which key-derivation function an envelope tag selects.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum CryptoKdf {
    Argon2id,
    Pbkdf2HmacSha256,
}

impl CryptoKdf {
    /// The KDF to use for new ciphertext.
    fn for_new_ciphertext() -> Self {
        if crate::safety::fips_enabled() {
            Self::Pbkdf2HmacSha256
        } else {
            Self::Argon2id
        }
    }

    /// The AEAD's additional data, which differs per version so that the
    /// version tag is *authenticated* rather than merely load-bearing.
    ///
    /// Without this, swapping `AE1F` for `AE1` on a ciphertext is rejected only
    /// because the two tags select different KDFs and therefore different keys
    /// — true today, and an accident rather than a property. Binding the
    /// version into the AAD makes the rejection structural: it holds even if
    /// two versions ever derive the same key.
    fn aad(self) -> &'static [u8] {
        match self {
            Self::Argon2id => CRYPTO_AAD,
            Self::Pbkdf2HmacSha256 => CRYPTO_AAD_FIPS,
        }
    }

    fn tag(self) -> &'static str {
        match self {
            Self::Argon2id => CRYPTO_ENVELOPE_V1,
            Self::Pbkdf2HmacSha256 => CRYPTO_ENVELOPE_V1_FIPS,
        }
    }

    /// Decrypt reads the KDF from the envelope, never from the ambient mode:
    /// ciphertext written under `IRONSHELL_FIPS` must stay readable without it,
    /// and vice versa.
    fn from_tag(tag: &str) -> Option<Self> {
        match tag {
            CRYPTO_ENVELOPE_V1 => Some(Self::Argon2id),
            CRYPTO_ENVELOPE_V1_FIPS => Some(Self::Pbkdf2HmacSha256),
            _ => None,
        }
    }
}

/// Derive a 32-byte AEAD key from a password.
///
/// Argon2id by default -- the same KDF `auth.rs` uses for password storage,
/// for the same reason: the threat is a precomputed table over a small
/// guessable space, and a fast hash invites one.
fn crypto_derive_key(
    builtin: &str,
    password: &str,
    salt: &[u8],
    kdf: CryptoKdf,
) -> Result<[u8; 32]> {
    let mut key = [0u8; 32];
    match kdf {
        // Argon2id v1.3 at the old `Argon2::default()` cost, so an envelope
        // written by 10.x-12.x derives the same key.
        CryptoKdf::Argon2id => ironcrypto::kdf::argon2::argon2(
            ironcrypto::kdf::argon2::Variant::Argon2id,
            &ironcrypto::kdf::argon2::Argon2Params::DEFAULT,
            password.as_bytes(),
            salt,
            &mut key,
        )
        .map_err(|e| crate::safety::ic_failed(builtin, e))?,
        CryptoKdf::Pbkdf2HmacSha256 => ironcrypto::kdf::pbkdf2::<ironcrypto::mac::HmacSha256>(
            password.as_bytes(),
            salt,
            CRYPTO_PBKDF2_ROUNDS,
            &mut key,
        )
        .map_err(|e| crate::safety::ic_failed(builtin, e))?,
    }
    Ok(key)
}

fn bi_crypto_encrypt(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    use ironcrypto::core_types::traits::Aead;

    let data = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "crypto_encrypt",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let password = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "crypto_encrypt",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    if password.is_empty() {
        return Err(crate::safety::arg_err(
            "crypto.encrypt requires a non-empty password; nothing was encrypted",
        ));
    }

    // Fresh salt per message, so the derived key is unique per ciphertext and a
    // random nonce carries no birthday-bound risk across messages.
    let mut salt = [0u8; 16];
    let mut nonce_bytes = [0u8; 12];
    crate::safety::ic_fill_random("crypto_encrypt", &mut salt)?;
    crate::safety::ic_fill_random("crypto_encrypt", &mut nonce_bytes)?;
    let kdf = CryptoKdf::for_new_ciphertext();
    let key = crypto_derive_key("crypto_encrypt", &password, &salt, kdf)?;

    // The envelope carries ciphertext then the 16-byte tag, the layout the
    // RustCrypto crate produced, so IronCrypto's detached tag is appended here.
    let cipher = ironcrypto::cipher::Aes256Gcm::new(&key)
        .map_err(|e| crate::safety::ic_failed("crypto_encrypt", e))?;
    let mut ct = data.as_bytes().to_vec();
    let mut tag = [0u8; 16];
    cipher
        .seal_detached(&nonce_bytes, kdf.aad(), &mut ct, &mut tag)
        .map_err(|_| {
            crate::safety::crypto_failed(
                "",
                "encryption failed; nothing was encrypted",
                "retry once; if it fails again the in-process cipher is refusing this input",
            )
        })?;
    ct.extend_from_slice(&tag);

    Ok(Value::Str(format!(
        "{}.{}.{}.{}",
        kdf.tag(),
        STANDARD.encode(salt),
        STANDARD.encode(nonce_bytes),
        STANDARD.encode(&ct)
    )))
}

/// Decrypt a pre-AS-2026-04 `openssl enc -aes-256-cbc -pbkdf2` ciphertext. Kept so
/// data written by an older IronShell stays recoverable, but off by default:
/// see the refusal in `bi_crypto_decrypt` for why.
///
/// The format is OpenSSL's `Salted__` envelope, base64 encoded: the magic, an
/// 8-byte salt, then AES-256-CBC with PKCS#7 padding. The key and IV come from
/// PBKDF2-HMAC-SHA256 at 10 000 iterations, 48 bytes, which is what
/// `openssl enc -pbkdf2` does with its defaults (OpenSSL 1.1.1 and later).
/// `openssl` is no longer run; a test decrypts OpenSSL's own output.
const CRYPTO_LEGACY_MAGIC: &[u8] = b"Salted__";
/// PBKDF2 iterations OpenSSL's `enc -pbkdf2` uses when none is given.
const CRYPTO_LEGACY_ITERATIONS: u32 = 10_000;
/// The most plaintext one legacy decrypt may return. Past it the call is
/// refused: a plaintext cut short would look whole.
const CRYPTO_LEGACY_MAX_BYTES: usize = 64 * 1024 * 1024;

fn crypto_decrypt_legacy_cbc(data: &str, password: &str) -> Result<Value> {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    use ironcrypto::core_types::traits::BlockCipher as _;

    let refused = |why: &str| {
        crate::safety::decrypt_failed(
            "crypto_decrypt",
            format!(
                "crypto_decrypt: legacy (unauthenticated) decrypt failed -- the password may be \
                 wrong, or the ciphertext may have been modified. AES-256-CBC is not authenticated, \
                 so a *successful* legacy decrypt is not proof of integrity either. {why}"
            ),
            "check the password; if it is right, the ciphertext was altered and should not be \
             trusted. Nothing was decrypted",
        )
    };
    let compact: String = data.chars().filter(|c| !c.is_whitespace()).collect();
    let raw = STANDARD
        .decode(&compact)
        .map_err(|_| refused("the input is not base64."))?;
    if raw.len() < 16 || &raw[..8] != CRYPTO_LEGACY_MAGIC {
        return Err(refused("the input has no `Salted__` header."));
    }
    let (salt, body) = (&raw[8..16], &raw[16..]);
    if body.is_empty() || body.len() % 16 != 0 {
        return Err(refused(
            "the ciphertext is not a whole number of AES blocks.",
        ));
    }
    if body.len() > CRYPTO_LEGACY_MAX_BYTES + 16 {
        return Err(refused(
            "the ciphertext is larger than the legacy decrypt limit.",
        ));
    }

    // 32 bytes of AES-256 key, then the 16-byte CBC IV.
    let mut derived = [0u8; 48];
    crate::crypto_phc::pbkdf2_sha256_rfc8018(
        "crypto_decrypt",
        password.as_bytes(),
        salt,
        CRYPTO_LEGACY_ITERATIONS,
        &mut derived,
    )?;
    let cipher = ironcrypto::cipher::Aes256::new(&derived[..32])
        .map_err(|e| crate::safety::ic_failed("crypto_decrypt", e))?;
    let mut plain = body.to_vec();
    ironcrypto::cipher::cbc_decrypt(&cipher, &derived[32..], &mut plain)
        .map_err(|e| crate::safety::ic_failed("crypto_decrypt", e))?;
    let n = ironcrypto::cipher::pkcs7_unpad(&plain)
        .map_err(|_| refused("the padding is wrong, which is what a bad password gives."))?;
    plain.truncate(n);

    // The same refusal as the authenticated path: a lossy conversion would
    // silently change the plaintext, so non-UTF-8 output is not returned.
    String::from_utf8(plain).map(Value::Str).map_err(|_| {
        crate::safety::decrypt_failed(
            "crypto_decrypt",
            "crypto_decrypt: plaintext is not valid UTF-8; the legacy decrypt \
             succeeded but its bytes are not text, so nothing was returned",
            "the plaintext is binary; the legacy ciphertext has to be decrypted by the \
             tool that wrote it",
        )
    })
}

fn bi_crypto_decrypt(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    use ironcrypto::core_types::traits::Aead;

    let data = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "crypto_decrypt",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let password = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "crypto_decrypt",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    let trimmed = data.trim();
    let parts: Vec<&str> = trimmed.split('.').collect();
    let kdf = parts.first().and_then(|t| CryptoKdf::from_tag(t));
    if parts.len() != 4 || kdf.is_none() {
        // Not an authenticated envelope. Accepting this silently would hand an
        // attacker a downgrade: strip the `AE1.` prefix and tag from a modern
        // ciphertext and the unauthenticated path would take it. So the legacy
        // format is opt-in, by whoever runs the shell rather than by whoever
        // supplies the ciphertext.
        if !crate::safety::truthy_env("IRONSHELL_CRYPTO_LEGACY_DECRYPT") {
            return Err(crate::safety::decrypt_failed(
                "crypto_decrypt",
                format!(
                    "crypto_decrypt: this is not an authenticated `{}` ciphertext. It was \
                     most likely produced by IronShell before 10.0.0, when crypto.encrypt \
                     used unauthenticated AES-256-CBC (AS-2026-04), so decrypting it cannot \
                     detect tampering. Nothing was decrypted",
                    CRYPTO_ENVELOPE_V1
                ),
                "set IRONSHELL_CRYPTO_LEGACY_DECRYPT=1 to decrypt it anyway, then re-encrypt \
                 with crypto.encrypt to gain integrity protection",
            ));
        }
        return crypto_decrypt_legacy_cbc(trimmed, &password);
    }

    let malformed = |what: &str| {
        crate::safety::decrypt_failed(
            "crypto_decrypt",
            format!("crypto_decrypt: malformed ciphertext ({what}); nothing was decrypted"),
            "pass the unmodified output of crypto.encrypt",
        )
    };
    let decode = |what: &str, s: &str| -> Result<Vec<u8>> {
        STANDARD
            .decode(s)
            .map_err(|e| malformed(&format!("{what} is not valid base64: {e}")))
    };
    let salt = decode("salt", parts[1])?;
    let nonce_bytes = decode("nonce", parts[2])?;
    let ct = decode("body", parts[3])?;
    if nonce_bytes.len() != 12 {
        return Err(malformed(&format!(
            "nonce is {} bytes, expected 12",
            nonce_bytes.len()
        )));
    }

    // The KDF comes from the envelope, never from the ambient FIPS mode. The
    // salt is attacker-chosen text, so a salt the KDF refuses is a malformed
    // ciphertext, not a shell fault.
    let kdf = kdf.expect("checked above");
    let key = crypto_derive_key("crypto_decrypt", &password, &salt, kdf).map_err(|e| {
        malformed(&format!(
            "the key could not be derived from its salt: {}",
            strip_code_prefix(&e.to_string())
        ))
    })?;
    let cipher = ironcrypto::cipher::Aes256Gcm::new(&key)
        .map_err(|e| malformed(&format!("the key has the wrong length: {e}")))?;

    // AES-GCM verifies the tag before any plaintext is released, so a wrong
    // password and a modified ciphertext give the same answer here -- and
    // unlike the CBC path, "it decrypted" now genuinely means "it was not
    // modified". The envelope stores the 16-byte tag after the ciphertext.
    let auth_failed = || {
        crate::safety::decrypt_failed(
            "crypto_decrypt",
            "crypto_decrypt: authentication failed -- the password is wrong or the \
             ciphertext was modified. No plaintext was released",
            "check the password; if it is right, the ciphertext was altered and should \
             not be trusted",
        )
    };
    let Some(tag_start) = ct.len().checked_sub(16) else {
        return Err(auth_failed());
    };
    let mut plaintext = ct;
    let tag = plaintext.split_off(tag_start);
    cipher
        .open_detached(&nonce_bytes, kdf.aad(), &mut plaintext, &tag)
        .map_err(|_| auth_failed())?;

    String::from_utf8(plaintext).map(Value::Str).map_err(|_| {
        crate::safety::decrypt_failed(
            "crypto_decrypt",
            "crypto_decrypt: plaintext is not valid UTF-8; nothing was returned",
            "the plaintext is binary; crypto.decrypt returns text only",
        )
    })
}

/// Drop a leading `E_CODE: ` token from an error's text. Used where a shared
/// helper's own code would otherwise appear inside a message that already
/// carries the `E_DECRYPT_FAILED` code.
fn strip_code_prefix(text: &str) -> &str {
    match text.split_once(": ") {
        Some((head, rest)) if head.starts_with("E_") => rest,
        _ => text,
    }
}

#[path = "digital_signatures.rs"]
mod digital_signatures;
fn bi_crypto_sign(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    digital_signatures::sign(args, input)
}

fn bi_crypto_key_generate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = "crypto_generate_key";
    if args.len() > 2 || input.is_some() {
        return Err(crate::safety::arg_err(
            "crypto_generate_key accepts zero to two arguments and no pipeline input",
        ));
    }
    let key_type = match args.first() {
        None => "rsa".to_string(),
        Some(Value::Str(s)) => s.to_ascii_lowercase(),
        Some(v) => {
            return Err(crate::safety::bad_arg(
                name,
                "key type String",
                v.type_name(),
            ))
        }
    };
    if !matches!(key_type.as_str(), "rsa" | "ec" | "ecdsa" | "ed25519") {
        return Err(crate::safety::bad_arg(
            name,
            "key type rsa, ec, ecdsa or ed25519",
            "unsupported key type",
        ));
    }
    let bits = match args.get(1) {
        None => 2048,
        Some(Value::Int(n)) if key_type == "rsa" && matches!(*n, 2048 | 3072 | 4096) => *n,
        Some(_) => {
            return Err(crate::safety::bad_arg(
                name,
                "RSA-only integer size of 2048, 3072 or 4096 bits",
                "invalid or inapplicable size",
            ))
        }
    };
    // Generated natively by IronCrypto and returned as unencrypted PKCS#8 PEM.
    // No file is written, so there is no file mode to set here; a caller that
    // saves the key owns that file's protection.
    digital_signatures::generate_key(&key_type, bits)
}

fn password_arguments<'a>(
    name: &str,
    args: &'a [Value],
    input: &Option<Value>,
    count: usize,
) -> Result<Vec<&'a str>> {
    if input.is_some() || args.len() != count {
        return Err(crate::safety::bad_arg(
            name,
            "exact positional String arguments; no pipeline input",
            "invalid call shape",
        ));
    }
    let values = args
        .iter()
        .map(|v| match v {
            Value::Str(s) => Ok(s.as_str()),
            _ => Err(crate::safety::bad_arg(name, "String", v.type_name())),
        })
        .collect::<Result<Vec<_>>>()?;
    if values[0].len() > 65536 || (count == 2 && values[1].len() > 1024) {
        return Err(crate::safety::budget_exceeded(
            name,
            "password or stored hash exceeds size limit".into(),
            "password limit 65536 bytes; stored hash limit 1024 bytes",
        ));
    }
    Ok(values)
}

fn bi_crypto_password_hash(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = "crypto_password_hash";
    let values = password_arguments(name, &args, &input, 1)?;
    let mut salt = [0u8; 16];
    crate::safety::ic_fill_random(name, &mut salt)?;
    let hash = if crate::safety::fips_enabled() {
        crate::crypto_phc::pbkdf2_sha256_hash(name, values[0].as_bytes(), &salt)?
    } else {
        crate::crypto_phc::argon2id_hash(name, values[0].as_bytes(), &salt)?
    };
    Ok(Value::Str(hash))
}

#[path = "sha_crypt.rs"]
mod sha_crypt;

fn bi_crypto_password_verify(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    use ironcrypto::core_types::ErrorKind;
    let name = "crypto_password_verify";
    let values = password_arguments(name, &args, &input, 2)?;
    let malformed = || {
        crate::safety::bad_arg(
            name,
            "supported password hash with valid parameters",
            "invalid stored hash",
        )
    };
    if values[1].len() == 64 && values[1].bytes().all(|b| b.is_ascii_hexdigit()) {
        if crate::safety::fips_enabled() {
            return Err(crate::safety::policy_deny(
                name,
                "legacy unsalted password hash",
                "rehash with crypto_password_hash",
            ));
        }
        // 64 hex digits decode to exactly 32 bytes, the SHA-256 length, so the
        // stored and computed digests are compared as the same kind of value.
        let expected = hex::decode(values[1]).map_err(|_| malformed())?;
        let actual = ic_sha256(name, values[0].as_bytes())?;
        return Ok(Value::Bool(ironcrypto::core_types::ct::verify(
            &expected, &actual,
        )));
    }
    // SHA-crypt ($5$ / $6$) is verify-only. It is built from SHA-2, but it is not
    // an approved password-hashing construction; under IRONSHELL_FIPS only PBKDF2 is,
    // as for the legacy hex and Argon2 branches.
    if values[1].starts_with("$5$") || values[1].starts_with("$6$") {
        if crate::safety::fips_enabled() {
            return Err(crate::safety::policy_deny(
                name,
                "SHA-crypt is outside the configured algorithm policy",
                "rehash with crypto_password_hash",
            ));
        }
        return Ok(Value::Bool(sha_crypt::verify(name, values[0], values[1])?));
    }
    // Salt and digest bounds are shared by both formats, and are checked before
    // the policy, as they always were.
    let bounded = |salt_len: usize, digest_len: usize| {
        if (8..=64).contains(&salt_len) && (16..=64).contains(&digest_len) {
            Ok(())
        } else {
            Err(malformed())
        }
    };
    let stored = values[1];
    let algorithm = stored
        .strip_prefix('$')
        .and_then(|rest| rest.split('$').next())
        .unwrap_or("");
    let verified = match algorithm {
        "argon2id" => {
            // IronCrypto's parser is the canonical Argon2 PHC reader: it refuses
            // padding, non-canonical decimals and unused base64 bits.
            let hash = ironcrypto::kdf::argon2::phc::PasswordHash::parse(stored)
                .map_err(|_| malformed())?;
            bounded(hash.salt.len(), hash.hash.len())?;
            if crate::safety::fips_enabled() {
                return Err(crate::safety::policy_deny(
                    name,
                    "Argon2 is outside the configured algorithm policy",
                    "use a PBKDF2 password hash",
                ));
            }
            // Version 1.3 with the three cost parameters only. A keyid or data
            // field is not something this function writes.
            if hash.version != ironcrypto::kdf::argon2::Version::V0x13
                || !hash.keyid.is_empty()
                || !hash.data.is_empty()
            {
                return Err(malformed());
            }
            let params = hash.params;
            if params.memory_kib > 65536 || params.passes > 10 || params.lanes > 4 {
                return Err(crate::safety::budget_exceeded(
                    name,
                    "stored Argon2 parameters exceed verification limits".into(),
                    "maximum m=65536 KiB, t=10, p=4",
                ));
            }
            match ironcrypto::kdf::argon2::phc::verify_password(values[0].as_bytes(), stored) {
                Ok(()) => true,
                Err(e) if e.kind() == ErrorKind::AuthenticationFailed => false,
                Err(_) => return Err(malformed()),
            }
        }
        "pbkdf2-sha256" => {
            let hash = crate::crypto_phc::parse_pbkdf2_sha256(stored).ok_or_else(|| malformed())?;
            bounded(hash.salt.len(), hash.hash.len())?;
            // The `pbkdf2` crate's defaults stand in for absent fields.
            let rounds = hash.rounds.unwrap_or(crate::crypto_phc::PBKDF2_HASH_ROUNDS);
            let output_length = hash.output_length.unwrap_or(32);
            if rounds == 0 || !(16..=64).contains(&output_length) {
                return Err(malformed());
            }
            if rounds > 1200000 {
                return Err(crate::safety::budget_exceeded(
                    name,
                    "stored PBKDF2 iterations exceed verification limit".into(),
                    "maximum 1200000 iterations",
                ));
            }
            if output_length != hash.hash.len() {
                false
            } else {
                let derived = crate::crypto_phc::pbkdf2_sha256_verify_derive(
                    name,
                    values[0].as_bytes(),
                    &hash.salt,
                    rounds,
                    output_length,
                )
                .map_err(|_| malformed())?;
                ironcrypto::core_types::ct::verify(&derived, &hash.hash)
            }
        }
        _ => return Err(malformed()),
    };
    Ok(Value::Bool(verified))
}

fn bi_crypto_checksum(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_crypto_hash_file(args, None)
}

fn bi_crypto_cert_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let name = "crypto_cert_info";
    if args.len() != 1 || input.is_some() {
        return Err(crate::safety::arg_err(
            "crypto_cert_info requires one path and no pipeline input",
        ));
    }
    let Value::Str(path) = &args[0] else {
        return Err(crate::safety::bad_arg(
            name,
            "path String",
            args[0].type_name(),
        ));
    };
    crate::safety::reject_option_like(name, std::slice::from_ref(path))?;
    let path = crate::safety::resolve_path_str(path);
    crate::security::check_read_jail(name, &path)?;
    let metadata =
        std::fs::metadata(&path).map_err(|e| crate::safety::fs_error(name, &path, &e))?;
    if !metadata.is_file() {
        return Err(crate::safety::bad_arg(
            name,
            "regular certificate file",
            "non-file path",
        ));
    }
    if metadata.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            name,
            "certificate input exceeds 64 MiB".into(),
            "inspect a smaller file",
        ));
    }
    // IronSocketLayer's X.509 (IronPKI) parses the certificates in-process; no
    // openssl process is started. See src/certificates.rs.
    let bytes = std::fs::read(&path).map_err(|e| crate::safety::fs_error(name, &path, &e))?;
    Ok(Value::Array(crate::certificates::inspect(name, &bytes)?))
}

// ============================================================================
// 500-519: Database
// ============================================================================

fn sqlite_db_exists(path: &str) -> bool {
    path == ":memory:" || std::path::Path::new(path).exists()
}

/// Refuses a database path that names an existing file which is not an SQLite
/// database. sqlite3 3.53 reads such a file as a SQL script: given
/// `sqlite3 notes.txt "VACUUM"` it ran notes.txt as SQL, opened a database
/// named `VACUUM` in the working directory, and exited 0, so a builtin handed
/// the wrong file executed it and answered true. An absent path (sqlite3
/// creates it), `:memory:`, an empty file (an empty database) and a file that
/// starts with the SQLite header pass.
fn sqlite_db_file(builtin: &str, path: &str) -> Result<()> {
    if path == ":memory:" {
        return Ok(());
    }
    crate::security::check_read_jail(builtin, path)?;
    let mut file = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        // A directory, or one sqlite3 cannot open either: its own error says so.
        Err(_) => return Ok(()),
    };
    if std::fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false) {
        return Ok(());
    }
    let mut head = [0u8; 16];
    let mut got = 0;
    while got < head.len() {
        match std::io::Read::read(&mut file, &mut head[got..]) {
            Ok(0) => break,
            Ok(n) => got += n,
            Err(e) => return Err(crate::safety::fs_error(builtin, path, &e)),
        }
    }
    if got == 0 || (got == head.len() && &head == b"SQLite format 3\0") {
        return Ok(());
    }
    Err(crate::safety::bad_arg(
        builtin,
        "an SQLite database file, or a path that does not exist yet",
        &format!("{path}, which is not an SQLite database"),
    ))
}

fn bi_db_sqlite_query(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // In-process and read-only since this commit; see src/sql.rs. It spawned
    // the sqlite3 CLI, so it was classed Exec, gated in agent mode, and absent
    // on any host without sqlite3.
    crate::sql::sql("sql", args, input)
}

/// explain_effects(code): every call in `code`, its effect class and the
/// agent-mode decision, without running it; see src/explain.rs.
fn bi_explain_effects(args: Vec<Value>) -> Result<Value> {
    match args.first() {
        Some(Value::Str(code)) => crate::explain::explain(code),
        other => Err(crate::safety::bad_arg(
            "explain_effects",
            "String",
            other.map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

/// sql_value: the one cell of a one-row, one-column query; see src/sql.rs.
fn bi_sql_value(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    crate::sql::sql_value(args, input)
}

/// The workspace jail for the database every sqlite writer changes, applied in
/// `db_sqlite_exec`, which they all reach. Those writers are WriteLocal, which
/// the dispatcher does not jail, and none guarded its database: in agent mode
/// `db_sqlite_insert` wrote a database outside the workspace that `file_write`
/// was refused for.
///
/// A helper rather than a guard call in the body, on purpose: a body that
/// guards is listed in SELF_GUARDED and skipped by the dispatcher, and
/// `db_sqlite_exec` called directly is Exec, which must keep the dispatcher's
/// approval. The dispatcher does not jail Exec, so the two checks do not overlap.
fn sqlite_db_in_workspace(db_path: &str) -> Result<String> {
    guard_local_write("db_sqlite_exec", db_path)
}

fn bi_db_sqlite_exec(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let (db_path, sql) = sqlite_exec_prepare(args)?;
    // Every mutating sqlite builtin (insert/update/delete/create_table/drop_table)
    // routes through here, so snapshotting the db file at this single chokepoint
    // makes those mutations reversible inside a transaction. No-op when no
    // transaction is active.
    crate::tx::snapshot(&db_path);
    sqlite_exec_run("db_sqlite_exec", &db_path, &sql, false)
}

/// Runs a statement that a builtin of its own built and validated. The sqlite3
/// CLI gets `-safe`, which refuses writefile(), ATTACH and the file
/// dot-commands, so a `;` the builtin missed still cannot reach the filesystem.
/// `db_sqlite_exec` takes arbitrary SQL, is classed Exec and asks for approval,
/// so it does not go through here.
fn sqlite_exec_contained(args: Vec<Value>) -> Result<Value> {
    sqlite_exec_contained_as("db_sqlite_exec", args)
}

/// [`sqlite_exec_contained`] for a builtin that names itself in the error a
/// failed statement raises, in place of `db_sqlite_exec`.
fn sqlite_exec_contained_as(builtin: &str, args: Vec<Value>) -> Result<Value> {
    let (db_path, sql) = sqlite_exec_prepare(args)?;
    // The undo journal's step for the database: absent before when this call
    // creates it, so undo removes it. One step however many statements the
    // builtin runs.
    crate::journal::record_file_once("db_sqlite_exec", &db_path);
    crate::tx::snapshot(&db_path);
    sqlite_exec_run(builtin, &db_path, &sql, true)
}

/// The arguments of a statement run, refused before anything is opened: a
/// dot-command, an option-like path, and a path outside the workspace.
fn sqlite_exec_prepare(args: Vec<Value>) -> Result<(String, String)> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_exec",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let sql = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_exec",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    crate::safety::reject_sqlite_dot_command("db_sqlite_exec", &sql)?;
    crate::safety::reject_option_like("db_sqlite_exec", std::slice::from_ref(&db_path))?;
    let db_path = sqlite_db_in_workspace(&db_path)?;
    Ok((db_path, sql))
}

/// What sqlite3 said, without its command-line wrapper: the first line of
/// stderr, minus a leading `Parse error in 3rd command line argument: `,
/// `Runtime error: ` or `Error: `, and without the echo of the statement and
/// the caret line that follow it.
fn sqlite_cli_message(stderr: &str) -> String {
    let first = stderr.lines().find(|l| !l.trim().is_empty()).unwrap_or("");
    let first = first.trim();
    if let Some(i) = first.find("command line argument: ") {
        return first[i + "command line argument: ".len()..].to_string();
    }
    for prefix in ["Runtime error: ", "Parse error: ", "Error: "] {
        if let Some(rest) = first.strip_prefix(prefix) {
            return rest.to_string();
        }
    }
    stderr.trim().to_string()
}

fn sqlite_exec_run(builtin: &str, db_path: &str, sql: &str, safe: bool) -> Result<Value> {
    // Checked again where the path is handed to the CLI, which is where it matters.
    crate::safety::reject_option_like("db_sqlite_exec", &[db_path.to_string()])?;
    sqlite_db_file("db_sqlite_exec", db_path)?;
    let mut cmd = crate::safety::child_command("sqlite3");
    if safe {
        cmd.arg("-safe");
    }
    cmd.args([db_path, sql]);
    let output = bounded_cmd_output(builtin, "sqlite3", cmd, TOOL_DEADLINE_SECS)?;
    // Every mutating sqlite builtin comes through here, and a SQL error was a
    // bare `false` with sqlite3's message discarded.
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let said = sqlite_cli_message(&stderr);
        // A statement that does not parse is the SQL's fault, not the service's:
        // sqlite3 says so in its own words, and the generic hint would send the
        // caller to check a daemon.
        if stderr.contains("syntax error") || stderr.contains("Parse error") {
            let hint = if said.contains("syntax error") {
                "the SQL did not parse; check the statement near the quoted token"
            } else {
                "the SQL named a table or column the database lacks; db_sqlite_schema(db, table) lists a table's columns"
            };
            return Err(crate::safety::tool_failed_hinted(
                builtin,
                "sqlite3",
                output.status.code(),
                &said,
                hint,
            ));
        }
        return Err(crate::safety::tool_failed(
            builtin,
            "sqlite3",
            output.status.code(),
            &said,
        ));
    }
    Ok(Value::Bool(true))
}

fn bi_db_sqlite_tables(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_tables",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    bi_db_sqlite_query(
        vec![
            Value::Str(db_path),
            Value::Str(
                "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name".to_string(),
            ),
        ],
        None,
    )
}

fn bi_db_sqlite_schema(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_schema",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table = args
        .get(1)
        .map(|v| expect_string("db_sqlite_schema", v))
        .transpose()?;

    let query = if let Some(t) = table {
        format!(
            "SELECT * FROM pragma_table_info({})",
            crate::safety::sql_literal("db_sqlite_schema", &t)?
        )
    } else {
        "SELECT sql FROM sqlite_master WHERE type='table' ORDER BY name".to_string()
    };

    bi_db_sqlite_query(vec![Value::Str(db_path), Value::Str(query)], None)
}

fn bi_db_sqlite_create(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_create",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    crate::safety::reject_option_like("db_sqlite_create", std::slice::from_ref(&db_path))?;
    // Opening creates the file, so it is jailed as a write.
    let db_path = guard_local_write("db_sqlite_create", &db_path)?;
    // A database that is new is recorded as absent before, so undo removes it.
    crate::journal::record_file_once("db_sqlite_create", &db_path);
    // Just touch the file to create empty database
    sqlite_db_file("db_sqlite_create", &db_path)?;
    let mut cmd = crate::safety::child_command("sqlite3");
    cmd.args(["-safe", &db_path, "SELECT 1"]);
    let output = bounded_cmd_output("db_sqlite_create", "sqlite3", cmd, TOOL_DEADLINE_SECS)?;
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "db_sqlite_create",
            "sqlite3",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    Ok(Value::Bool(true))
}

fn bi_db_sqlite_backup(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_backup",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let backup_path = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        None => format!("{}.backup", db_path),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_backup",
                "destination: String",
                other.type_name(),
            ))
        }
    };

    crate::safety::reject_option_like("db_sqlite_backup", std::slice::from_ref(&db_path))?;
    // The path is interpolated into a `.backup '…'` dot-command. A quote in it
    // closes that argument and the rest becomes further arguments to `.backup`
    // — measured: `.backup 'x' --append 'other.db'` reaches the option parser.
    // That is not command execution (`.backup`'s options do not run programs,
    // and a newline does not start a second dot-command when the whole string
    // arrives as one argv entry — both checked against sqlite3 3.53.4), but it
    // does let a caller who asked to write one file pass options to a command
    // they were not given. Refused rather than escaped: a backup path with a
    // quote or a newline in it is not a request worth honouring.
    if backup_path.contains('\'') || backup_path.contains('\n') {
        return Err(crate::safety::bad_arg(
            "db_sqlite_backup",
            "a backup path without quotes or newlines",
            &backup_path,
        ));
    }
    // The backup is the file written; the database is only read.
    let backup_path = guard_local_write("db_sqlite_backup", &backup_path)?;
    // sqlite3 opens an absent source by creating it, so this exited 0, wrote an
    // empty backup and left an empty database at the source path. `:memory:` is
    // equally empty in a new sqlite3 process.
    if db_path == ":memory:" {
        return Err(crate::safety::bad_arg(
            "db_sqlite_backup",
            "a database file; :memory: holds nothing in a new sqlite3 process",
            &db_path,
        ));
    }
    if !sqlite_db_exists(&db_path) {
        return Err(crate::safety::not_found(
            "db_sqlite_backup",
            "database",
            &db_path,
        ));
    }
    crate::tx::snapshot(&backup_path);
    // The journal step names the backup (absent before, or replaced), never the
    // database, which is only read; a default `<db>.backup` is named by no argument.
    crate::journal::record_group(
        "db_sqlite_backup",
        crate::safety::Effect::WriteLocal,
        vec![backup_path.clone()],
    );
    sqlite_db_file("db_sqlite_backup", &db_path)?;
    sqlite_vacuum_into("db_sqlite_backup", &db_path, &backup_path)?;
    Ok(Value::Bool(true))
}

/// Writes a copy of `db_path` to `dest` in-process with `VACUUM INTO`. This
/// replaces the sqlite3 CLI's `.backup` dot-command: `-safe` refuses `.backup`,
/// and here the destination is a bound parameter, not text inside a dot-command.
/// The copy is staged beside `dest` and renamed over it once whole, so a failed
/// backup leaves an existing one as it was.
fn sqlite_vacuum_into(builtin: &str, db_path: &str, dest: &str) -> Result<()> {
    crate::tx::snapshot(dest);
    let staged = format!("{dest}.part-{}", std::process::id());
    let _ = std::fs::remove_file(&staged);
    let copied = (|| -> Result<()> {
        let conn = rusqlite::Connection::open_with_flags(
            db_path,
            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
        )
        .map_err(|e| crate::safety::tool_failed(builtin, "VACUUM INTO", None, &e.to_string()))?;
        conn.execute("VACUUM INTO ?1", [staged.as_str()])
            .map_err(|e| {
                crate::safety::tool_failed(builtin, "VACUUM INTO", None, &e.to_string())
            })?;
        std::fs::rename(&staged, dest).map_err(|e| crate::safety::fs_error(builtin, dest, &e))
    })();
    if copied.is_err() {
        let _ = std::fs::remove_file(&staged);
    }
    copied
}

/// A coded budget refusal whose builtin name is left empty: the boundary
/// (`ensure_structured`) fills it in, so the message carries no builtin prefix.
fn budget_unnamed(message: &str, hint: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::BudgetExceeded,
        message: message.to_string(),
        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(),
    })
}

/// A coded I/O failure from a library whose error is not an `io::Error` (here
/// rusqlite), so `safety::fs_error` does not apply. `E_IO` is the code for a
/// failure that is neither absence nor refusal.
fn coded_io(builtin: &str, message: String, hint: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::Io,
        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(),
    })
}

fn bi_db_csv_to_sqlite(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    const NAME: &str = "db_csv_to_sqlite";
    let db_path = args
        .first()
        .ok_or_else(|| crate::safety::arg_err("db_csv_to_sqlite: db is required"))?;
    let db_path = expect_string(NAME, db_path)?;
    let csv_path = args
        .get(1)
        .ok_or_else(|| crate::safety::arg_err("db_csv_to_sqlite: csv is required"))?;
    let csv_path = expect_string(NAME, csv_path)?;
    let table = args
        .get(2)
        .map(|v| expect_string(NAME, v))
        .transpose()?
        .unwrap_or("imported");
    let table = crate::safety::sql_identifier(NAME, table)?;
    let csv_path = crate::safety::resolve_path_str(csv_path);
    std::fs::metadata(&csv_path).map_err(|e| crate::safety::fs_error(NAME, &csv_path, &e))?;
    let source = crate::security::validate_read_path(&csv_path).map_err(|e| {
        crate::safety::policy_deny(
            NAME,
            format!("{NAME}: {e}"),
            "the shell's read policy refuses this file; choose a file it permits",
        )
    })?;
    let metadata =
        std::fs::metadata(&source).map_err(|e| crate::safety::fs_error(NAME, &csv_path, &e))?;
    crate::security::check_file_size_limit(metadata.len()).map_err(|e| {
        crate::safety::budget_exceeded(
            NAME,
            e.to_string(),
            "the CSV file is larger than the read limit; split it into smaller files",
        )
    })?;
    let content = std::fs::read_to_string(&source)
        .map_err(|e| crate::safety::fs_error(NAME, &csv_path, &e))?;
    let csv_error = |e: csv::Error| {
        crate::safety::bad_arg(
            NAME,
            "CSV with a header and equal-length rows",
            &e.to_string(),
        )
    };
    let mut reader = csv::ReaderBuilder::new()
        .trim(csv::Trim::Headers)
        .from_reader(content.as_bytes());
    let headers = reader.headers().map_err(csv_error)?.clone();
    if headers.is_empty() {
        return Err(crate::safety::arg_err(
            "db_csv_to_sqlite: CSV header must be nonempty",
        ));
    }
    let mut names = std::collections::HashSet::new();
    let columns: Vec<String> = headers
        .iter()
        .map(|name| {
            let quoted = crate::safety::sql_identifier(NAME, name)?;
            if !names.insert(name.to_ascii_lowercase()) {
                return Err(crate::safety::arg_err(
                    "db_csv_to_sqlite: duplicate CSV column name",
                ));
            }
            Ok(quoted)
        })
        .collect::<Result<_>>()?;
    // Parse all rows before opening the destination; failed validation creates nothing.
    let rows = reader
        .records()
        .enumerate()
        .map(|(index, row)| {
            if index >= 1_000_000 {
                return Err(crate::safety::budget_exceeded(
                    NAME,
                    "CSV exceeds 1000000 rows".to_string(),
                    "split the CSV into files of at most 1000000 rows",
                ));
            }
            row.map_err(csv_error)
        })
        .collect::<Result<Vec<_>>>()?;
    let db_path = guard_local_write(NAME, db_path)?;
    crate::tx::snapshot(&db_path);
    let mut db = rusqlite::Connection::open(&db_path).map_err(|e| {
        coded_io(
            NAME,
            format!("{NAME}: cannot open the database: {e}"),
            "check that the database path is writable and not locked by another process",
        )
    })?;
    let transaction = db.transaction().map_err(|e| {
        coded_io(
            NAME,
            format!("{NAME}: cannot begin the import transaction: {e}"),
            "no rows were written; check that the database is not locked or corrupt",
        )
    })?;
    let sql_error = |e: rusqlite::Error| {
        crate::safety::arg_err(&format!(
            "{NAME}: SQLite rejected import: {e}; no rows committed"
        ))
    };
    // Typed as `sql` reads the same file: an empty cell is NULL and a column of
    // numbers is INTEGER or REAL, so ORDER BY and sum() work on numbers.
    let header_names: Vec<String> = headers.iter().map(str::to_string).collect();
    let typed = csv_rows_sql(&header_names, &rows);
    let definitions = columns
        .iter()
        .zip(&header_names)
        .map(|(quoted, name)| {
            let kind = sqlite_column_type(typed.iter().filter_map(|row| row.get(name)));
            format!("{quoted} {kind}")
        })
        .collect::<Vec<_>>()
        .join(", ");
    transaction
        .execute_batch(&format!(
            "CREATE TABLE IF NOT EXISTS {table} ({definitions})"
        ))
        .map_err(sql_error)?;
    let placeholders = vec!["?"; columns.len()].join(", ");
    {
        let mut statement = transaction
            .prepare(&format!(
                "INSERT INTO {table} ({}) VALUES ({placeholders})",
                columns.join(", ")
            ))
            .map_err(sql_error)?;
        for row in &typed {
            let params: Vec<rusqlite::types::Value> = header_names
                .iter()
                .map(|name| {
                    row.get(name)
                        .map(crate::sql::to_sql)
                        .unwrap_or(rusqlite::types::Value::Null)
                })
                .collect();
            statement
                .execute(rusqlite::params_from_iter(params))
                .map_err(sql_error)?;
        }
    }
    transaction
        .commit()
        .map_err(|e| {
            coded_io(
                NAME,
                format!("{NAME}: committing import: {e}"),
                "the import was rolled back and no rows were committed; check that the database is writable and has space",
            )
        })?;
    Ok(Value::Bool(true))
}

fn bi_db_sqlite_to_csv(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_to_csv",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table_or_query = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_to_csv",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    // The output was written with a bare fs::write: unjailed, not
    // journalled, and truncated in place before the new text landed. It is
    // now refused before sqlite3 runs if the jail forbids it, snapshotted for
    // a transaction, and published atomically, as session_export does.
    let output_path = args
        .get(2)
        .map(|v| expect_string("db_sqlite_to_csv", v))
        .transpose()?
        .map(|p| guard_local_write("db_sqlite_to_csv", p))
        .transpose()?;

    // A leading SELECT means the caller passed a query and owns it, the same
    // contract as the WHERE clause in `db_sqlite_delete`. Anything else is a
    // table *name*, so it is an identifier and is validated — without this it
    // was interpolated raw, and the sqlite3 CLI runs every `;`-separated
    // statement it is handed.
    let upper = table_or_query.trim_start().to_ascii_uppercase();
    let is_query = upper.starts_with("SELECT")
        && upper[6..]
            .chars()
            .next()
            .is_some_and(|c| !(c.is_alphanumeric() || c == '_'));
    let query = if is_query {
        table_or_query
    } else {
        format!(
            "SELECT * FROM {}",
            crate::safety::sql_identifier("db_sqlite_to_csv", &table_or_query)?
        )
    };

    crate::safety::reject_sqlite_dot_command("db_sqlite_to_csv", &query)?;
    crate::safety::reject_option_like("db_sqlite_to_csv", std::slice::from_ref(&db_path))?;
    // sqlite3 creates an absent database, so an export would leave one behind.
    if !sqlite_db_exists(&db_path) {
        return Err(crate::safety::not_found(
            "db_sqlite_to_csv",
            "database",
            &db_path,
        ));
    }
    sqlite_db_file("db_sqlite_to_csv", &db_path)?;
    let mut cmd = crate::safety::child_command("sqlite3");
    // -readonly: a SELECT that carries a second statement cannot change the file.
    cmd.args(["-safe", "-readonly", "-header", "-csv", &db_path, &query]);
    let output = bounded_cmd_output("db_sqlite_to_csv", "sqlite3", cmd, TOOL_DEADLINE_SECS)?;

    if output.status.success() {
        let csv = normalize_csv_line_ends(&String::from_utf8_lossy(&output.stdout));
        if let Some(path) = output_path {
            crate::tx::snapshot(&path);
            // The journal step names the file written, not the database read.
            crate::journal::record_file_once("db_sqlite_to_csv", &path);
            write_file_atomically("db_sqlite_to_csv", &path, csv.as_bytes())?;
            return Ok(Value::Str(path));
        }
        return Ok(Value::Str(csv));
    }
    Err(crate::safety::tool_failed(
        "db_sqlite_to_csv",
        "sqlite3",
        output.status.code(),
        &String::from_utf8_lossy(&output.stderr),
    ))
}

fn bi_db_kv_get(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let store_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => ".ironshell_kv.db".to_string(),
    };
    let key = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_kv_get",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // A store that does not exist yet holds no value; asking must not
    // create one.
    if !sqlite_db_exists(&store_path) {
        return Ok(Value::Null);
    }
    bi_db_sqlite_query(
        vec![
            Value::Str(store_path),
            Value::Str(format!(
                "SELECT value FROM kv WHERE key = {}",
                crate::safety::sql_literal("db_kv_get", &key)?
            )),
        ],
        None,
    )
    .map(|v| match v {
        Value::Array(arr) if !arr.is_empty() => {
            if let Value::Record(rec) = &arr[0] {
                rec.get("value").cloned().unwrap_or(Value::Null)
            } else {
                Value::Null
            }
        }
        _ => Value::Null,
    })
}

fn bi_db_kv_set(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let store_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_kv_set",
                "store: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let key = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_kv_set",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let value = match args.get(2) {
        Some(Value::Str(s)) => s.clone(),
        Some(v) => format!("{:?}", v),
        other => {
            return Err(crate::safety::bad_arg(
                "db_kv_set",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // Validate literals before any file can be created or changed.
    let query = format!(
        "INSERT OR REPLACE INTO kv (key, value) VALUES ({}, {})",
        crate::safety::sql_literal("db_kv_set", &key)?,
        crate::safety::sql_literal("db_kv_set", &value)?
    );
    // Ensure table exists, propagating its failure.
    sqlite_exec_contained(vec![
        Value::Str(store_path.clone()),
        Value::Str("CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT)".to_string()),
    ])?;

    sqlite_exec_contained(vec![Value::Str(store_path), Value::Str(query)])
}

fn bi_db_kv_delete(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let store_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_kv_delete",
                "store: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let key = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_kv_delete",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "db_kv_delete",
        effect: crate::safety::Effect::Destructive,
        what: "db_delete",
        targets: vec![format!("{}:{}", store_path, key)],
        blast_radius: serde_json::json!({ "store": store_path.clone(), "key": key.clone() }),
        reversible: false,
        fs_paths: false,
    })?;

    sqlite_exec_contained(vec![
        Value::Str(store_path),
        Value::Str(format!(
            "DELETE FROM kv WHERE key = {}",
            crate::safety::sql_literal("db_kv_delete", &key)?
        )),
    ])
}

fn bi_db_kv_keys(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let store_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => ".ironshell_kv.db".to_string(),
    };

    if !sqlite_db_exists(&store_path) {
        return Ok(Value::Array(vec![]));
    }
    bi_db_sqlite_query(
        vec![
            Value::Str(store_path),
            Value::Str("SELECT key FROM kv".to_string()),
        ],
        None,
    )
    .map(|v| match v {
        Value::Array(arr) => Value::Array(
            arr.iter()
                .filter_map(|r| match r {
                    Value::Record(rec) => rec.get("key").cloned(),
                    _ => None,
                })
                .collect(),
        ),
        _ => Value::Array(vec![]),
    })
}

/// Deadline for one `db_json_query` run of jq over a file.
const DB_JQ_DEADLINE_SECS: u64 = 30;
/// The most output one `db_json_query` may produce. More is E_BUDGET_EXCEEDED.
const DB_JQ_MAX_OUTPUT: usize = 16 * 1024 * 1024;

fn bi_db_json_query(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let json_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_json_query",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let jq_filter = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => ".".to_string(),
    };
    // Both go to jq positionally, so a leading `-` would be read as an option.
    crate::safety::reject_option_like("db_json_query", &[json_path.clone(), jq_filter.clone()])?;

    // jq reads the file itself and gets no stdin, so nothing is written to it
    // here. The run has a deadline and an output cap like every other tool run.
    let output = run_output(
        "db_json_query",
        "jq",
        "jq",
        &[jq_filter.as_str(), json_path.as_str()],
        |_| {},
        None,
        DB_JQ_DEADLINE_SECS,
        DB_JQ_MAX_OUTPUT,
    )?;

    if output.status.success() {
        let json_str = String::from_utf8_lossy(&output.stdout);
        if let Ok(json) = serde_json::from_str::<serde_json::Value>(&json_str) {
            return Ok(json_to_value(json));
        }
        return Ok(Value::Str(json_str.trim().to_string()));
    }

    // This "fell back" to reading the file and returning all of it, so a
    // filter jq rejected answered with the whole document, filter ignored.
    Err(crate::safety::tool_failed(
        "db_json_query",
        "jq",
        output.status.code(),
        &String::from_utf8_lossy(&output.stderr),
    ))
}

fn bi_db_csv_query(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let csv_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_csv_query",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    let content = read_text_capped("db_csv_query", &csv_path)?;
    let mut reader = csv::ReaderBuilder::new()
        .trim(csv::Trim::All)
        .from_reader(content.as_bytes());
    let csv_error = |e: csv::Error| {
        crate::safety::bad_arg("db_csv_query", "CSV with equal-length rows", &e.to_string())
    };
    let headers = reader.headers().map_err(csv_error)?.clone();
    // A repeated header would let the later column replace the earlier one.
    let names: Vec<String> = headers.iter().map(str::to_string).collect();
    check_csv_headers("db_csv_query", &names)?;
    let rows = reader
        .records()
        .map(|record| {
            let record = record.map_err(csv_error)?;
            Ok(Value::Record(
                headers
                    .iter()
                    .zip(record.iter())
                    .map(|(header, value)| (header.to_string(), Value::Str(value.to_string())))
                    .collect(),
            ))
        })
        .collect::<Result<Vec<_>>>()?;

    Ok(Value::Array(rows))
}

fn bi_db_json_to_csv(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Every failure here answered "": invalid JSON, a non-array, a first row
    // that was not a record. Worse, cells that were not strings were written
    // with Rust's Debug format, so 5 became `Int(5)`; columns came from the
    // first record only, so a field first seen later was dropped; and a row
    // that was not a record was skipped.
    const B: &str = "db_json_to_csv";
    let rows = match args.first() {
        Some(Value::Array(arr)) => arr.clone(),
        Some(Value::Str(s)) => {
            let json = serde_json::from_str::<serde_json::Value>(s)
                .map_err(|e| crate::safety::bad_arg(B, "valid JSON", &e.to_string()))?;
            match json_to_value(json) {
                Value::Array(arr) => arr,
                other => {
                    return Err(crate::safety::bad_arg(
                        B,
                        "a JSON array of objects",
                        other.type_name(),
                    ))
                }
            }
        }
        other => {
            return Err(crate::safety::bad_arg(
                B,
                "an array of records, or its JSON text",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    if rows.is_empty() {
        return Ok(Value::Str(String::new()));
    }

    let mut headers = std::collections::BTreeSet::new();
    for row in &rows {
        match row {
            Value::Record(rec) => headers.extend(rec.keys().cloned()),
            other => {
                return Err(crate::safety::bad_arg(
                    B,
                    "every row a record",
                    other.type_name(),
                ))
            }
        }
    }
    let headers: Vec<String> = headers.into_iter().collect();

    fn cell(v: Option<&Value>) -> String {
        let raw = match v {
            None | Some(Value::Null) => return String::new(),
            Some(Value::Str(s)) => s.clone(),
            Some(v @ (Value::Int(_) | Value::Float(_) | Value::Bool(_))) => v.to_display_string(),
            Some(other) => value_to_json(other.clone()).to_string(),
        };
        if raw.contains([',', '"', '\n', '\r']) {
            format!("\"{}\"", raw.replace('"', "\"\""))
        } else {
            raw
        }
    }

    let mut csv = headers
        .iter()
        .map(|h| cell(Some(&Value::Str(h.clone()))))
        .collect::<Vec<_>>()
        .join(",");
    csv.push('\n');
    for row in &rows {
        let Value::Record(rec) = row else {
            unreachable!("checked above")
        };
        let line: Vec<String> = headers.iter().map(|h| cell(rec.get(h))).collect();
        csv.push_str(&line.join(","));
        csv.push('\n');
    }
    Ok(Value::Str(csv))
}

fn bi_db_csv_to_json(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_db_csv_query(args, None)
}

// ============================================================================
// Missing Clipboard & Input implementations
// ============================================================================

/// Most image data `clipboard_get_image` returns or `clipboard_set_image` copies.
const CLIPBOARD_IMAGE_MAX: usize = 32 * 1024 * 1024;
/// The image types the clipboard image builtins carry, in the order
/// `clipboard_get_image` prefers them.
#[cfg(target_os = "linux")]
const CLIPBOARD_IMAGE_TYPES: [&str; 5] = [
    "image/png",
    "image/jpeg",
    "image/gif",
    "image/bmp",
    "image/webp",
];

/// The MIME type of an image, from its first bytes, if it is one the
/// clipboard image builtins carry.
fn image_mime_of(bytes: &[u8]) -> Option<&'static str> {
    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
        Some("image/png")
    } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
        Some("image/jpeg")
    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
        Some("image/gif")
    } else if bytes.starts_with(b"BM") && bytes.len() > 14 {
        Some("image/bmp")
    } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
        Some("image/webp")
    } else {
        None
    }
}

/// The targets (X11) or MIME types (Wayland) the Linux clipboard offers, one
/// per entry; empty when nothing owns the clipboard. With no display it is
/// E_NO_UI. xsel cannot list targets or carry images, so only xclip serves
/// X11 here.
#[cfg(target_os = "linux")]
fn linux_clipboard_offers(name: &str) -> Result<Vec<String>> {
    if !display_env_set("DISPLAY") && !display_env_set("WAYLAND_DISPLAY") {
        return Err(crate::safety::no_ui(name));
    }
    let lines = |out: &std::process::Output| {
        String::from_utf8_lossy(&out.stdout)
            .lines()
            .map(|l| l.trim().to_string())
            .filter(|l| !l.is_empty())
            .collect::<Vec<_>>()
    };
    if display_env_set("WAYLAND_DISPLAY") {
        let out = linux_clipboard_tool(name, "wl-paste", &["--list-types"])?.ok_or_else(|| {
            crate::safety::tool_missing(
                name,
                "wl-paste",
                "install wl-clipboard to use clipboard images",
            )
        })?;
        if out.status.success() {
            return Ok(lines(&out));
        }
        if out.status.code() == Some(1)
            && String::from_utf8_lossy(&out.stderr).contains("Nothing is copied")
        {
            return Ok(Vec::new());
        }
        return Err(crate::safety::tool_failed(
            name,
            "wl-paste",
            out.status.code(),
            &gui_stderr_tail(&out),
        ));
    }
    let out = linux_clipboard_tool(
        name,
        "xclip",
        &["-selection", "clipboard", "-o", "-t", "TARGETS"],
    )?
    .ok_or_else(|| {
        crate::safety::tool_missing(
            name,
            "xclip",
            "install xclip to use clipboard images; xsel cannot carry them",
        )
    })?;
    if out.status.success() {
        return Ok(lines(&out));
    }
    if String::from_utf8_lossy(&out.stderr).contains("not available") {
        return Ok(Vec::new());
    }
    Err(crate::safety::tool_failed(
        name,
        "xclip",
        out.status.code(),
        &gui_stderr_tail(&out),
    ))
}

/// The Record `clipboard_get_image` answers with, from the image bytes a
/// platform clipboard gave. The refusals are the same on every OS: over
/// `CLIPBOARD_IMAGE_MAX` is E_BUDGET_EXCEEDED, and no data is E_NOT_FOUND.
#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
fn clipboard_image_answer(name: &str, mime: &str, bytes: &[u8]) -> Result<Value> {
    if bytes.len() > CLIPBOARD_IMAGE_MAX {
        return Err(crate::safety::budget_exceeded(
            name,
            format!(
                "the clipboard image is {} bytes, over the {CLIPBOARD_IMAGE_MAX}-byte limit",
                bytes.len()
            ),
            "copy a smaller image; this shell returns no truncated image",
        ));
    }
    if bytes.is_empty() {
        return Err(crate::safety::not_found(
            name,
            "image on the clipboard",
            "the clipboard offered an image but gave no data; copy it again",
        ));
    }
    use base64::Engine;
    let mut rec = BTreeMap::new();
    rec.insert("mime".to_string(), Value::Str(mime.to_string()));
    rec.insert("bytes".to_string(), Value::Int(bytes.len() as i64));
    rec.insert(
        "base64".to_string(),
        Value::Str(base64::engine::general_purpose::STANDARD.encode(bytes)),
    );
    Ok(Value::Record(rec))
}

/// The image `clipboard_get_image` refuses with E_NOT_FOUND when the clipboard
/// holds none. Shared by every platform so the code and text match.
#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
fn no_clipboard_image(name: &str) -> anyhow::Error {
    crate::safety::not_found(
        name,
        "image on the clipboard",
        "the clipboard holds no PNG, JPEG, GIF, BMP or WEBP image",
    )
}

/// The PowerShell script `clipboard_get_image` runs on Windows, under -STA (the
/// Clipboard class needs a single-threaded apartment). It writes `NONE` when
/// the clipboard holds no image, `OVER` when the PNG is past the cap (checked
/// before it is turned into text, so a huge image is never encoded), and
/// otherwise the PNG as base64 on stdout. Nothing is interpolated: the script
/// is fixed, and LIMIT is replaced by the number of CLIPBOARD_IMAGE_MAX.
#[cfg(target_os = "windows")]
const WINDOWS_IMAGE_GET_SCRIPT: &str = r#"$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
$img = $null
$done = $false
for ($try = 0; $try -lt 10 -and -not $done; $try++) {
    try {
        if ([System.Windows.Forms.Clipboard]::ContainsImage()) { $img = [System.Windows.Forms.Clipboard]::GetImage() }
        $done = $true
    } catch { Start-Sleep -Milliseconds 100 }
}
if (-not $done) { throw 'the clipboard stayed busy' }
if ($null -eq $img) {
    'NONE'
} else {
    $png = New-Object System.IO.MemoryStream
    $img.Save($png, [System.Drawing.Imaging.ImageFormat]::Png)
    if ($png.Length -gt LIMIT) { 'OVER' } else { [Convert]::ToBase64String($png.ToArray()) }
}"#;

/// The PowerShell script `clipboard_set_image` runs on Windows, under -STA. The
/// image arrives on stdin, never in the script text. It is copied as a bitmap
/// and as PNG, and flushed with copy=true so it outlives this process.
#[cfg(target_os = "windows")]
const WINDOWS_IMAGE_SET_SCRIPT: &str = r#"$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
$in = New-Object System.IO.MemoryStream
[Console]::OpenStandardInput().CopyTo($in)
$in.Position = 0
$src = [System.Drawing.Image]::FromStream($in)
$bmp = New-Object System.Drawing.Bitmap $src
$src.Dispose()
$png = New-Object System.IO.MemoryStream
$bmp.Save($png, [System.Drawing.Imaging.ImageFormat]::Png)
$pngBytes = $png.ToArray()
$data = New-Object System.Windows.Forms.DataObject
$data.SetData([System.Windows.Forms.DataFormats]::Bitmap, $bmp)
$data.SetData('PNG', $false, [System.IO.MemoryStream]::new($pngBytes))
$done = $false
for ($try = 0; $try -lt 10 -and -not $done; $try++) {
    try { [System.Windows.Forms.Clipboard]::SetDataObject($data, $true); $done = $true }
    catch { Start-Sleep -Milliseconds 100 }
}
if (-not $done) { throw 'the clipboard stayed busy' }"#;

/// `clipboard_get_image` on Windows: the PNG the script copies out of the
/// clipboard, through the shared answer.
#[cfg(target_os = "windows")]
fn windows_clipboard_image(name: &str) -> Result<Value> {
    use base64::Engine;
    let script = WINDOWS_IMAGE_GET_SCRIPT.replace("LIMIT", &CLIPBOARD_IMAGE_MAX.to_string());
    let mut cmd = crate::safety::child_command("powershell");
    cmd.args([
        "-NoProfile",
        "-NonInteractive",
        "-STA",
        "-Command",
        script.as_str(),
    ]);
    let output = bounded_cmd_output(name, "powershell", cmd, TOOL_DEADLINE_SECS)?;
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            name,
            "powershell",
            output.status.code(),
            &gui_stderr_tail(&output),
        ));
    }
    let answer = String::from_utf8_lossy(&output.stdout);
    match answer.trim() {
        "NONE" => Err(no_clipboard_image(name)),
        "OVER" => Err(crate::safety::budget_exceeded(
            name,
            format!("the clipboard image is over the {CLIPBOARD_IMAGE_MAX}-byte limit"),
            "copy a smaller image; this shell returns no truncated image",
        )),
        encoded => {
            let bytes = base64::engine::general_purpose::STANDARD
                .decode(encoded)
                .map_err(|e| {
                    crate::safety::tool_failed(
                        name,
                        "powershell",
                        Some(0),
                        &format!("its answer was not base64: {e}"),
                    )
                })?;
            clipboard_image_answer(name, "image/png", &bytes)
        }
    }
}

/// `clipboard_set_image` on Windows: the validated image bytes go to the script
/// on stdin. The script's own failure is the tool's failure.
#[cfg(target_os = "windows")]
fn windows_clipboard_set_image(name: &str, bytes: Vec<u8>) -> Result<()> {
    let args = [
        "-NoProfile",
        "-NonInteractive",
        "-STA",
        "-Command",
        WINDOWS_IMAGE_SET_SCRIPT,
    ];
    let output = run_output(
        name,
        "powershell",
        "powershell",
        &args,
        |_| {},
        Some(bytes),
        TOOL_DEADLINE_SECS,
        64 * 1024,
    )?;
    if output.status.success() {
        return Ok(());
    }
    Err(crate::safety::tool_failed(
        name,
        "powershell",
        output.status.code(),
        &gui_stderr_tail(&output),
    ))
}

/// The AppleScript `clipboard_get_image` runs on macOS, with the output path as
/// its one argument. A clipboard with no PNG class (error -1700) answers NONE;
/// any other error is reported as the failure it is. OK means the PNG is in the
/// file. AppleScript cannot measure PNG data (`length of` it is error -1728), so
/// the size is checked from the file before it is read.
#[cfg(target_os = "macos")]
const MACOS_IMAGE_GET_SCRIPT: &str = r#"on run argv
	set outPath to item 1 of argv
	try
		set pngData to the clipboard as «class PNGf»
	on error errMsg number errNum
		if errNum = -1700 then return "NONE"
		error errMsg number errNum
	end try
	set fh to open for access (POSIX file outPath) with write permission
	try
		set eof of fh to 0
		write pngData to fh
		close access fh
	on error errMsg number errNum
		try
			close access fh
		end try
		error errMsg number errNum
	end try
	return "OK"
end run"#;

/// The AppleScript `clipboard_set_image` runs on macOS. Arguments: the absolute
/// image path, then its kind (png, jpeg, gif or bmp), which picks the AppleScript
/// class the file is read as.
#[cfg(target_os = "macos")]
const MACOS_IMAGE_SET_SCRIPT: &str = r#"on run argv
	set inPath to item 1 of argv
	set imageKind to item 2 of argv
	if imageKind = "png" then
		set imageData to read (POSIX file inPath) as «class PNGf»
	else if imageKind = "jpeg" then
		set imageData to read (POSIX file inPath) as «class JPEG»
	else if imageKind = "gif" then
		set imageData to read (POSIX file inPath) as «class GIFf»
	else
		set imageData to read (POSIX file inPath) as «class BMPf»
	end if
	set the clipboard to imageData
	return "OK"
end run"#;

/// `clipboard_get_image` on macOS: osascript writes the clipboard's PNG to a
/// fresh file under the temp dir, which is read back and removed on every path.
#[cfg(target_os = "macos")]
fn macos_clipboard_image(name: &str) -> Result<Value> {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let path =
        std::env::temp_dir().join(format!("ae-clip-image-{}-{nanos}.png", std::process::id()));
    let outcome = macos_clipboard_image_to(name, &path);
    let _ = std::fs::remove_file(&path);
    outcome
}

#[cfg(target_os = "macos")]
fn macos_clipboard_image_to(name: &str, path: &std::path::Path) -> Result<Value> {
    let mut cmd = crate::safety::child_command("osascript");
    cmd.arg("-e").arg(MACOS_IMAGE_GET_SCRIPT).arg(path);
    let output = bounded_cmd_output(name, "osascript", cmd, TOOL_DEADLINE_SECS)?;
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            name,
            "osascript",
            output.status.code(),
            &gui_stderr_tail(&output),
        ));
    }
    match String::from_utf8_lossy(&output.stdout).trim() {
        "NONE" => Err(no_clipboard_image(name)),
        "OK" => {
            let size = std::fs::metadata(path)
                .map_err(|e| crate::safety::fs_error(name, path, &e))?
                .len();
            if size > CLIPBOARD_IMAGE_MAX as u64 {
                return Err(crate::safety::budget_exceeded(
                    name,
                    format!("the clipboard image is over the {CLIPBOARD_IMAGE_MAX}-byte limit"),
                    "copy a smaller image; this shell returns no truncated image",
                ));
            }
            let bytes = std::fs::read(path).map_err(|e| crate::safety::fs_error(name, path, &e))?;
            clipboard_image_answer(name, "image/png", &bytes)
        }
        other => Err(crate::safety::tool_failed(
            name,
            "osascript",
            Some(0),
            &format!("it answered {other:?}, not a clipboard image"),
        )),
    }
}

/// `clipboard_set_image` on macOS. WEBP has no AppleScript class on macOS, so
/// it is refused before the clipboard is touched.
#[cfg(target_os = "macos")]
fn macos_clipboard_set_image(name: &str, mime: &str, path: &std::path::Path) -> Result<()> {
    let kind = match mime {
        "image/png" => "png",
        "image/jpeg" => "jpeg",
        "image/gif" => "gif",
        "image/bmp" => "bmp",
        _ => {
            return Err(crate::safety::unimplemented(
                name,
                "the macOS clipboard has no WEBP class, so this image was NOT COPIED",
                "convert the image to PNG, JPEG, GIF or BMP",
            ))
        }
    };
    // osascript takes the path as an argument; an absolute one never starts
    // with "-", so it cannot be read as an option.
    let absolute =
        std::fs::canonicalize(path).map_err(|e| crate::safety::fs_error(name, path, &e))?;
    let mut cmd = crate::safety::child_command("osascript");
    cmd.arg("-e")
        .arg(MACOS_IMAGE_SET_SCRIPT)
        .arg(&absolute)
        .arg(kind);
    let output = bounded_cmd_output(name, "osascript", cmd, TOOL_DEADLINE_SECS)?;
    if output.status.success() {
        return Ok(());
    }
    Err(crate::safety::tool_failed(
        name,
        "osascript",
        output.status.code(),
        &gui_stderr_tail(&output),
    ))
}

fn bi_clipboard_get_image(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "clipboard_get_image";
    no_args_or_input(NAME, &args, &input)?;
    crate::safety::clipboard_read_gate(NAME)?;
    #[cfg(target_os = "windows")]
    {
        windows_clipboard_image(NAME)
    }
    #[cfg(target_os = "macos")]
    {
        macos_clipboard_image(NAME)
    }
    #[cfg(target_os = "linux")]
    {
        let offers = linux_clipboard_offers(NAME)?;
        let Some(mime) = CLIPBOARD_IMAGE_TYPES
            .iter()
            .find(|t| offers.iter().any(|o| o.eq_ignore_ascii_case(t)))
        else {
            return Err(no_clipboard_image(NAME));
        };
        let (tool, read_args): (&str, Vec<&str>) = if display_env_set("WAYLAND_DISPLAY") {
            ("wl-paste", vec!["--no-newline", "--type", mime])
        } else {
            ("xclip", vec!["-selection", "clipboard", "-o", "-t", mime])
        };
        let out = linux_clipboard_tool(NAME, tool, &read_args)?.ok_or_else(|| {
            crate::safety::tool_missing(NAME, tool, "install it to read clipboard images")
        })?;
        if !out.status.success() {
            return Err(crate::safety::tool_failed(
                NAME,
                tool,
                out.status.code(),
                &gui_stderr_tail(&out),
            ));
        }
        clipboard_image_answer(NAME, mime, &out.stdout)
    }
    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "reading an image from the clipboard is implemented on Windows, macOS and Linux only; NOTHING WAS READ",
            "use a platform clipboard tool",
        ))
    }
}

/// Copy an image file to the clipboard. The argument, the file and its type
/// are checked before the display, so every refusal but E_NO_UI is the same
/// on every OS.
fn bi_clipboard_set_image(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "clipboard_set_image";
    refuse_piped_input(NAME, &input)?;
    let path = gui_text(
        NAME,
        "image path",
        gui_required(NAME, &args, 0, "an image path")?,
        GUI_FIELD_MAX_BYTES,
        false,
    )?;
    if args.len() > 1 {
        return Err(crate::safety::bad_arg(
            NAME,
            "one argument: the image path",
            &format!("{} arguments", args.len()),
        ));
    }
    if !std::path::Path::new(&path).exists() {
        return Err(crate::safety::not_found(NAME, "image file", &path));
    }
    let validated = validate_read_path(&path)?;
    let size = fs::metadata(&validated)
        .map_err(|e| crate::safety::fs_error(NAME, &path, &e))?
        .len();
    if size > CLIPBOARD_IMAGE_MAX as u64 {
        return Err(crate::safety::budget_exceeded(
            NAME,
            format!("{path} is {size} bytes, over the {CLIPBOARD_IMAGE_MAX}-byte limit"),
            "copy a smaller image",
        ));
    }
    let bytes = read_bytes_capped(NAME, &validated)?;
    let Some(mime) = image_mime_of(&bytes) else {
        return Err(crate::safety::bad_arg(
            NAME,
            "a PNG, JPEG, GIF, BMP or WEBP image",
            &format!("{path}, which is none of those"),
        ));
    };
    #[cfg(target_os = "linux")]
    {
        linux_clipboard_set_image(NAME, mime, bytes)?;
        Ok(Value::Bool(true))
    }
    #[cfg(target_os = "windows")]
    {
        let _ = mime;
        windows_clipboard_set_image(NAME, bytes)?;
        Ok(Value::Bool(true))
    }
    #[cfg(target_os = "macos")]
    {
        macos_clipboard_set_image(NAME, mime, &validated)?;
        Ok(Value::Bool(true))
    }
    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
    {
        let _ = (mime, bytes, validated);
        Err(crate::safety::unimplemented(
            NAME,
            "writing an image to the clipboard is implemented on Windows, macOS and Linux only; NOTHING WAS COPIED",
            "use a platform clipboard tool",
        ))
    }
}

/// Hand `input` to a clipboard helper on its stdin and wait for it, with a
/// deadline. `child` must have been spawned with a piped stdin. Its stdout and
/// stderr are left however the caller set them and are never read here: a
/// clipboard holder forked by xclip keeps the inherited handles open, so
/// waiting on them would wait for the holder as well.
///
/// The write runs on its own thread and the pipe is closed when it finishes,
/// so a helper that stops reading cannot block the caller. Past `deadline_secs`
/// the child is killed and reaped, and the call is a coded budget error. A
/// BrokenPipe means the helper exited before reading everything. That is not an
/// error here: the exit status decides, and the caller judges it as before.
/// Any other write failure is a coded tool error.
#[cfg(any(target_os = "macos", target_os = "linux", test))]
fn feed_stdin_and_wait(
    builtin: &str,
    tool: &str,
    mut child: std::process::Child,
    input: Vec<u8>,
    deadline_secs: u64,
) -> Result<std::process::ExitStatus> {
    use std::io::Write;
    use std::sync::mpsc;
    use std::time::{Duration, Instant};
    let Some(mut stdin) = child.stdin.take() else {
        let _ = child.kill();
        let _ = child.wait();
        return Err(crate::safety::tool_failed(
            builtin,
            tool,
            None,
            "its stdin was not piped",
        ));
    };
    let (tx, rx) = mpsc::channel::<std::io::Result<()>>();
    std::thread::spawn(move || {
        let written = stdin.write_all(&input);
        // Dropping the pipe here is what lets the helper see end of input.
        drop(stdin);
        let _ = tx.send(written);
    });
    let deadline = Instant::now() + Duration::from_secs(deadline_secs);
    let mut write: Option<std::io::Result<()>> = None;
    let status = loop {
        if write.is_none() {
            write = rx.try_recv().ok();
        }
        if let Some(Err(e)) = &write {
            if e.kind() != std::io::ErrorKind::BrokenPipe {
                let message = format!("writing its input failed: {e}");
                let _ = child.kill();
                let _ = child.wait();
                return Err(crate::safety::tool_failed(builtin, tool, None, &message));
            }
        }
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if Instant::now() < deadline => {
                std::thread::sleep(Duration::from_millis(20));
            }
            Ok(None) => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(crate::safety::budget_exceeded(
                    builtin,
                    format!("`{tool}` did not finish within {deadline_secs} s and was stopped"),
                    "the clipboard may be unchanged; check it, then retry",
                ));
            }
            Err(e) => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(crate::safety::tool_failed(
                    builtin,
                    tool,
                    None,
                    &e.to_string(),
                ));
            }
        }
    };
    if write.is_none() {
        // The helper has exited; the write has at most a moment left to report.
        write = rx.recv_timeout(Duration::from_millis(200)).ok();
    }
    match write {
        Some(Err(e)) if e.kind() != std::io::ErrorKind::BrokenPipe => {
            Err(crate::safety::tool_failed(
                builtin,
                tool,
                None,
                &format!("writing its input failed: {e}"),
            ))
        }
        _ => Ok(status),
    }
}

/// Hand `bytes` to xclip or wl-copy as `mime`.
///
/// Not through bounded_cmd_output or run_tree, on purpose. Both tools fork a
/// holder that owns the selection after the command returns, and run_tree puts
/// its child in a new process group and kills that group when a pipe outlives
/// the child: it would kill the holder and empty the clipboard again. So the
/// tool keeps this shell's process group, gets null stdout and stderr (the
/// holder keeps no pipe of ours), and only the direct child is waited on, with
/// a deadline, through feed_stdin_and_wait.
#[cfg(target_os = "linux")]
fn linux_clipboard_set_image(name: &str, mime: &str, bytes: Vec<u8>) -> Result<()> {
    use std::process::Stdio;
    if !display_env_set("DISPLAY") && !display_env_set("WAYLAND_DISPLAY") {
        return Err(crate::safety::no_ui(name));
    }
    let (tool, tool_args): (&str, Vec<&str>) = if display_env_set("WAYLAND_DISPLAY") {
        ("wl-copy", vec!["--type", mime])
    } else {
        ("xclip", vec!["-selection", "clipboard", "-t", mime, "-i"])
    };
    let mut clip = crate::safety::child_command(tool);
    crate::safety::strip_ironshell_env(&mut clip);
    let child = clip
        .args(&tool_args)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| crate::safety::spawn_error(name, tool, &e))?;
    let status = feed_stdin_and_wait(name, tool, child, bytes, TOOL_DEADLINE_SECS)?;
    if status.success() {
        return Ok(());
    }
    Err(crate::safety::tool_failed(
        name,
        tool,
        status.code(),
        "it did not take the image",
    ))
}

fn bi_clipboard_history(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "clipboard_history";
    no_args_or_input(NAME, &args, &input)?;
    crate::safety::clipboard_read_gate(NAME)?;
    #[cfg(target_os = "windows")]
    {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-NoProfile",
            "-NonInteractive",
            "-Command",
            "Get-ClipboardHistory | Select-Object -First 10 | ForEach-Object { $_.Text }",
        ]);
        let output = bounded_cmd_output(NAME, "powershell", cmd, TOOL_DEADLINE_SECS)?;
        if !output.status.success() {
            // Previously answered a String explaining the requirement, which
            // read as a list of one entry. The requirement is an error.
            return Err(crate::safety::tool_failed(
                NAME,
                "Get-ClipboardHistory",
                output.status.code(),
                &gui_stderr_tail(&output),
            ));
        }
        let text = String::from_utf8_lossy(&output.stdout).into_owned();
        Ok(Value::Array(
            text.lines().map(|l| Value::Str(l.to_string())).collect(),
        ))
    }
    #[cfg(not(target_os = "windows"))]
    {
        Err(crate::safety::unimplemented(
            NAME,
            "clipboard history is implemented on Windows 10 and later only; NOTHING WAS READ",
            "clipboard() reads the current clipboard text",
        ))
    }
}

/// `input_read_char(timeout_ms?)`: one keypress from the terminal, answered as
/// a String. Needs stdin and stderr to be terminals; otherwise it refuses with
/// E_NO_UI without reading anything, so piped stdin is left for the next read.
/// Ctrl+C is refused (E_POLICY_DENY), not answered: raw mode delivers it as a
/// key, and answering it as a character would hide that the user cancelled.
fn bi_input_read_char(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const BUILTIN: &str = "input_read_char";
    const MAX_MS: i64 = 3_600_000;
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "no pipeline input",
            "a piped value",
        ));
    }
    let timeout = match args.as_slice() {
        [] => None,
        [Value::Int(ms)] if (1..=MAX_MS).contains(ms) => {
            Some(std::time::Duration::from_millis(*ms as u64))
        }
        [other] => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "an Int timeout_ms from 1 through 3600000",
                &format!("{other:?}"),
            ))
        }
        more => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "input_read_char(timeout_ms?: Int)",
                &format!("{} arguments", more.len()),
            ))
        }
    };
    use std::io::IsTerminal;
    if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal()) {
        return Err(crate::safety::no_ui(BUILTIN));
    }
    read_key_native(BUILTIN, timeout)
}

#[cfg(feature = "native")]
fn read_key_native(builtin: &str, timeout: Option<std::time::Duration>) -> Result<Value> {
    use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
    use crossterm::terminal;

    let io = |e: std::io::Error| crate::safety::fs_error(builtin, "the terminal", &e);

    // Same discipline as line_editor::terminal::read_line: raw mode is
    // restored on every path, including a failed read, before the result
    // is returned.
    terminal::enable_raw_mode().map_err(io)?;
    let outcome = (|| -> Result<Option<String>> {
        let deadline = timeout.map(|t| std::time::Instant::now() + t);
        loop {
            if let Some(deadline) = deadline {
                let remaining = deadline.saturating_duration_since(std::time::Instant::now());
                if remaining.is_zero() || !event::poll(remaining).map_err(io)? {
                    return Ok(None);
                }
            }
            let Event::Key(key) = event::read().map_err(io)? else {
                continue;
            };
            if key.kind != KeyEventKind::Press {
                continue;
            }
            if let KeyCode::Char('c' | 'C') = key.code {
                if key.modifiers.contains(KeyModifiers::CONTROL) {
                    return Err(crate::safety::policy_deny(
                        builtin,
                        format!(
                            "{builtin}: Ctrl+C was pressed; the key was cancelled, not answered"
                        ),
                        "the user cancelled this read; ask again only if they want to answer",
                    ));
                }
            }
            // Keys with no name here (modifier-only presses, media keys) are
            // skipped, so the answer is always a key an agent can match.
            if let Some(name) = key_name(key.code) {
                return Ok(Some(name));
            }
        }
    })();
    let restored = terminal::disable_raw_mode();
    let answer = outcome?;
    restored.map_err(io)?;
    Ok(answer.map_or(Value::Null, Value::Str))
}

#[cfg(feature = "native")]
fn key_name(code: crossterm::event::KeyCode) -> Option<String> {
    use crossterm::event::KeyCode;
    Some(match code {
        KeyCode::Char(c) => c.to_string(),
        KeyCode::Enter => "Enter".to_string(),
        KeyCode::Esc => "Esc".to_string(),
        KeyCode::Tab => "Tab".to_string(),
        KeyCode::BackTab => "BackTab".to_string(),
        KeyCode::Backspace => "Backspace".to_string(),
        KeyCode::Delete => "Delete".to_string(),
        KeyCode::Insert => "Insert".to_string(),
        KeyCode::Home => "Home".to_string(),
        KeyCode::End => "End".to_string(),
        KeyCode::PageUp => "PageUp".to_string(),
        KeyCode::PageDown => "PageDown".to_string(),
        KeyCode::Up => "Up".to_string(),
        KeyCode::Down => "Down".to_string(),
        KeyCode::Left => "Left".to_string(),
        KeyCode::Right => "Right".to_string(),
        KeyCode::F(n) => format!("F{n}"),
        _ => return None,
    })
}

#[cfg(not(feature = "native"))]
fn read_key_native(builtin: &str, timeout: Option<std::time::Duration>) -> Result<Value> {
    let _ = timeout;
    Err(crate::safety::unimplemented(
        builtin,
        "reading a keypress needs the `native` feature (crossterm); NOTHING WAS READ",
        "build with default features, or use `ish tui`",
    ))
}

/// `input_spinner(label, duration_ms)`: animates `| / - \` on stderr for
/// `duration_ms`, then clears its line and answers `{label, duration_ms}`.
/// When stderr is not a terminal nothing is drawn (no CR or escape bytes reach
/// a log), but the call still waits the full duration. Control characters in
/// the label are drawn as `?`; the answer carries the label unchanged.
fn bi_input_spinner(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const BUILTIN: &str = "input_spinner";
    const MAX_MS: i64 = 600_000;
    const MAX_LABEL_BYTES: usize = 1024;
    const FRAME_MS: u64 = 100;
    const FRAMES: [char; 4] = ['|', '/', '-', '\\'];
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "no pipeline input",
            "a piped value",
        ));
    }
    let [label, duration] = args.as_slice() else {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "input_spinner(label: String, duration_ms: Int)",
            &format!("{} arguments", args.len()),
        ));
    };
    let Value::Str(label) = label else {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "a String label",
            &format!("{label:?}"),
        ));
    };
    if label.len() > MAX_LABEL_BYTES {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "a label of at most 1024 bytes",
            &format!("{} bytes", label.len()),
        ));
    }
    let ms = match duration {
        Value::Int(ms) if (1..=MAX_MS).contains(ms) => *ms as u64,
        other => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "an Int duration_ms from 1 through 600000",
                &format!("{other:?}"),
            ))
        }
    };
    use std::io::IsTerminal;
    let draw = std::io::stderr().is_terminal();
    let shown: String = label
        .chars()
        .map(|c| if c.is_control() { '?' } else { c })
        .collect();
    let total = std::time::Duration::from_millis(ms);
    let start = std::time::Instant::now();
    let mut frame = 0usize;
    loop {
        let elapsed = start.elapsed();
        if elapsed >= total {
            break;
        }
        if draw {
            eprint!("\r{} {}", FRAMES[frame % FRAMES.len()], shown);
        }
        frame += 1;
        std::thread::sleep((total - elapsed).min(std::time::Duration::from_millis(FRAME_MS)));
    }
    if draw {
        eprint!("\r{}\r", " ".repeat(shown.chars().count() + 2));
    }
    let mut rec = std::collections::BTreeMap::new();
    rec.insert("label".to_string(), Value::Str(label.clone()));
    rec.insert("duration_ms".to_string(), Value::Int(ms as i64));
    Ok(Value::Record(rec))
}

/// `input_progress(current, total, label?)`: draws one progress line on stderr
/// and answers `{current, total, percent}`. Nothing is kept between calls.
fn bi_input_progress(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const BUILTIN: &str = "input_progress";
    const WIDTH: usize = 30;
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "no pipeline input",
            "a piped value",
        ));
    }
    if !(2..=3).contains(&args.len()) {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "input_progress(current: Number, total: Number, label?: String)",
            &format!("{} arguments", args.len()),
        ));
    }
    let number = |v: &Value, what: &str| -> Result<f64> {
        let n = match v {
            Value::Int(i) => *i as f64,
            Value::Float(f) => *f,
            other => {
                return Err(crate::safety::bad_arg(
                    BUILTIN,
                    &format!("a Number {what}"),
                    &format!("{other:?}"),
                ))
            }
        };
        if !n.is_finite() {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                &format!("a finite Number {what}"),
                &format!("{n}"),
            ));
        }
        Ok(n)
    };
    let current_value = &args[0];
    let total_value = &args[1];
    let current = number(current_value, "current")?;
    let total = number(total_value, "total")?;
    if total <= 0.0 {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "a total greater than 0",
            &format!("{total}"),
        ));
    }
    if current < 0.0 || current > total {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "0 <= current <= total",
            &format!("current {current} of total {total}"),
        ));
    }
    let label = match args.get(2) {
        None => None,
        Some(Value::Str(s)) => Some(s.as_str()),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "a String label",
                &format!("{other:?}"),
            ))
        }
    };
    let fraction = (current / total).clamp(0.0, 1.0);
    let percent = (fraction * 100.0).floor() as i64;
    let filled = ((fraction * WIDTH as f64).floor() as usize).min(WIDTH);
    let bar = format!("{}{}", "#".repeat(filled), "-".repeat(WIDTH - filled));
    let prefix = match label {
        Some(text) => format!("{text} "),
        None => String::new(),
    };
    let finished = current == total;
    eprint!("\r{prefix}[{bar}] {percent}%");
    if finished {
        eprintln!();
    }
    let mut record = std::collections::BTreeMap::new();
    record.insert("current".to_string(), current_value.clone());
    record.insert("total".to_string(), total_value.clone());
    record.insert("percent".to_string(), Value::Int(percent));
    Ok(Value::Record(record))
}

/// Most fields one `input_form` asks about.
const INPUT_FORM_MAX_FIELDS: usize = 50;
/// Longest label, default or choice text a line prompt accepts.
const INPUT_TEXT_MAX_BYTES: usize = 1024;
/// Invalid answers a line prompt tolerates before it refuses.
const INPUT_MAX_ATTEMPTS: usize = 3;
/// Most rows one `input_table` lists.
const INPUT_TABLE_MAX_ROWS: usize = 1000;
/// Columns one `input_table` shows; the chosen row still carries every key.
const INPUT_TABLE_MAX_COLUMNS: usize = 16;
/// Characters of one table cell shown before it is cut with `...`.
const INPUT_TABLE_CELL_CHARS: usize = 40;
/// Most choices one `input_autocomplete` accepts.
const INPUT_AUTOCOMPLETE_MAX_CHOICES: usize = 10000;
/// Matches one `input_autocomplete` lists when a prefix is ambiguous.
const INPUT_AUTOCOMPLETE_LIST: usize = 20;
/// Answers one `input_autocomplete` accepts before it refuses.
const INPUT_AUTOCOMPLETE_MAX_ATTEMPTS: usize = 5;

/// A form field name: `^[A-Za-z_][A-Za-z0-9_]{0,63}$`.
fn is_form_field_name(name: &str) -> bool {
    let bytes = name.as_bytes();
    matches!(bytes.first(), Some(b) if b.is_ascii_alphabetic() || *b == b'_')
        && bytes.len() <= 64
        && bytes
            .iter()
            .all(|b| b.is_ascii_alphanumeric() || *b == b'_')
}

/// One table cell or column title: control characters become spaces, and text
/// over the cell width is cut with `...`.
fn input_table_cell(text: &str) -> String {
    let flat: String = text
        .chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect();
    if flat.chars().count() <= INPUT_TABLE_CELL_CHARS {
        return flat;
    }
    let mut cut: String = flat.chars().take(INPUT_TABLE_CELL_CHARS - 3).collect();
    cut.push_str("...");
    cut
}

/// A form of named fields, asked one line each. Every field is validated
/// before the first prompt, so a malformed form asks nothing.
fn bi_input_form(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_form";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "a direct call; the answers come from the terminal, not piped input",
            "a piped value",
        ));
    }
    let [fields] = args.as_slice() else {
        return Err(crate::safety::bad_arg(
            NAME,
            "fields: Array of field Records",
            &format!("{} argument(s)", args.len()),
        ));
    };
    let Value::Array(specs) = fields else {
        return Err(crate::safety::bad_arg(
            NAME,
            "fields: Array of field Records",
            fields.type_name(),
        ));
    };
    if specs.is_empty() || specs.len() > INPUT_FORM_MAX_FIELDS {
        return Err(crate::safety::bad_arg(
            NAME,
            &format!("1..={INPUT_FORM_MAX_FIELDS} fields"),
            &format!("{} field(s)", specs.len()),
        ));
    }

    // (name, label, default, required), validated in full before any prompt.
    let mut checked: Vec<(String, String, Option<String>, bool)> = Vec::with_capacity(specs.len());
    let mut seen = std::collections::BTreeSet::new();
    for (i, spec) in specs.iter().enumerate() {
        let position = i + 1;
        let Value::Record(rec) = spec else {
            return Err(crate::safety::bad_arg(
                NAME,
                &format!("field {position}: a Record"),
                spec.type_name(),
            ));
        };
        if let Some(key) = rec
            .keys()
            .find(|k| !matches!(k.as_str(), "name" | "label" | "default" | "required"))
        {
            return Err(crate::safety::bad_arg(
                NAME,
                &format!("field {position}: keys name, label, default, required"),
                &format!("unknown key {key:?}"),
            ));
        }
        let name = match rec.get("name") {
            Some(Value::Str(s)) if is_form_field_name(s) => s.clone(),
            Some(Value::Str(s)) => {
                return Err(crate::safety::bad_arg(
                    NAME,
                    &format!("field {position}: name matching ^[A-Za-z_][A-Za-z0-9_]{{0,63}}$"),
                    &format!("{s:?}"),
                ))
            }
            Some(other) => {
                return Err(crate::safety::bad_arg(
                    NAME,
                    &format!("field {position}: name as a String"),
                    other.type_name(),
                ))
            }
            None => {
                return Err(crate::safety::bad_arg(
                    NAME,
                    &format!("field {position}: a name"),
                    "no name",
                ))
            }
        };
        if !seen.insert(name.clone()) {
            return Err(crate::safety::bad_arg(
                NAME,
                "field names that are unique",
                &format!("duplicate {name:?}"),
            ));
        }
        let text = |key: &str| -> Result<Option<String>> {
            match rec.get(key) {
                None => Ok(None),
                Some(Value::Str(s)) if s.len() <= INPUT_TEXT_MAX_BYTES => Ok(Some(s.clone())),
                Some(Value::Str(s)) => Err(crate::safety::bad_arg(
                    NAME,
                    &format!("field {position}: {key} of at most {INPUT_TEXT_MAX_BYTES} bytes"),
                    &format!("{} bytes", s.len()),
                )),
                Some(other) => Err(crate::safety::bad_arg(
                    NAME,
                    &format!("field {position}: {key} as a String"),
                    other.type_name(),
                )),
            }
        };
        let label = text("label")?
            .filter(|l| !l.is_empty())
            .unwrap_or_else(|| name.clone());
        let default = text("default")?;
        let required = match rec.get("required") {
            None => false,
            Some(Value::Bool(b)) => *b,
            Some(other) => {
                return Err(crate::safety::bad_arg(
                    NAME,
                    &format!("field {position}: required as a Bool"),
                    other.type_name(),
                ))
            }
        };
        checked.push((name, label, default, required));
    }

    let mut answers = BTreeMap::new();
    for (name, label, default, required) in &checked {
        let prompt = match default {
            Some(d) => format!("{label} ({d}): "),
            None => format!("{label}: "),
        };
        let mut empty_answers = 0usize;
        let answer = loop {
            let raw = read_answer(NAME, &prompt)?;
            if !raw.is_empty() {
                break raw;
            }
            if let Some(d) = default {
                break d.clone();
            }
            if !required {
                break String::new();
            }
            empty_answers += 1;
            if empty_answers == INPUT_MAX_ATTEMPTS {
                return Err(crate::safety::bad_arg(
                    NAME,
                    &format!("a non-empty answer for required field `{name}`"),
                    &format!("{empty_answers} empty answers"),
                ));
            }
            eprintln!("{NAME}: `{name}` is required");
        };
        answers.insert(name.clone(), Value::Str(answer));
    }
    Ok(Value::Record(answers))
}

/// Lists rows as a numbered table on stderr, then answers the row the user
/// picks, as it was given.
fn bi_input_table(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_table";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            NAME,
            "a direct call; the choice comes from the terminal, not piped input",
            "a piped value",
        ));
    }
    if args.is_empty() || args.len() > 2 {
        return Err(crate::safety::bad_arg(
            NAME,
            "rows: Array of Records, prompt?: String",
            &format!("{} argument(s)", args.len()),
        ));
    }
    let Value::Array(rows) = &args[0] else {
        return Err(crate::safety::bad_arg(
            NAME,
            "rows: Array of Records",
            args[0].type_name(),
        ));
    };
    let prompt = match args.get(1) {
        None => None,
        Some(Value::Str(p)) => Some(p.clone()),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "prompt: String",
                other.type_name(),
            ))
        }
    };
    if rows.is_empty() || rows.len() > INPUT_TABLE_MAX_ROWS {
        return Err(crate::safety::bad_arg(
            NAME,
            &format!("1..={INPUT_TABLE_MAX_ROWS} rows"),
            &format!("{} row(s)", rows.len()),
        ));
    }
    let mut columns = std::collections::BTreeSet::new();
    for (i, row) in rows.iter().enumerate() {
        let Value::Record(rec) = row else {
            return Err(crate::safety::bad_arg(
                NAME,
                &format!("row {}: a Record", i + 1),
                row.type_name(),
            ));
        };
        columns.extend(rec.keys().map(String::as_str));
    }

    let shown: Vec<&str> = columns
        .iter()
        .copied()
        .take(INPUT_TABLE_MAX_COLUMNS)
        .collect();
    let hidden = columns.len() - shown.len();
    let mut table = String::from("   #");
    for column in &shown {
        table.push_str(" | ");
        table.push_str(&input_table_cell(column));
    }
    if hidden > 0 {
        table.push_str(&format!(" | (+{hidden} more columns)"));
    }
    table.push('\n');
    for (i, row) in rows.iter().enumerate() {
        table.push_str(&format!("{:>4}", i + 1));
        if let Value::Record(rec) = row {
            for column in &shown {
                let cell = rec
                    .get(*column)
                    .map(|v| v.to_display_string())
                    .unwrap_or_default();
                table.push_str(" | ");
                table.push_str(&input_table_cell(&cell));
            }
        }
        table.push('\n');
    }
    eprint!("{table}");

    let question = prompt.unwrap_or_else(|| format!("Select a row (1-{}): ", rows.len()));
    for _ in 0..INPUT_MAX_ATTEMPTS {
        let answer = read_answer(NAME, &question)?;
        match answer.trim().parse::<usize>() {
            Ok(n) if (1..=rows.len()).contains(&n) => return Ok(rows[n - 1].clone()),
            _ => eprintln!(
                "{NAME}: {answer:?} is not a row number in 1..={}",
                rows.len()
            ),
        }
    }
    Err(crate::safety::bad_arg(
        NAME,
        &format!("a row number in 1..={}", rows.len()),
        &format!("no valid answer in {INPUT_MAX_ATTEMPTS} attempts"),
    ))
}

/// `input_date(prompt?)`: a `YYYY-MM-DD` date the calendar accepts, answered as
/// its text. Anything else is asked again; after the last attempt the call
/// refuses with E_BAD_ARG.
fn bi_input_date(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "input_date";
    direct_args(
        NAME,
        &args,
        input.is_some(),
        0,
        1,
        "input_date(prompt?: String)",
    )?;
    let prompt = optional_prompt(NAME, &args, "Enter date (YYYY-MM-DD): ")?;
    ask_until(NAME, &prompt, "a date as YYYY-MM-DD", |answer| {
        parse_date(answer.trim())
    })
    .map(Value::Str)
}

// ============================================================================
// Missing Crypto implementations
// ============================================================================

fn bi_crypto_cert_verify(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let cert_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "crypto_cert_verify",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    crate::safety::reject_option_like("crypto_cert_verify", std::slice::from_ref(&cert_path))?;
    crate::security::check_read_jail("crypto_cert_verify", &cert_path)?;
    // A certificate file that did not exist answered false, "invalid".
    if !std::path::Path::new(&cert_path).is_file() {
        return Err(crate::safety::not_found(
            "crypto_cert_verify",
            "certificate file",
            &cert_path,
        ));
    }
    // The same size limit as crypto_cert_info, checked before the file is read.
    let metadata = std::fs::metadata(&cert_path)
        .map_err(|e| crate::safety::fs_error("crypto_cert_verify", &cert_path, &e))?;
    if metadata.len() > 64 * 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            "crypto_cert_verify",
            "certificate input exceeds 64 MiB".into(),
            "verify a smaller file",
        ));
    }
    // A file that exists but cannot be read is a coded error, never false.
    let bytes = std::fs::read(&cert_path)
        .map_err(|e| crate::safety::fs_error("crypto_cert_verify", &cert_path, &e))?;
    // IronSocketLayer's X.509 chain validation against the system trust store.
    // Only a chain that does not validate is false; a missing trust store,
    // an unsupported key, or exceeded bounds are coded errors. See
    // src/certificates.rs.
    Ok(Value::Bool(crate::certificates::verify_file(
        "crypto_cert_verify",
        &bytes,
    )?))
}

fn bi_crypto_generate_key(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    bi_crypto_key_generate(args, input)
}

/// Signature verification returns a Bool only after structural input validation.
fn bi_crypto_verify_signature(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    digital_signatures::verify(args, input)
}

fn bi_crypto_jwt_decode(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let token = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "crypto_jwt_decode",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // The payload, decoded without verifying the signature. This shelled
    // out to `base64` (Unix) or PowerShell (Windows) and answered null for a
    // malformed token, a bad segment or a payload that was not JSON.
    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
    let bad = |why: &str| {
        crate::safety::bad_arg("crypto_jwt_decode", "a JWT (header.payload.signature)", why)
    };
    let parts: Vec<&str> = token.trim().split('.').collect();
    if parts.len() != 3 {
        return Err(bad(&format!("{} dot-separated segment(s)", parts.len())));
    }
    let bytes = URL_SAFE_NO_PAD
        .decode(parts[1].trim_end_matches('='))
        .map_err(|e| bad(&format!("a payload that is not base64url: {e}")))?;
    let json: serde_json::Value = serde_json::from_slice(&bytes)
        .map_err(|e| bad(&format!("a payload that is not JSON: {e}")))?;
    Ok(json_to_value(json))
}

// ============================================================================
// Missing Database implementations
// ============================================================================

fn bi_db_sqlite_open(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Just verify the database can be opened
    bi_db_sqlite_create(args, None)
}

/// Render one `Value` as a SQL literal.
///
/// Strings go through [`crate::safety::sql_literal`] rather than a local
/// `replace('\'', "''")`. The two agree on doubling quotes, but the helper also
/// refuses an interior NUL — the sqlite3 CLI reads its SQL as a C string, so a
/// NUL silently truncates the statement, and storing a shortened value is its own
/// bug. Two call sites had hand-rolled the escaping and inherited neither that
/// check nor any later fix to it.
fn sql_value(builtin: &str, v: &Value) -> Result<String> {
    Ok(match v {
        Value::Str(s) => crate::safety::sql_literal(builtin, s)?,
        Value::Int(n) => n.to_string(),
        Value::Float(f) if f.is_finite() => f.to_string(),
        Value::Bool(b) => if *b { "1" } else { "0" }.to_string(),
        Value::Null => "NULL".to_string(),
        other => {
            return Err(crate::safety::bad_arg(
                builtin,
                "String, Int, finite Float, Bool or Null SQL cell",
                other.type_name(),
            ))
        }
    })
}

fn bi_db_sqlite_insert(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_insert",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_insert",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let values = match args.get(2) {
        Some(Value::Record(r)) => r.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_insert",
                "Record",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    if values.is_empty() {
        return Err(crate::safety::arg_err(
            "db_sqlite_insert: values must be a nonempty Record",
        ));
    }

    // Column names are identifiers, and they come from a caller-supplied record,
    // so they are exactly as controlled as the values are. Escaping the values
    // and not the keys made the gap easier to miss, not smaller: a key of
    // `id) VALUES (1); DROP TABLE victim; --` closed the statement and the
    // sqlite3 CLI ran what followed.
    let columns: Vec<String> = values
        .keys()
        .map(|k| crate::safety::sql_identifier("db_sqlite_insert", k))
        .collect::<Result<_>>()?;
    let vals: Vec<String> = values
        .values()
        .map(|v| sql_value("db_sqlite_insert", v))
        .collect::<Result<_>>()?;

    let sql = format!(
        "INSERT INTO {} ({}) VALUES ({})",
        crate::safety::sql_identifier("db_sqlite_insert", &table)?,
        columns.join(", "),
        vals.join(", ")
    );
    sqlite_exec_contained_as(
        "db_sqlite_insert",
        vec![Value::Str(db_path), Value::Str(sql)],
    )
}

fn bi_db_sqlite_update(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_update",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_update",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let values = match args.get(2) {
        Some(Value::Record(r)) => r.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_update",
                "Record",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let where_clause = match args.get(3) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_update",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    if values.is_empty() || where_clause.trim().is_empty() {
        return Err(crate::safety::arg_err(
            "db_sqlite_update: values and WHERE clause must be nonempty",
        ));
    }
    crate::safety::reject_sql_batch("db_sqlite_update", &where_clause)?;

    // Same as `db_sqlite_insert`: the record's keys are identifiers and are
    // caller-controlled. The WHERE clause is SQL by contract -- this builtin
    // exists to take one -- so it stays the caller's, matching the note in
    // `db_sqlite_delete`.
    let sets: Vec<String> = values
        .iter()
        .map(|(k, v)| {
            Ok(format!(
                "{} = {}",
                crate::safety::sql_identifier("db_sqlite_update", k)?,
                sql_value("db_sqlite_update", v)?
            ))
        })
        .collect::<Result<_>>()?;

    let sql = format!(
        "UPDATE {} SET {} WHERE {}",
        crate::safety::sql_identifier("db_sqlite_update", &table)?,
        sets.join(", "),
        where_clause
    );
    sqlite_exec_contained_as(
        "db_sqlite_update",
        vec![Value::Str(db_path), Value::Str(sql)],
    )
}

fn bi_db_sqlite_delete(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_delete",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_delete",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    // Omitting the condition used to delete nothing and answer true. Neither
    // that nor deleting every row is what a caller who left it out meant, so a
    // missing or blank condition is refused, and the way to say "every row" is
    // written out.
    let where_clause = match args.get(2) {
        Some(Value::Str(s)) if !s.trim().is_empty() => s.clone(),
        None | Some(Value::Str(_)) => {
            return Err(crate::safety::bad_arg_in(
                "db_sqlite_delete",
                "db_sqlite_delete: a where clause is required; to delete every row pass where \"1=1\"",
                "pass the condition as the third argument, e.g. db_sqlite_delete(db, table, \"age > 40\"), or \"1=1\" to delete every row",
            ));
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_delete",
                "where: String",
                other.type_name(),
            ))
        }
    };

    // Refused before the approval prompt: a malformed condition is not worth asking about.
    crate::safety::reject_sql_batch("db_sqlite_delete", &where_clause)?;
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "db_sqlite_delete",
        effect: crate::safety::Effect::Destructive,
        what: "db_delete",
        targets: vec![format!("{}:{}", db_path, table)],
        blast_radius: serde_json::json!({
            "db": db_path.clone(), "table": table.clone(), "where": where_clause.clone()
        }),
        reversible: false,
        fs_paths: false,
    })?;

    // The table is an identifier and is validated; the WHERE clause is SQL by
    // contract -- this builtin exists to take one -- so it is the caller's.
    let sql = format!(
        "DELETE FROM {} WHERE {}",
        crate::safety::sql_identifier("db_sqlite_delete", &table)?,
        where_clause
    );
    sqlite_exec_contained_as(
        "db_sqlite_delete",
        vec![Value::Str(db_path), Value::Str(sql)],
    )
}

fn bi_db_sqlite_count(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_count",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_count",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let where_clause = args.get(2).and_then(|v| match v {
        Value::Str(s) => Some(s.clone()),
        _ => None,
    });

    let sql = if let Some(w) = where_clause {
        format!(
            "SELECT COUNT(*) as count FROM {} WHERE {}",
            crate::safety::sql_identifier("db_sqlite_count", &table)?,
            w
        )
    } else {
        format!(
            "SELECT COUNT(*) as count FROM {}",
            crate::safety::sql_identifier("db_sqlite_count", &table)?
        )
    };

    // This matched only a String count. db_sqlite_query returns it as an Int,
    // so every table counted 0 -- a 3-row table included.
    let rows = bi_db_sqlite_query(vec![Value::Str(db_path), Value::Str(sql)], None)?;
    let count = match &rows {
        Value::Array(arr) => match arr.first() {
            Some(Value::Record(rec)) => match rec.get("count") {
                Some(Value::Int(n)) => Some(*n),
                Some(Value::Str(s)) => s.trim().parse().ok(),
                _ => None,
            },
            _ => None,
        },
        _ => None,
    };
    count.map(Value::Int).ok_or_else(|| {
        crate::safety::tool_failed(
            "db_sqlite_count",
            "sqlite3 SELECT COUNT(*)",
            None,
            &format!("no count in the result: {}", rows.to_display_string()),
        )
    })
}

fn bi_db_sqlite_create_table(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_create_table",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_create_table",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let columns = match args.get(2) {
        Some(Value::Record(r)) => r.clone(),
        Some(Value::Str(s)) => {
            // Allow raw column definition
            if s.trim().is_empty() {
                return Err(crate::safety::arg_err(
                    "db_sqlite_create_table: column definition must be nonempty",
                ));
            }
            crate::safety::reject_sql_batch("db_sqlite_create_table", s)?;
            let sql = format!(
                "CREATE TABLE IF NOT EXISTS {} ({})",
                crate::safety::sql_identifier("db_sqlite_create_table", &table)?,
                s
            );
            return sqlite_exec_contained(vec![Value::Str(db_path), Value::Str(sql)]);
        }
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_create_table",
                "Record or String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    if columns.is_empty() {
        return Err(crate::safety::arg_err(
            "db_sqlite_create_table: columns must be a nonempty Record",
        ));
    }

    // Record-form column names and type strings are validated before execution.
    // The explicit raw-SQL string form above retains the caller's SQL grammar.
    let col_defs: Vec<String> = columns
        .iter()
        .map(|(name, typ)| {
            let name = crate::safety::sql_identifier("db_sqlite_create_table", name)?;
            let type_str = match typ {
                Value::Str(s) => crate::safety::sql_column_type("db_sqlite_create_table", s)?,
                other => {
                    return Err(crate::safety::bad_arg(
                        "db_sqlite_create_table",
                        "column type: String",
                        other.type_name(),
                    ))
                }
            };
            Ok(format!("{} {}", name, type_str))
        })
        .collect::<Result<_>>()?;

    let sql = format!(
        "CREATE TABLE IF NOT EXISTS {} ({})",
        crate::safety::sql_identifier("db_sqlite_create_table", &table)?,
        col_defs.join(", ")
    );
    sqlite_exec_contained(vec![Value::Str(db_path), Value::Str(sql)])
}

fn bi_db_sqlite_drop_table(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_drop_table",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_drop_table",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "db_sqlite_drop_table",
        effect: crate::safety::Effect::Destructive,
        what: "db_sqlite_drop_table",
        targets: vec![format!("{}:{}", db_path, table)],
        blast_radius: serde_json::json!({ "db": db_path, "table": table }),
        // Reversible only inside a transaction — db_sqlite_exec snapshots the
        // file, so a rollback restores it byte-for-byte.
        reversible: crate::tx::is_active(),
        fs_paths: false,
    })?;
    // Validated after the guard, so an approval prompt still describes the table
    // the caller named rather than a sanitised version of it.
    let sql = format!(
        "DROP TABLE IF EXISTS {}",
        crate::safety::sql_identifier("db_sqlite_drop_table", &table)?
    );
    sqlite_exec_contained(vec![Value::Str(db_path), Value::Str(sql)])
}

fn bi_db_sqlite_vacuum(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_vacuum",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // Run in-process: the sqlite3 CLI's `-safe` mode refuses the ATTACH that
    // VACUUM runs inside itself ("cannot run ATTACH in safe mode"), so every
    // call failed. The statement is fixed text and no caller SQL reaches it.
    crate::safety::reject_option_like("db_sqlite_vacuum", std::slice::from_ref(&db_path))?;
    let db_path = sqlite_db_in_workspace(&db_path)?;
    sqlite_db_file("db_sqlite_vacuum", &db_path)?;
    crate::journal::record_file_once("db_sqlite_exec", &db_path);
    crate::tx::snapshot(&db_path);
    let vacuum_error = |e: rusqlite::Error| {
        crate::safety::tool_failed("db_sqlite_vacuum", "VACUUM", None, &e.to_string())
    };
    rusqlite::Connection::open(&db_path)
        .and_then(|conn| conn.execute_batch("VACUUM;"))
        .map_err(vacuum_error)?;
    Ok(Value::Bool(true))
}

fn bi_db_sqlite_dump(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_dump",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    crate::safety::reject_option_like("db_sqlite_dump", std::slice::from_ref(&db_path))?;
    if !sqlite_db_exists(&db_path) {
        return Err(crate::safety::not_found(
            "db_sqlite_dump",
            "database",
            &db_path,
        ));
    }
    sqlite_db_file("db_sqlite_dump", &db_path)?;
    let mut cmd = crate::safety::child_command("sqlite3");
    cmd.args(["-safe", "-readonly", &db_path, ".dump"]);
    let output = bounded_cmd_output("db_sqlite_dump", "sqlite3", cmd, TOOL_DEADLINE_SECS)?;

    if output.status.success() {
        return Ok(Value::Str(
            String::from_utf8_lossy(&output.stdout).to_string(),
        ));
    }
    // A failure answered null.
    Err(crate::safety::tool_failed(
        "db_sqlite_dump",
        "sqlite3 .dump",
        output.status.code(),
        &String::from_utf8_lossy(&output.stderr),
    ))
}

fn bi_db_sqlite_import(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_import",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let sql_file = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_import",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    let sql = read_text_capped("db_sqlite_import", &sql_file)?;
    sqlite_exec_contained(vec![Value::Str(db_path), Value::Str(sql)])
}

fn bi_db_json_to_sqlite(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // A malformed call used to return `Ok(Value::Bool(false))`: no error, exit
    // 0, and a value the caller may well read as "the import found nothing".
    // Same shape as `round(x, digits)` discarding `digits` and `env(name,
    // default)` discarding `default` -- a wrong answer with nothing in it that
    // says to look again. The argument order is (db, json, table), which is the
    // opposite of what the name reads like, so getting it wrong is the likely
    // mistake and it must say so.
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_json_to_sqlite",
                "a database path as the first argument: db_json_to_sqlite(db, json, table)",
                other.map_or("nothing", |v| v.type_name()),
            ))
        }
    };
    let json_path = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_json_to_sqlite",
                "a JSON path as the second argument: db_json_to_sqlite(db, json, table)",
                other.map_or("nothing", |v| v.type_name()),
            ))
        }
    };
    let table_name = match args.get(2) {
        Some(Value::Str(s)) => s.clone(),
        _ => "imported".to_string(),
    };

    // Read JSON
    let content = read_text_capped("db_json_to_sqlite", &json_path)?;
    // Everything is checked and every statement built before the first write.
    // This answered true after skipping any row that was not an object, wrote a
    // nested value as NULL, and failed partway on a row with a key the table
    // lacks, leaving the rows before it behind.
    let json: serde_json::Value = serde_json::from_str(&content).map_err(|e| {
        crate::safety::bad_arg(
            "db_json_to_sqlite",
            "a JSON file holding an array of objects",
            &e.to_string(),
        )
    })?;
    let serde_json::Value::Array(rows) = json else {
        return Err(crate::safety::bad_arg(
            "db_json_to_sqlite",
            "a JSON array of objects",
            "another JSON value",
        ));
    };
    // An empty array names no columns, so no table can be made: nothing imported.
    let Some(first) = rows.first() else {
        return Ok(Value::Bool(false));
    };
    let serde_json::Value::Object(first) = first else {
        return Err(crate::safety::bad_arg(
            "db_json_to_sqlite",
            "a JSON array of objects",
            "row 0 is not an object",
        ));
    };
    // Column names come from the *file*, so the injection payload does not even
    // have to be an argument: a JSON object key of
    // `x TEXT); DROP TABLE victim; --` closed the statement and the sqlite3 CLI
    // ran what followed. Every name is therefore quoted as an identifier
    // (`sql_identifier`), which also lets a key with a space or a reserved word
    // become a column.
    //
    // The columns are the union of the rows' keys, in the order first seen; a row
    // without a key stores NULL. Each column is typed as `sql` reads the same
    // file: INTEGER for integers and Booleans (1 or 0), REAL when a number has a
    // fraction, TEXT for strings, nested values (stored as JSON text) and a column
    // of nothing but nulls.
    let mut keys: Vec<&String> = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for (index, row) in rows.iter().enumerate() {
        let serde_json::Value::Object(obj) = row else {
            return Err(crate::safety::bad_arg(
                "db_json_to_sqlite",
                "a JSON array of objects",
                &format!("row {index} is not an object"),
            ));
        };
        for key in obj.keys() {
            if seen.insert(key) {
                keys.push(key);
            }
        }
    }
    let _ = first;
    let columns: Vec<String> = keys
        .iter()
        .map(|key| {
            let (mut ints, mut reals, mut text) = (false, false, false);
            for row in &rows {
                match row.get(key.as_str()) {
                    None | Some(serde_json::Value::Null) => {}
                    Some(serde_json::Value::Bool(_)) => ints = true,
                    Some(serde_json::Value::Number(n)) if n.is_i64() => ints = true,
                    Some(serde_json::Value::Number(_)) => reals = true,
                    Some(_) => text = true,
                }
            }
            let kind = if text {
                "TEXT"
            } else if reals {
                "REAL"
            } else if ints {
                "INTEGER"
            } else {
                "TEXT"
            };
            Ok(format!(
                "{} {kind}",
                crate::safety::sql_identifier("db_json_to_sqlite", key)?
            ))
        })
        .collect::<Result<_>>()?;
    let create_sql = format!(
        "CREATE TABLE IF NOT EXISTS {} ({})",
        crate::safety::sql_identifier("db_json_to_sqlite", &table_name)?,
        columns.join(", ")
    );

    let cols: Vec<String> = keys
        .iter()
        .map(|key| crate::safety::sql_identifier("db_json_to_sqlite", key))
        .collect::<Result<_>>()?;
    let mut inserts = Vec::with_capacity(rows.len());
    for row in &rows {
        let vals: Vec<String> = keys
            .iter()
            .map(|key| {
                Ok(match row.get(key.as_str()) {
                    None | Some(serde_json::Value::Null) => "NULL".to_string(),
                    Some(serde_json::Value::String(s)) => {
                        crate::safety::sql_literal("db_json_to_sqlite", s)?
                    }
                    Some(serde_json::Value::Number(n)) => n.to_string(),
                    Some(serde_json::Value::Bool(b)) => if *b { "1" } else { "0" }.to_string(),
                    Some(nested) => {
                        crate::safety::sql_literal("db_json_to_sqlite", &nested.to_string())?
                    }
                })
            })
            .collect::<Result<_>>()?;
        inserts.push(format!(
            "INSERT INTO {} ({}) VALUES ({})",
            crate::safety::sql_identifier("db_json_to_sqlite", &table_name)?,
            cols.join(", "),
            vals.join(", ")
        ));
    }

    sqlite_exec_contained_as(
        "db_json_to_sqlite",
        vec![Value::Str(db_path.clone()), Value::Str(create_sql)],
    )?;
    for insert_sql in inserts {
        sqlite_exec_contained_as(
            "db_json_to_sqlite",
            vec![Value::Str(db_path.clone()), Value::Str(insert_sql)],
        )?;
    }
    Ok(Value::Bool(true))
}

fn bi_db_sqlite_to_json(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_to_json",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let table = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "db_sqlite_to_json",
                "String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    bi_db_sqlite_query(
        vec![
            Value::Str(db_path),
            Value::Str(format!(
                "SELECT * FROM {}",
                crate::safety::sql_identifier("db_sqlite_to_json", &table)?
            )),
        ],
        None,
    )
}

fn bi_db_kv_store(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Initialize KV store
    let store_path = args
        .first()
        .and_then(|v| match v {
            Value::Str(s) => Some(s.clone()),
            _ => None,
        })
        .unwrap_or_else(|| ".ironshell_kv.db".to_string());

    // The result was discarded, so a store that could not be created was
    // reported as created.
    sqlite_exec_contained(vec![
        Value::Str(store_path.clone()),
        Value::Str("CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT)".to_string()),
    ])?;
    Ok(Value::Str(store_path))
}

// =====================================================================
// ROBUST FILE EDITING BUILTINS (for AI agents)
// =====================================================================
// These functions provide structured, atomic file editing that avoids
// shell quoting/escaping issues that plague BASH and PowerShell.
// AI agents can safely manipulate multi-line text without worrying about
// special characters, newlines, or encoding problems.
// =====================================================================

/// file_write(path, content) - Write content to a file (creates or overwrites)
/// This is the foundation for safe file writing without shell escaping issues.
/// Usage: file_write("config.txt", "line1\nline2\nline3")
///        content | file_write("output.txt")
fn write_file_atomically(builtin: &str, path: &str, content: &[u8]) -> Result<()> {
    use std::io::Write;
    let requested = std::path::Path::new(path);
    // A rename over a symlink would replace the link with a regular file. So a
    // symlink is resolved first, and the write goes next to the file it names;
    // the link keeps pointing at the updated file. The jail check already
    // resolves links, so the resolved file is the one that was checked.
    let resolved;
    let target: &std::path::Path = match fs::symlink_metadata(requested) {
        Ok(meta) if meta.file_type().is_symlink() => {
            resolved = fs::canonicalize(requested)
                .map_err(|error| crate::safety::fs_write_error(builtin, path, &error))?;
            &resolved
        }
        _ => requested,
    };
    let parent = target
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    let temporary = parent.join(format!(".ironshell_tmp_{}", uuid::Uuid::new_v4()));
    // Never reuse another writer's temporary file or follow a preexisting link.
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&temporary)
        .map_err(|error| crate::safety::fs_write_error(builtin, path, &error))?;
    let original_permissions = file.metadata().ok().map(|m| m.permissions());
    // The data must reach the disk before the rename publishes it, or a crash
    // can leave an empty or partial file under the target name.
    let written = file.write_all(content).and_then(|_| file.sync_all());
    drop(file);
    let result = written
        .map_err(|error| crate::safety::fs_write_error(builtin, path, &error))
        .and_then(|_| match fs::metadata(target) {
            // An existing target keeps its mode (Unix) and read-only attribute (Windows).
            Ok(existing) => fs::set_permissions(&temporary, existing.permissions())
                .map_err(|error| crate::safety::fs_write_error(builtin, path, &error)),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(crate::safety::fs_write_error(builtin, path, &error)),
        })
        .and_then(|_| {
            fs::rename(&temporary, target)
                .map_err(|error| crate::safety::fs_write_error(builtin, path, &error))
        });
    match result {
        Ok(()) => {
            sync_parent_directory(parent);
            Ok(())
        }
        Err(error) => {
            // Restore our own file's permissions before removing it: a read-only copy cannot be deleted on Windows.
            if let Some(permissions) = original_permissions {
                let _ = fs::set_permissions(&temporary, permissions);
            }
            let _ = fs::remove_file(&temporary);
            Err(error)
        }
    }
}

/// Best-effort fsync of the directory that holds a just-renamed file, so the
/// rename itself survives a crash on Unix. Errors are ignored: the file is
/// already published, and some filesystems refuse to sync a directory.
#[cfg(unix)]
fn sync_parent_directory(parent: &std::path::Path) {
    if let Ok(dir) = fs::File::open(parent) {
        let _ = dir.sync_all();
    }
}

/// Windows has no directory fsync in std, and the rename is already durable there.
#[cfg(not(unix))]
fn sync_parent_directory(_parent: &std::path::Path) {}

/// The text a file_write or file_append writes for `value`: a String as is, an
/// Array of Strings joined with newlines. Any other value is refused before a
/// byte is written, with a hint for converting it; its Debug text is never written.
fn text_to_write(builtin: &str, value: &Value) -> Result<String> {
    match value {
        Value::Str(s) => Ok(s.clone()),
        Value::Array(items) => {
            let mut lines = Vec::with_capacity(items.len());
            for (index, item) in items.iter().enumerate() {
                match item {
                    Value::Str(s) => lines.push(s.as_str()),
                    other => return Err(not_text_to_write(builtin, other, Some(index))),
                }
            }
            // Each element is a line: joined with "\n", with no line break after the last.
            Ok(lines.join("\n"))
        }
        other => Err(not_text_to_write(builtin, other, None)),
    }
}

/// The refusal for content that is not text. `element` is the index of the
/// Array element that is not a String, counted from 0 as the batch messages are.
fn not_text_to_write(builtin: &str, value: &Value, element: Option<usize>) -> anyhow::Error {
    let got = value.type_name();
    let message = match element {
        Some(index) => format!(
            "{builtin}: content: an Array must hold only Strings (lines), element {index} is {got}"
        ),
        None => format!("{builtin}: content must be a String or an Array of Strings, got {got}"),
    };
    let hint = match value {
        Value::Bool(_) | Value::Int(_) | Value::Float(_) => {
            "convert it first, e.g. str(value) or to_json(value)"
        }
        _ => "convert it first, e.g. to_json(value) or to_toml(value)",
    };
    crate::safety::bad_arg_in(builtin, message, hint)
}

fn bi_file_write(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err("file_write requires a file path"));
    }

    let path = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "file_write",
                "path: String",
                other.type_name(),
            ))
        }
    };
    // In a jailed context, a relative path is workspace-relative (not CWD-relative)
    // so the write lands inside the jail and matches the transaction journal.
    let path = crate::safety::resolve_path_str(&path);

    // Get content from args or pipeline input
    let content = if args.len() > 1 {
        text_to_write("file_write", &args[1])?
    } else {
        match input {
            Some(value) => text_to_write("file_write", &value)?,
            None => {
                return Err(crate::safety::arg_err(
                    "file_write requires content to write",
                ))
            }
        }
    };

    // Agent mode / explicit workspace: a write is allowed but jailed to the
    // workspace (WriteLocal is allow-by-policy; fs_paths enforces containment, so
    // an absolute path outside the workspace is rejected).
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "file_write",
        effect: crate::safety::Effect::WriteLocal,
        what: "write",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({ "bytes": content.len() }),
        reversible: true,
        fs_paths: true,
    })?;

    crate::tx::snapshot(&path); // record pre-write state if a transaction is active

    let shared = shared_link_count(&path);
    write_file_atomically("file_write", &path, content.as_bytes())?;

    let mut result = BTreeMap::new();
    result.insert("path".to_string(), Value::Str(path));
    result.insert("bytes".to_string(), Value::Int(content.len() as i64));
    result.insert(
        "lines".to_string(),
        Value::Int(content.lines().count() as i64),
    );
    result.insert("success".to_string(), Value::Bool(true));
    if shared.is_some() {
        result.insert("note".to_string(), Value::Str(SHARED_LINK_NOTE.to_string()));
    }

    Ok(Value::Record(result))
}

/// The note on a result whose atomic replace broke a hard link: the rename
/// gives the target a new file, so its other names keep the old content.
const SHARED_LINK_NOTE: &str = "replaced a hard-linked file; its other links keep the old content";

/// The link count of `path` when it has more than one hard link, read before an
/// atomic replace of it. `None` for a file with one name or none.
fn shared_link_count(path: &str) -> Option<u64> {
    crate::safety::hard_link_count(std::path::Path::new(path)).filter(|n| *n > 1)
}

/// file_append(path, content) - Append content to a file
/// Usage: file_append("log.txt", "New log entry\n")
///        new_lines | file_append("data.txt")
fn bi_file_append(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err("file_append requires a file path"));
    }

    let path = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "file_append",
                "path: String",
                other.type_name(),
            ))
        }
    };
    // Jailed: relative paths are workspace-relative (see file_write).
    let path = crate::safety::resolve_path_str(&path);

    // Get content from args or pipeline input
    let content = if args.len() > 1 {
        text_to_write("file_append", &args[1])?
    } else {
        match input {
            Some(value) => text_to_write("file_append", &value)?,
            None => {
                return Err(crate::safety::arg_err(
                    "file_append requires content to append",
                ))
            }
        }
    };

    // Jailed to the workspace in agent mode (see file_write).
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "file_append",
        effect: crate::safety::Effect::WriteLocal,
        what: "append",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({ "bytes": content.len() }),
        reversible: true,
        fs_paths: true,
    })?;
    crate::safety::refuse_hard_linked_write("file_append", &path)?;

    crate::tx::snapshot(&path); // record pre-append state if a transaction is active

    use std::io::Write;
    let mut file = crate::safety::open_in_place("file_append", std::path::Path::new(&path), true)
        .map_err(|e| crate::safety::in_place_error("file_append", &path, e))?;

    file.write_all(content.as_bytes())
        .map_err(|error| crate::safety::fs_error("file_append", &path, &error))?;

    let mut result = BTreeMap::new();
    result.insert("path".to_string(), Value::Str(path));
    result.insert(
        "bytes_appended".to_string(),
        Value::Int(content.len() as i64),
    );
    result.insert("success".to_string(), Value::Bool(true));

    Ok(Value::Record(result))
}

/// An empty string to find matches at every character boundary, so a
/// replacement with it writes new text between every character of the file.
/// Refused by the edit builtins before anything is read or written.
fn refuse_empty_find(builtin: &str, find: &str) -> Result<()> {
    if !find.is_empty() {
        return Ok(());
    }
    Err(crate::safety::bad_arg_in(
        builtin,
        format!("{builtin}: the text to find is empty"),
        "pass the exact text to find; an empty string matches between every character, so nothing was written",
    ))
}

/// A regex that matches empty text (`x*`, `(?:)`) finds a match between every
/// character of a file, so a file edit with it would insert the replacement
/// everywhere. Refused before the file is read or written.
fn refuse_empty_matching_regex(builtin: &str, pattern: &str, re: &regex::Regex) -> Result<()> {
    // What corrupts a file is an empty match *between two characters*: `x*` or
    // `(?:)` inserts the replacement everywhere. An empty match only at a line
    // start or end (`(?m)^`, `$`) or at a boundary is an ordinary sed edit, such
    // as prefixing every line, so it is allowed.
    let between = re
        .find_at("ab", 1)
        .is_some_and(|m| m.start() == 1 && m.is_empty());
    if !between {
        return Ok(());
    }
    Err(crate::safety::bad_arg_in(
        builtin,
        format!(
            "{builtin}: the pattern `{pattern}` matches empty text, which would insert the replacement between every character"
        ),
        "use a pattern that must match at least one character, such as `x+` for `x*`; nothing was written",
    ))
}

/// An edit whose target file does not exist is E_NOT_FOUND, named as such,
/// before any pattern is looked for. A remote-share name is not probed (the
/// probe would open the share); the read that follows checks it.
fn require_edit_target(builtin: &str, path: &str) -> Result<()> {
    if crate::safety::names_a_remote_share(path) || std::path::Path::new(path).exists() {
        return Ok(());
    }
    Err(crate::safety::no_file_at(builtin, path))
}

/// A file_insert line past the end: a file of `count` lines takes lines 1 to
/// count + 1, where count + 1 appends. Anything later used to append silently.
fn file_insert_past_end(path: &str, line: usize, count: usize) -> anyhow::Error {
    crate::safety::bad_arg_in(
        "file_insert",
        format!("file_insert: line {line} is past the end of {path} ({count} lines)"),
        &format!("use line {} to append", count + 1),
    )
}

/// The line break a file is written with: CRLF when every line break in the
/// text is CRLF, LF otherwise (a file with no line break is LF).
fn file_line_break(text: &str) -> &'static str {
    let lf = text.matches('\n').count();
    if lf > 0 && text.matches("\r\n").count() == lf {
        "\r\n"
    } else {
        "\n"
    }
}

/// `text` with each bare LF written as `eol`. A LF that already follows a CR is
/// left alone, so a CRLF in `text` is not doubled. With `eol` = LF it is `text`.
fn with_file_line_breaks(text: &str, eol: &str) -> String {
    if eol == "\n" || !text.contains('\n') {
        return text.to_string();
    }
    let mut out = String::with_capacity(text.len() + eol.len() * 4);
    let mut previous = '\0';
    for c in text.chars() {
        if c == '\n' && previous != '\r' {
            out.push_str(eol);
        } else {
            out.push(c);
        }
        previous = c;
    }
    out
}

/// A line of a file without its line break (LF or CRLF), read as `str::lines`
/// reads it. The segment is one `split_inclusive('\n')` piece of the file.
fn file_line_text(segment: &str) -> &str {
    match segment.strip_suffix('\n') {
        Some(line) => line.strip_suffix('\r').unwrap_or(line),
        None => segment,
    }
}

thread_local! {
    /// The builtin `bi_file_patch` reports its errors under; see bi_file_replace.
    static PATCH_CALLER: std::cell::Cell<&'static str> = const { std::cell::Cell::new("file_patch") };
}

/// file_patch(path, patches) - Apply multiple search/replace operations atomically
/// Patches is an array of records: [{find: "old", replace: "new"}, ...]
/// Usage: file_patch("config.txt", [{find: "DEBUG=0", replace: "DEBUG=1"}])
fn bi_file_patch(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Every error is reported under the builtin the caller invoked: `file_replace`
    // runs through here and sets PATCH_CALLER, so a directory or an unreadable
    // file is reported as file_replace, not file_patch.
    let builtin: &str = PATCH_CALLER.with(|c| c.get());
    if args.is_empty() {
        return Err(crate::safety::arg_err(format!(
            "{builtin} requires a file path"
        )));
    }

    let path = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                builtin,
                "path: String",
                other.type_name(),
            ))
        }
    };
    // Classified `ReadLocal` while the body wrote the file back in place.
    // `WriteLocal` is what the jail keys on, so this path went uncontained.
    let path = guard_local_write(builtin, &path)?;
    require_edit_target(builtin, &path)?;

    let patches = if args.len() > 1 {
        match &args[1] {
            Value::Array(arr) => arr.clone(),
            Value::Record(r) => vec![Value::Record(r.clone())],
            _ => {
                return Err(crate::safety::bad_arg_in(
                    builtin,
                    format!("{builtin}: patches must be an array of records"),
                    &format!(
                        "{builtin} takes [{{find, replace}}] records and does not read a unified diff; each record's find text is replaced with its replace text, in order"
                    ),
                ))
            }
        }
    } else {
        match input {
            Some(Value::Array(arr)) => arr,
            Some(Value::Record(r)) => vec![Value::Record(r)],
            _ => {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: patches must be provided"
                )))
            }
        }
    };

    // Each patch is a full pass over the file, so the batch is capped the way
    // file_edit caps its own.
    if patches.len() > 10_000 {
        return Err(crate::safety::budget_exceeded(
            builtin,
            "batch exceeds 10000 patches".into(),
            "use a smaller batch",
        ));
    }

    // Refuse malformed instructions before reading or writing the file.
    for (index, patch) in patches.iter().enumerate() {
        let Value::Record(record) = patch else {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: patch {index} must be a record"
            )));
        };
        for names in [["find", "old", "search"], ["replace", "new", "with"]] {
            if !matches!(
                record
                    .get(names[0])
                    .or(record.get(names[1]))
                    .or(record.get(names[2])),
                Some(Value::Str(_))
            ) {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: patch {index} requires a {} string",
                    names[0]
                )));
            }
        }
        // An empty find matches between every character: refused, not applied.
        if let Some(Value::Str(find)) = record
            .get("find")
            .or(record.get("old"))
            .or(record.get("search"))
        {
            refuse_empty_find("file_patch", find)?;
        }
    }

    // Read current content
    let mut content = read_text_capped(builtin, &path)?;
    // In a CRLF file the find and replace texts are written with CRLF line
    // breaks, so a multi-line find matches and no bare LF is written into it.
    let eol = file_line_break(&content);

    let mut applied = Vec::new();
    let mut failed = Vec::new();
    // The patch index of each entry in `failed`, in the same order.
    let mut failed_at: Vec<usize> = Vec::new();
    // The text each unmatched patch looked for, in the same order.
    let mut failed_find: Vec<String> = Vec::new();

    for (i, patch) in patches.iter().enumerate() {
        let record = match patch {
            Value::Record(r) => r,
            _ => {
                failed_at.push(i);
                failed.push(Value::Str(format!("patch {}: not a record", i)));
                continue;
            }
        };

        let find_str = match record
            .get("find")
            .or(record.get("old"))
            .or(record.get("search"))
        {
            Some(Value::Str(s)) => s.clone(),
            _ => {
                failed_at.push(i);
                failed.push(Value::Str(format!("patch {}: missing 'find' string", i)));
                continue;
            }
        };

        let replace_str = match record
            .get("replace")
            .or(record.get("new"))
            .or(record.get("with"))
        {
            Some(Value::Str(s)) => s.clone(),
            _ => {
                failed_at.push(i);
                failed.push(Value::Str(format!("patch {}: missing 'replace' string", i)));
                continue;
            }
        };

        let search = with_file_line_breaks(&find_str, eol);
        let replacement = with_file_line_breaks(&replace_str, eol);
        if content.contains(&search) {
            let count = content.matches(&search).count();
            content = content.replace(&search, &replacement);

            let mut patch_result = BTreeMap::new();
            patch_result.insert("find".to_string(), Value::Str(find_str));
            patch_result.insert("replace".to_string(), Value::Str(replace_str));
            patch_result.insert("count".to_string(), Value::Int(count as i64));
            applied.push(Value::Record(patch_result));
        } else {
            failed_at.push(i);
            failed_find.push(find_str.clone());
            failed.push(Value::Str(format!(
                "patch {}: '{}' not found",
                i,
                if find_str.chars().nth(40).is_some() {
                    format!("{}...", find_str.chars().take(40).collect::<String>())
                } else {
                    find_str
                }
            )));
        }
    }

    // All or nothing, and a batch that does not apply is an error: a patch that
    // finds nothing is a failed edit, not a success with a flag in the record.
    // Nothing is written, and the error makes the dispatcher drop the journal
    // step this call would have recorded.
    if let Some(&first) = failed_at.first() {
        let find = failed_find.first().cloned().unwrap_or_default();
        return Err(crate::safety::edit_not_found(
            builtin,
            format!("{builtin}: pattern not found in {path}"),
            &format!(
                "patch {first} looks for {find:?}, which is not in the file as written. \
                 Nothing was written. Read the file first and copy the exact text: a \
                 match is an exact, case-sensitive substring."
            ),
        ));
    }
    let written = !applied.is_empty();
    let mut shared = None;
    if written {
        // Write back atomically
        crate::tx::snapshot(&path); // record pre-patch state if a transaction is active
        shared = shared_link_count(&path);
        write_file_atomically(builtin, &path, content.as_bytes())?;
    } else {
        crate::journal::report_no_change();
    }
    // Nothing was written when a patch failed, so none of them was applied.
    let applied = if written { applied } else { Vec::new() };

    let mut result = BTreeMap::new();
    result.insert("path".to_string(), Value::Str(path));
    result.insert("applied".to_string(), Value::Array(applied.clone()));
    result.insert("failed".to_string(), Value::Array(failed.clone()));
    result.insert("success".to_string(), Value::Bool(failed.is_empty()));
    result.insert("written".to_string(), Value::Bool(written));
    // The first patch that did not apply, by its index in the batch; null when
    // every patch applied. The batch is refused as a whole when it is set.
    result.insert(
        "failed_patch".to_string(),
        failed_at
            .first()
            .map_or(Value::Null, |i| Value::Int(*i as i64)),
    );
    result.insert(
        "patches_applied".to_string(),
        Value::Int(applied.len() as i64),
    );
    result.insert(
        "patches_failed".to_string(),
        Value::Int(failed.len() as i64),
    );
    if shared.is_some() {
        result.insert("note".to_string(), Value::Str(SHARED_LINK_NOTE.to_string()));
    }

    Ok(Value::Record(result))
}

/// file_replace(path, old_text, new_text) - Simple string replacement in a file
/// Usage: file_replace("config.txt", "old_value", "new_value")
fn bi_file_replace(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.len() < 3 {
        return Err(crate::safety::arg_err(
            "file_replace requires path, old_text, and new_text",
        ));
    }

    let path = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "file_replace",
                "path: String",
                other.type_name(),
            ))
        }
    };

    let old_text = match &args[1] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "file_replace",
                "old_text: String",
                other.type_name(),
            ))
        }
    };

    let new_text = match &args[2] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "file_replace",
                "new_text: String",
                other.type_name(),
            ))
        }
    };

    // An empty find string matches between every character, so it would insert
    // new_text everywhere. Refused before the file is read or written.
    refuse_empty_find("file_replace", &old_text)?;

    // A missing file is named as missing, not as a pattern that is not in it.
    require_edit_target("file_replace", &crate::safety::resolve_path_str(&path))?;

    let mut patch = BTreeMap::new();
    patch.insert("find".to_string(), Value::Str(old_text));
    patch.insert("replace".to_string(), Value::Str(new_text));

    // The one-patch batch reports its miss as `file_patch`; a caller who asked
    // for file_replace is told about file_replace.
    let caller = PATCH_CALLER.with(|c| c.replace("file_replace"));
    let result = bi_file_patch(
        vec![
            Value::Str(path.clone()),
            Value::Array(vec![Value::Record(patch)]),
        ],
        None,
    );
    PATCH_CALLER.with(|c| c.set(caller));
    match result {
        Err(e)
            if matches!(
                e.downcast_ref::<crate::safety::SafetyError>(),
                Some(se) if se.code == crate::safety::ErrorCode::NotFound
            ) =>
        {
            let hint = e
                .downcast_ref::<crate::safety::SafetyError>()
                .map(|se| se.hint.clone())
                .unwrap_or_default();
            Err(crate::safety::edit_not_found(
                "file_replace",
                format!("file_replace: pattern not found in {path}"),
                &hint,
            ))
        }
        other => other,
    }
}

/// file_insert(path, position, content) - Insert content at a specific position
fn bi_file_insert(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "file_insert requires path and position",
        ));
    }

    let path = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "file_insert",
                "path: String",
                other.type_name(),
            ))
        }
    };
    // Classified `ReadLocal` while the body wrote the file back in place.
    // `WriteLocal` is what the jail keys on, so this path went uncontained.
    let path = guard_local_write("file_insert", &path)?;
    require_edit_target("file_insert", &path)?;

    // An empty anchor is contained by every line, so the insert would land at
    // the first line. Refused as an empty find.
    let empty_anchor = match &args[1] {
        Value::Str(pos) => pos.is_empty(),
        Value::Record(r) => {
            matches!(r.get("after").or(r.get("before")), Some(Value::Str(t)) if t.is_empty())
        }
        _ => false,
    };
    if empty_anchor {
        return Err(crate::safety::bad_arg_in(
            "file_insert",
            "file_insert: the text to find is empty",
            "pass an anchor line's exact text, a line number, or a keyword (start, end); an empty anchor matches every line, so nothing was written",
        ));
    }

    let content = if args.len() > 2 {
        match &args[2] {
            Value::Str(s) => s.clone(),
            Value::Array(arr) => arr
                .iter()
                .map(|v| match v {
                    Value::Str(s) => s.clone(),
                    other => format!("{:?}", other),
                })
                .collect::<Vec<_>>()
                .join("\n"),
            other => format!("{:?}", other),
        }
    } else {
        match input {
            Some(Value::Str(s)) => s,
            Some(Value::Array(arr)) => arr
                .iter()
                .map(|v| match v {
                    Value::Str(s) => s.clone(),
                    other => format!("{:?}", other),
                })
                .collect::<Vec<_>>()
                .join("\n"),
            Some(other) => format!("{:?}", other),
            None => {
                return Err(crate::safety::arg_err(
                    "file_insert requires content to insert",
                ))
            }
        }
    };

    // Empty content inserts no line, yet the write below would still add a
    // trailing newline: refused before the file is read or written.
    if content.is_empty() {
        return Err(crate::safety::bad_arg_in(
            "file_insert",
            "file_insert: nothing to insert",
            "pass the text to insert; empty content would change nothing, so the file was left as it was",
        ));
    }

    let file_content = read_text_capped("file_insert", &path)?;
    // A UTF-8 byte-order mark stays the first bytes of the file. Line numbers
    // count from the line after it, so line 1 inserts after the BOM, not before.
    let bom = if file_content.starts_with('\u{FEFF}') {
        "\u{FEFF}"
    } else {
        ""
    };
    let file_content = &file_content[bom.len()..];

    // Every file line keeps its own bytes, line break included; only the inserted
    // lines are new. Positions count the lines `str::lines` counts.
    let segments: Vec<&str> = file_content.split_inclusive('\n').collect();
    let lines: Vec<&str> = segments.iter().map(|&s| file_line_text(s)).collect();
    let insert_lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
    let insert_pos: usize;
    let mut pattern_found = true;

    match &args[1] {
        Value::Int(line_num) => {
            if *line_num < 1 {
                return Err(crate::safety::bad_arg_in(
                    "file_insert",
                    format!("file_insert: lines are numbered from 1, got {line_num}"),
                    "use 1 to insert before the first line, or the keyword start; nothing was written",
                ));
            }
            let line = *line_num as usize;
            if line > lines.len() + 1 {
                return Err(file_insert_past_end(&path, line, lines.len()));
            }
            insert_pos = line - 1;
        }
        Value::Str(pos) => match pos.as_str() {
            "start" | "beginning" | "top" => insert_pos = 0,
            "end" | "bottom" | "append" => insert_pos = lines.len(),
            _ => {
                if let Some(idx) = lines.iter().position(|l| l.contains(pos)) {
                    insert_pos = idx + 1;
                } else {
                    pattern_found = false;
                    insert_pos = lines.len();
                }
            }
        },
        Value::Record(r) => {
            if let Some(Value::Str(after_pattern)) = r.get("after") {
                if let Some(idx) = lines.iter().position(|l| l.contains(after_pattern)) {
                    insert_pos = idx + 1;
                } else {
                    pattern_found = false;
                    insert_pos = lines.len();
                }
            } else if let Some(Value::Str(before_pattern)) = r.get("before") {
                if let Some(idx) = lines.iter().position(|l| l.contains(before_pattern)) {
                    insert_pos = idx;
                } else {
                    pattern_found = false;
                    insert_pos = 0;
                }
            } else if let Some(Value::Int(line)) = r.get("line") {
                let line = (*line).max(1) as usize;
                if line > lines.len() + 1 {
                    return Err(file_insert_past_end(&path, line, lines.len()));
                }
                insert_pos = line - 1;
            } else {
                return Err(crate::safety::arg_err(
                    "file_insert: position record must have 'after', 'before', or 'line' key",
                ));
            }
        }
        _ => {
            return Err(crate::safety::arg_err(
                "file_insert: position must be a line number, string, or record",
            ))
        }
    }

    // An anchor that no line contains is a failed insert. It used to be written
    // at the end of the file and reported as a success.
    if !pattern_found {
        let anchor = match &args[1] {
            Value::Str(text) => text.clone(),
            Value::Record(r) => match r.get("after").or(r.get("before")) {
                Some(Value::Str(text)) => text.clone(),
                _ => String::new(),
            },
            _ => String::new(),
        };
        return Err(crate::safety::edit_not_found(
            "file_insert",
            format!("file_insert: anchor {anchor:?} not found in {path}"),
            "no line contains the anchor text. Read the file first and copy a line from \
             it exactly (the match is an exact, case-sensitive substring), or insert by \
             line number. Nothing was written.",
        ));
    }

    // The inserted lines take the file's line break (CRLF in a CRLF file, else
    // LF), and the rest of the file is written back byte for byte. The last line
    // of a file may have no line break: an insert before it leaves it that way,
    // while an insert after it ends that line first, so the new text ends with a
    // line break.
    let eol = file_line_break(file_content);
    let (before, after) = segments.split_at(insert_pos);
    let mut out =
        String::with_capacity(bom.len() + file_content.len() + content.len() + 2 * eol.len());
    out.push_str(bom);
    for segment in before {
        out.push_str(segment);
    }
    if insert_pos == segments.len() && !file_content.is_empty() && !file_content.ends_with('\n') {
        out.push_str(eol);
    }
    for line in &insert_lines {
        out.push_str(line);
        out.push_str(eol);
    }
    for segment in after {
        out.push_str(segment);
    }

    crate::tx::snapshot(&path); // record pre-insert state if a transaction is active
    write_file_atomically("file_insert", &path, out.as_bytes())?;

    let mut result = BTreeMap::new();
    result.insert("path".to_string(), Value::Str(path));
    result.insert(
        "lines_inserted".to_string(),
        Value::Int(insert_lines.len() as i64),
    );
    result.insert("at_line".to_string(), Value::Int((insert_pos + 1) as i64));
    result.insert("pattern_found".to_string(), Value::Bool(pattern_found));
    result.insert("success".to_string(), Value::Bool(true));

    Ok(Value::Record(result))
}

/// Delete an inclusive one-based range or lines selected by a literal pattern.
fn bi_file_delete_lines(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if !(2..=3).contains(&args.len()) || input.is_some() {
        return Err(crate::safety::arg_err("file_delete_lines requires path, line specification and optional range end, without pipeline input"));
    }
    enum Selection {
        Range(usize, usize),
        Pattern(String, bool),
        Regex(regex::Regex),
    }
    // The forms a selection takes, for the refusals below. The generic hint for
    // a bad argument would name only the signature's types.
    const SELECTION_FORMS: &str = "delete_lines takes a line Int, or a start and an end Int, \
        a String (every line containing that text), or a record {contains|pattern|exact|matching: text} \
        for literal text, or {regex: pattern} for a regular expression";
    fn line_index(value: Value) -> Result<usize> {
        match value {
            Value::Int(n) if n > 0 => usize::try_from(n - 1)
                .map_err(|_| crate::safety::arg_err("file_delete_lines line number is too large")),
            _ => Err(crate::safety::arg_err(
                "file_delete_lines line numbers must be positive Int",
            )),
        }
    }
    let mut args = args.into_iter();
    let Some(Value::Str(path)) = args.next() else {
        return Err(crate::safety::arg_err(
            "file_delete_lines path must be String",
        ));
    };
    let selection = match args.next() {
        Some(value @ Value::Int(_)) => {
            let start = line_index(value)?;
            let end = args.next().map(line_index).transpose()?.unwrap_or(start);
            if end < start {
                return Err(crate::safety::bad_arg_in(
                    "delete_lines",
                    "delete_lines range end must not precede start",
                    "give the first line, then a last line at or after it",
                ));
            }
            Selection::Range(start, end)
        }
        Some(Value::Record(record)) => {
            if args.next().is_some() || record.len() != 1 {
                return Err(crate::safety::arg_err("file_delete_lines pattern record requires exactly one selector and no range end"));
            }
            let (key, value) = record.into_iter().next().expect("one selector checked");
            if !matches!(
                key.as_str(),
                "matching" | "contains" | "pattern" | "exact" | "regex"
            ) {
                return Err(crate::safety::bad_arg_with_hint(
                    "delete_lines",
                    "a selector record with one of matching, contains, pattern, exact or regex",
                    &format!("{key:?}"),
                    SELECTION_FORMS,
                ));
            }
            let Value::Str(pattern) = value else {
                return Err(crate::safety::arg_err(
                    "file_delete_lines pattern must be String",
                ));
            };
            if key == "regex" {
                let re = regex::Regex::new(&pattern).map_err(|e| {
                    crate::safety::bad_arg(
                        "delete_lines",
                        "a regular expression (Rust regex syntax)",
                        &regex_error_detail(&e),
                    )
                })?;
                Selection::Regex(re)
            } else {
                Selection::Pattern(pattern, key == "exact")
            }
        }
        // A String is the `contains` form of the pattern record: every line that
        // holds this literal text goes, as `{contains: text}` does.
        Some(Value::Str(text)) => {
            if args.next().is_some() {
                return Err(crate::safety::arg_err(
                    "file_delete_lines takes one String selector and no range end",
                ));
            }
            Selection::Pattern(text, false)
        }
        _ => {
            return Err(crate::safety::bad_arg_in(
                "file_delete_lines",
                "file_delete_lines selection must be a positive Int, a String, or a pattern Record",
                SELECTION_FORMS,
            ))
        }
    };
    let path = crate::safety::resolve_path_str(&path);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "file_delete_lines",
        effect: crate::safety::Effect::Destructive,
        what: "delete lines",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({"path":path}),
        reversible: true,
        fs_paths: true,
    })?;
    let content = line_read("file_delete_lines", &path)?;
    let mut new_content = String::with_capacity(content.len());
    let mut deleted = 0;
    let mut remaining = 0;
    for (index, line) in content.lines().enumerate() {
        let remove = match &selection {
            Selection::Range(start, end) => (*start..=*end).contains(&index),
            Selection::Pattern(pattern, exact) => {
                if *exact {
                    line == pattern
                } else {
                    line.contains(pattern)
                }
            }
            Selection::Regex(re) => re.is_match(line),
        };
        if remove {
            deleted += 1;
        } else {
            new_content.push_str(line);
            new_content.push('\n');
            remaining += 1;
        }
    }
    crate::tx::snapshot(&path);
    write_file_atomically("file_delete_lines", &path, new_content.as_bytes())?;
    let mut result: BTreeMap<String, Value> = BTreeMap::from([
        ("path".into(), Value::Str(path)),
        ("lines_deleted".into(), Value::Int(deleted)),
        ("lines_remaining".into(), Value::Int(remaining)),
        ("success".into(), Value::Bool(true)),
    ]);
    // A literal selector that holds regex syntax and deletes nothing is the
    // usual regex mistake (`t.*` as a pattern); say so rather than leave it silent.
    if let Selection::Pattern(text, _) = &selection {
        if deleted == 0 && text.chars().any(|c| ".*+?^$[](){}|\\".contains(c)) {
            result.insert(
                "note".into(),
                Value::Str("matched literally; use {regex: ...} for a regular expression".into()),
            );
        }
    }
    Ok(Value::Record(result))
}

/// Apply a validated batch in descending line order, then publish once.
fn bi_file_edit(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const MAX_BYTES: usize = 64 * 1024 * 1024;
    const MAX_LINES: usize = 1_000_000;
    if (input.is_some() && args.len() != 1) || (input.is_none() && args.len() != 2) {
        return Err(crate::safety::arg_err(
            "file_edit requires path and direct or piped edits, without conflicting input",
        ));
    }
    let mut args = args.into_iter();
    let Some(Value::Str(path)) = args.next() else {
        return Err(crate::safety::arg_err("file_edit path must be String"));
    };
    let edits = match input.or_else(|| args.next()) {
        Some(Value::Array(edits)) => edits,
        Some(edit @ Value::Record(_)) => vec![edit],
        _ => {
            return Err(crate::safety::arg_err(
                "file_edit edits must be a Record or Array of Records",
            ))
        }
    };
    if edits.len() > 10_000 {
        return Err(crate::safety::budget_exceeded(
            "file_edit",
            "batch exceeds 10000 edits".into(),
            "use a smaller batch",
        ));
    }
    fn field(
        record: &mut BTreeMap<String, Value>,
        name: &str,
        alias: &str,
    ) -> Result<Option<Value>> {
        let first = record.remove(name);
        let second = record.remove(alias);
        if first.is_some() && second.is_some() {
            return Err(crate::safety::arg_err(format!(
                "file_edit cannot combine {name} and {alias}"
            )));
        }
        Ok(first.or(second))
    }
    // `key` is the field name(s) as the message quotes them, e.g. `"line"`.
    fn position(value: Option<Value>, index: usize, key: &str) -> Result<usize> {
        match value {
            Some(Value::Int(n)) if n > 0 => usize::try_from(n - 1).map_err(|_| {
                crate::safety::bad_arg_in(
                    "file_edit",
                    format!("file_edit: edit {index} {key} is too large"),
                    "use a line number within the file",
                )
            }),
            Some(Value::Int(n)) => Err(crate::safety::bad_arg_in(
                "file_edit",
                format!("file_edit: edit {index} {key} is {n}; line numbers count from 1"),
                "use 1 for the first line of the file",
            )),
            Some(other) => Err(crate::safety::bad_arg_in(
                "file_edit",
                format!(
                    "file_edit: edit {index} {key} must be an Int from 1, got {}",
                    other.type_name()
                ),
                "give the 1-based line number as an Int",
            )),
            None => Err(crate::safety::bad_arg_in(
                "file_edit",
                format!("file_edit: edit {index} has no {key} (an Int from 1)"),
                "every edit names the 1-based line it works on",
            )),
        }
    }
    struct Edit {
        index: usize,
        op: &'static str,
        start: usize,
        end: usize,
        lines: Vec<String>,
    }
    let mut prepared = Vec::with_capacity(edits.len());
    let mut payload_bytes = 0usize;
    let mut payload_lines = 0usize;
    for (index, edit) in edits.into_iter().enumerate() {
        let Value::Record(mut record) = edit else {
            return Err(crate::safety::arg_err(
                "file_edit every edit must be a Record",
            ));
        };
        let op = match field(&mut record, "op", "operation")? {
            Some(Value::Str(op)) => match op.as_str() {
                "replace" | "replace_range" => "replace_range",
                "insert" | "insert_at" => "insert_at",
                "delete" | "delete_range" => "delete_range",
                _ => {
                    return Err(crate::safety::bad_arg_in(
                        "file_edit",
                        format!(
                            "file_edit: edit {index} has unknown op \"{op}\": use replace, insert or delete"
                        ),
                        "replace swaps lines, insert adds lines before a line, delete removes lines",
                    ))
                }
            },
            Some(other) => {
                return Err(crate::safety::bad_arg_in(
                    "file_edit",
                    format!(
                        "file_edit: edit {index} \"op\" must be a String, got {}",
                        other.type_name()
                    ),
                    "use replace, insert or delete",
                ))
            }
            None => {
                return Err(crate::safety::bad_arg_in(
                    "file_edit",
                    format!("file_edit: edit {index} has no \"op\": use replace, insert or delete"),
                    "use replace, insert or delete",
                ))
            }
        };
        let start = if op == "insert_at" {
            position(record.remove("line"), index, "\"line\"")?
        } else {
            position(
                field(&mut record, "start_line", "line")?,
                index,
                "\"start_line\" or \"line\"",
            )?
        };
        let end = if op == "insert_at" {
            start
        } else {
            record
                .remove("end_line")
                .map(|v| position(Some(v), index, "\"end_line\""))
                .transpose()?
                .unwrap_or(start)
        };
        if end < start {
            return Err(crate::safety::arg_err(
                "file_edit range end must not precede start",
            ));
        }
        let lines = if op == "delete_range" {
            Vec::new()
        } else {
            let text = match field(&mut record, "content", "text")? {
                Some(Value::Str(text)) => text,
                Some(other) => {
                    return Err(crate::safety::bad_arg_in(
                        "file_edit",
                        format!(
                            "file_edit: edit {index} \"content\" must be a String, got {}",
                            other.type_name()
                        ),
                        "pass the text as a String; several lines are joined with \\n",
                    ))
                }
                None => {
                    return Err(crate::safety::bad_arg_in(
                        "file_edit",
                        format!("file_edit: edit {index} has no \"content\" (a String)"),
                        "insert and replace need the text as a String; delete takes no content",
                    ))
                }
            };
            payload_bytes = payload_bytes.saturating_add(text.len());
            payload_lines = payload_lines.saturating_add(text.lines().count());
            if payload_bytes > MAX_BYTES || payload_lines > MAX_LINES {
                return Err(crate::safety::budget_exceeded(
                    "file_edit",
                    "edit payload exceeds 64 MiB or one million lines".into(),
                    "use a smaller batch",
                ));
            }
            text.lines().map(str::to_owned).collect()
        };
        if !record.is_empty() {
            return Err(crate::safety::arg_err(
                "file_edit unknown or conflicting operation fields",
            ));
        }
        prepared.push(Edit {
            index,
            op,
            start,
            end,
            lines,
        });
    }
    let path = guard_local_write("file_edit", &path)?;
    let raw = line_read("file_edit", &path)?;
    // A leading UTF-8 byte-order mark is not a line: it is kept as the first
    // bytes of the file. The lines are written with the file's own line break,
    // CRLF when every line break in the file is CRLF, LF otherwise.
    let bom = if raw.starts_with('\u{FEFF}') {
        "\u{FEFF}"
    } else {
        ""
    };
    let content = &raw[bom.len()..];
    let eol = file_line_break(content);
    let count = content.lines().count();
    let max_lines = count.saturating_add(payload_lines);
    if max_lines > MAX_LINES || max_lines.saturating_mul(prepared.len()) > 10_000_000 {
        return Err(crate::safety::budget_exceeded(
            "file_edit",
            "batch exceeds one million potential lines or ten million line-edit work units".into(),
            "use a smaller file or batch",
        ));
    }
    let mut lines: Vec<String> = content.lines().map(str::to_owned).collect();
    drop(raw);
    prepared.sort_by(|a, b| b.start.cmp(&a.start));
    let mut applied = Vec::with_capacity(prepared.len());
    for edit in prepared {
        let mut result = BTreeMap::from([("op".into(), Value::Str(edit.op.into()))]);
        if edit.op == "insert_at" {
            let at = edit.start.min(lines.len());
            let inserted = edit.lines.len();
            lines.splice(at..at, edit.lines);
            result.insert("line".into(), Value::Int((at + 1) as i64));
            result.insert("lines_inserted".into(), Value::Int(inserted as i64));
        } else {
            if edit.start >= lines.len() {
                let hint = if count == 0 {
                    format!("{path} is empty, so it has no line to edit; use file_insert or file_write to add lines")
                } else {
                    format!("{path} has {count} lines; line numbers count from 1 up to {count}")
                };
                return Err(crate::safety::bad_arg_in(
                    "file_edit",
                    format!("file_edit edit {}: start line out of range", edit.index),
                    &hint,
                ));
            }
            let end = edit.end.min(lines.len() - 1);
            result.insert("start_line".into(), Value::Int((edit.start + 1) as i64));
            if edit.op == "replace_range" {
                lines.splice(edit.start..=end, edit.lines);
                result.insert("end_line".into(), Value::Int((end + 1) as i64));
            } else {
                lines.drain(edit.start..=end);
                result.insert(
                    "lines_deleted".into(),
                    Value::Int((end - edit.start + 1) as i64),
                );
            }
        }
        applied.push(Value::Record(result));
    }
    let bytes = lines.iter().fold(bom.len(), |n, line| {
        n.saturating_add(line.len()).saturating_add(eol.len())
    });
    if bytes > MAX_BYTES {
        return Err(crate::safety::budget_exceeded(
            "file_edit",
            "normalized output exceeds 64 MiB".into(),
            "produce a smaller file",
        ));
    }
    let mut output = String::with_capacity(bytes);
    output.push_str(bom);
    for line in &lines {
        output.push_str(line);
        output.push_str(eol);
    }
    crate::tx::snapshot(&path);
    write_file_atomically("file_edit", &path, output.as_bytes())?;
    let applied_count = applied.len();
    Ok(Value::Record(BTreeMap::from([
        ("path".into(), Value::Str(path)),
        ("applied".into(), Value::Array(applied)),
        ("failed".into(), Value::Array(Vec::new())),
        ("success".into(), Value::Bool(true)),
        ("edits_applied".into(), Value::Int(applied_count as i64)),
        ("edits_failed".into(), Value::Int(0)),
        ("final_lines".into(), Value::Int(lines.len() as i64)),
    ])))
}

/// file_diff(path1, path2) - Compare two files and return differences
fn bi_file_diff(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if input.is_some() || args.len() != 2 {
        return Err(crate::safety::arg_err(
            "file_diff requires two direct file paths and no pipeline input",
        ));
    }
    let mut args = args.into_iter();
    let Some(Value::Str(path1)) = args.next() else {
        return Err(crate::safety::arg_err(
            "file_diff first path must be String",
        ));
    };
    let Some(Value::Str(path2)) = args.next() else {
        return Err(crate::safety::arg_err(
            "file_diff second path must be String",
        ));
    };
    let resolved1 = crate::safety::resolve_path_str(&path1);
    let resolved2 = crate::safety::resolve_path_str(&path2);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "file_diff",
        effect: crate::safety::Effect::ReadLocal,
        what: "compare files",
        targets: vec![resolved1.clone(), resolved2.clone()],
        blast_radius: serde_json::json!({"files":2}),
        reversible: true,
        fs_paths: true,
    })?;
    let content1 = line_read("file_diff", &resolved1)?;
    let content2 = line_read("file_diff", &resolved2)?;
    let mut lines1 = content1.lines();
    let mut lines2 = content2.lines();
    let (mut count1, mut count2, mut line) = (0, 0, 0);
    let mut diffs = Vec::new();
    loop {
        let old = lines1.next();
        let new = lines2.next();
        if old.is_none() && new.is_none() {
            break;
        }
        line += 1;
        count1 += usize::from(old.is_some());
        count2 += usize::from(new.is_some());
        if old == new {
            continue;
        }
        if diffs.len() >= 10000 {
            return Err(crate::safety::budget_exceeded(
                "file_diff",
                "comparison exceeds 10000 differences".into(),
                "compare smaller files",
            ));
        }
        let kind = match (old, new) {
            (Some(_), Some(_)) => "changed",
            (Some(_), None) => "deleted",
            (None, Some(_)) => "added",
            _ => unreachable!(),
        };
        let mut diff = BTreeMap::from([
            ("line".into(), Value::Int(line)),
            ("type".into(), Value::Str(kind.into())),
        ]);
        if let Some(old) = old {
            diff.insert("old".into(), Value::Str(old.to_string()));
        }
        if let Some(new) = new {
            diff.insert("new".into(), Value::Str(new.to_string()));
        }
        diffs.push(Value::Record(diff));
    }
    let diff_count = diffs.len();
    Ok(Value::Record(BTreeMap::from([
        ("file1".into(), Value::Str(path1)),
        ("file2".into(), Value::Str(path2)),
        ("lines1".into(), Value::Int(count1 as i64)),
        ("lines2".into(), Value::Int(count2 as i64)),
        ("differences".into(), Value::Array(diffs)),
        ("diff_count".into(), Value::Int(diff_count as i64)),
        ("identical".into(), Value::Bool(diff_count == 0)),
    ])))
}
/// file_backup(path, [suffix]) - Create a backup copy of a file before editing
/// Usage: file_backup("config.txt")  -> creates config.txt.bak
/// Usage: file_backup("config.txt", ".backup")  -> creates config.txt.backup
fn bi_file_backup(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let mut args = args.into_iter();
    let path = match input {
        Some(Value::Str(path)) => path,
        Some(_) => {
            return Err(crate::safety::arg_err(
                "file_backup piped path must be String",
            ))
        }
        None => match args.next() {
            Some(Value::Str(path)) => path,
            _ => return Err(crate::safety::arg_err("file_backup requires path String")),
        },
    };
    let suffix = match args.next() {
        None => ".bak".to_string(),
        Some(Value::Str(suffix)) => suffix,
        Some(_) => return Err(crate::safety::arg_err("file_backup suffix must be String")),
    };
    if args.next().is_some() {
        return Err(crate::safety::arg_err(
            "file_backup accepts path and optional suffix only",
        ));
    }
    if suffix.is_empty()
        || suffix.ends_with(['.', ' '])
        || suffix
            .chars()
            .any(|c| c.is_control() || matches!(c, '/' | '\\' | ':'))
    {
        return Err(crate::safety::arg_err("file_backup suffix must be nonempty, without separators, colon, controls or trailing dot/space"));
    }
    let backup = crate::safety::resolve_path_str(&format!("{path}{suffix}"));
    let path = crate::safety::resolve_path_str(&path);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "file_backup",
        effect: crate::safety::Effect::WriteLocal,
        what: "back up file",
        targets: vec![path.clone(), backup.clone()],
        blast_radius: serde_json::json!({"files":2}),
        reversible: true,
        fs_paths: true,
    })?;
    // The journal step names the file this call writes (the backup), not the
    // source it only reads: undo removes a new backup, or restores one replaced.
    crate::journal::record_group(
        "file_backup",
        crate::safety::Effect::WriteLocal,
        vec![backup.clone()],
    );
    let bytes = backup_file_atomically(&path, &backup)?;
    Ok(Value::Record(BTreeMap::from([
        ("path".into(), Value::Str(path)),
        ("backup".into(), Value::Str(backup)),
        ("bytes".into(), Value::Int(bytes as i64)),
        ("success".into(), Value::Bool(true)),
    ])))
}

/// Copy binary bytes through an exclusively created sibling, then publish it.
fn backup_file_atomically(source: &str, destination: &str) -> Result<u64> {
    copy_file_atomically("file_backup", source, destination, 64 * 1024 * 1024)
}

fn copy_file_atomically(
    builtin: &str,
    source: &str,
    destination: &str,
    max_bytes: u64,
) -> Result<u64> {
    use std::io::Read;
    let metadata =
        fs::metadata(source).map_err(|e| crate::safety::fs_error(builtin, source, &e))?;
    if !metadata.is_file() {
        return Err(crate::safety::arg_err(format!(
            "{builtin} source must be a regular file"
        )));
    }
    if metadata.len() > max_bytes {
        return Err(crate::safety::budget_exceeded(
            builtin,
            "source exceeds remaining copy byte budget".into(),
            "copy a smaller file",
        ));
    }
    match fs::metadata(destination) {
        Ok(metadata) if !metadata.is_file() => {
            return Err(crate::safety::arg_err(format!(
                "{builtin} destination must be a regular file when it exists"
            )))
        }
        Ok(_) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => return Err(crate::safety::fs_error(builtin, destination, &error)),
    }
    if let Ok(source_path) = fs::canonicalize(source) {
        if fs::canonicalize(destination)
            .is_ok_and(|destination_path| destination_path == source_path)
        {
            return Err(crate::safety::arg_err(format!(
                "{builtin} destination must differ from source"
            )));
        }
    }
    let file = fs::File::open(source).map_err(|e| crate::safety::fs_error(builtin, source, &e))?;
    let target = std::path::Path::new(destination);
    let parent = target
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    let temporary = parent.join(format!(".ironshell_tmp_{}", uuid::Uuid::new_v4()));
    let mut output = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&temporary)
        .map_err(|e| crate::safety::fs_error(builtin, destination, &e))?;
    let original_permissions = output.metadata().ok().map(|m| m.permissions());
    let result = (|| -> Result<u64> {
        let bytes = std::io::copy(&mut file.take(max_bytes + 1), &mut output)
            .map_err(|e| crate::safety::fs_error(builtin, destination, &e))?;
        if bytes > max_bytes {
            return Err(crate::safety::budget_exceeded(
                builtin,
                "source grew beyond remaining copy byte budget".into(),
                "copy a smaller file",
            ));
        }
        output
            .set_permissions(metadata.permissions())
            .map_err(|e| crate::safety::fs_error(builtin, destination, &e))?;
        drop(output);
        crate::tx::snapshot(destination);
        fs::rename(&temporary, target)
            .map_err(|e| crate::safety::fs_error(builtin, destination, &e))?;
        Ok(bytes)
    })();
    if result.is_err() {
        // Restore the original sibling-file permissions before cleaning our own file.
        // This also removes Windows read-only attributes copied from the source.
        if let Some(permissions) = original_permissions {
            let _ = fs::set_permissions(&temporary, permissions);
        }
        let _ = fs::remove_file(&temporary);
    }
    result
}

/// Copy a bounded, preflighted file or directory tree.
fn bi_file_copy(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const MAX_BYTES: u64 = 64 * 1024 * 1024;
    const MAX_ENTRIES: usize = 10_000;
    if args.len() != 2 || input.is_some() {
        return Err(crate::safety::arg_err(
            "file_copy requires exactly source and destination paths, without pipeline input",
        ));
    }
    let mut args = args.into_iter();
    let Some(Value::Str(source)) = args.next() else {
        return Err(crate::safety::arg_err("file_copy source must be String"));
    };
    let Some(Value::Str(dest)) = args.next() else {
        return Err(crate::safety::arg_err(
            "file_copy destination must be String",
        ));
    };
    let source = crate::safety::resolve_path_str(&source);
    let dest = crate::safety::resolve_path_str(&dest);
    // A file onto a directory lands inside it, as `cp` does.
    let dest = file_copy_target(&source, &dest);
    // The source is read: under the jail, a file outside the workspace may not
    // be copied in, or `cp("../outside/secret", "x")` then `cat("x")` reads
    // what `cat("../outside/secret")` is refused.
    crate::security::check_read_jail("file_copy", &source)?;
    let source_path = std::path::Path::new(&source);
    let dest_path = std::path::Path::new(&dest);
    let metadata = fs::symlink_metadata(source_path)
        .map_err(|e| crate::safety::fs_error("file_copy", source_path, &e))?;
    if !metadata.is_file() && !metadata.is_dir() {
        return Err(crate::safety::arg_err(
            "file_copy supports regular files and directories only, without symlink entries",
        ));
    }
    // Canonicalize the existing parent before joining the leaf: this also makes
    // non-existent destinations comparable with the canonical source tree.
    let parent = dest_path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    let parent =
        fs::canonicalize(parent).map_err(|e| crate::safety::fs_error("file_copy", parent, &e))?;
    let leaf = dest_path.file_name().ok_or_else(|| {
        crate::safety::arg_err("file_copy destination must name a file or directory")
    })?;
    if !parent.is_dir() {
        return Err(crate::safety::arg_err(
            "file_copy destination parent must be an existing directory",
        ));
    }
    let canonical_dest = match fs::canonicalize(dest_path) {
        Ok(path) => path,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => parent.join(leaf),
        Err(e) => return Err(crate::safety::fs_error("file_copy", dest_path, &e)),
    };
    let canonical_source = fs::canonicalize(source_path)
        .map_err(|e| crate::safety::fs_error("file_copy", source_path, &e))?;
    if canonical_source == canonical_dest
        || (metadata.is_dir()
            && (canonical_dest.starts_with(&canonical_source)
                || canonical_source.starts_with(&canonical_dest)))
    {
        return Err(crate::safety::arg_err(
            "file_copy source and destination must not overlap",
        ));
    }
    // The source was judged by the read jail above; destinations are guarded.
    let mut plan = vec![(
        source_path.to_path_buf(),
        dest_path.to_path_buf(),
        metadata.is_dir(),
    )];
    let mut bytes = if metadata.is_file() {
        metadata.len()
    } else {
        0
    };
    if metadata.is_dir() {
        for entry in WalkDir::new(source_path).min_depth(1) {
            if plan.len() >= MAX_ENTRIES {
                return Err(crate::safety::budget_exceeded(
                    "file_copy",
                    "copy exceeds 10000 entries".into(),
                    "copy a smaller tree",
                ));
            }
            let entry = entry.map_err(|e| {
                crate::safety::fs_error(
                    "file_copy",
                    e.path().unwrap_or(source_path),
                    &std::io::Error::other(e.to_string()),
                )
            })?;
            let kind = entry.file_type();
            if entry.path().to_str().is_none() {
                return Err(crate::safety::arg_err(
                    "file_copy tree paths must be valid UTF-8",
                ));
            }
            if !kind.is_file() && !kind.is_dir() {
                return Err(crate::safety::arg_err("file_copy tree must contain regular files and directories only, without symlink entries"));
            }
            let relative = entry
                .path()
                .strip_prefix(source_path)
                .map_err(|_| crate::safety::arg_err("file_copy traversal escaped source"))?;
            if kind.is_file() {
                let size = fs::metadata(entry.path())
                    .map_err(|e| crate::safety::fs_error("file_copy", entry.path(), &e))?
                    .len();
                bytes = bytes.saturating_add(size);
            }
            plan.push((
                entry.path().to_path_buf(),
                dest_path.join(relative),
                kind.is_dir(),
            ));
            if bytes > MAX_BYTES {
                break;
            }
        }
    }
    if bytes > MAX_BYTES {
        return Err(crate::safety::budget_exceeded(
            "file_copy",
            "copy exceeds 64 MiB total".into(),
            "copy smaller files",
        ));
    }
    // Refuse conflicts and symlink destinations for the entire plan before any
    // mkdir, transaction snapshot or copy. Existing directories are merged.
    for (_, target, directory) in &plan {
        match fs::symlink_metadata(target) {
            Ok(m) if (*directory && !m.is_dir()) || (!*directory && !m.is_file()) => {
                return Err(crate::safety::arg_err(
                    "file_copy destination type conflicts with source or is a symlink",
                ));
            }
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(crate::safety::fs_error("file_copy", target, &e)),
        }
    }
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "file_copy",
        effect: crate::safety::Effect::WriteLocal,
        what: "copy files",
        targets: plan
            .iter()
            .map(|(_, p, _)| p.to_string_lossy().into_owned())
            .collect(),
        blast_radius: serde_json::json!({"entries":plan.len(),"bytes":bytes}),
        reversible: true,
        fs_paths: true,
    })?;
    let mut copied = 0;
    for (from, to, directory) in plan {
        let to_str = to.to_string_lossy();
        if directory {
            // Snapshot only new directories; snapshotting an existing merge
            // root would also journal unrelated files in that directory.
            if !to.exists() {
                crate::tx::snapshot(&to_str);
                fs::create_dir(&to).map_err(|e| crate::safety::fs_error("file_copy", &to, &e))?;
            }
        } else {
            copied += copy_file_atomically(
                "file_copy",
                &from.to_string_lossy(),
                &to_str,
                MAX_BYTES - copied,
            )?;
        }
    }
    Ok(Value::Record(BTreeMap::from([
        ("source".into(), Value::Str(source)),
        ("dest".into(), Value::Str(dest)),
        ("bytes".into(), Value::Int(copied as i64)),
        ("success".into(), Value::Bool(true)),
    ])))
}

/// `path` with its symbolic links resolved as far as it exists. The part below
/// the first missing ancestor is appended as written, so a destination that does
/// not exist yet still compares with the real location of its parent.
fn canonical_location(path: &str) -> std::path::PathBuf {
    let mut rest: Vec<std::ffi::OsString> = Vec::new();
    let mut current = std::path::Path::new(path);
    loop {
        if let Ok(real) = fs::canonicalize(current) {
            let mut out = real;
            for part in rest.iter().rev() {
                out.push(part);
            }
            return out;
        }
        match (current.parent(), current.file_name()) {
            (Some(parent), Some(name)) => {
                rest.push(name.to_os_string());
                current = parent;
            }
            _ => return std::path::PathBuf::from(path),
        }
    }
}

/// The path a copy from `source` to `dest` writes, both resolved. A regular file
/// copied onto an existing directory goes inside it under its own name, as `cp`
/// does. A symbolic link destination is not followed: it stays as it is, and the
/// copy refuses it.
pub(crate) fn file_copy_target(source: &str, dest: &str) -> String {
    let src = std::path::Path::new(source);
    let dst = std::path::Path::new(dest);
    let source_is_file = fs::symlink_metadata(src).is_ok_and(|m| m.is_file());
    let dest_is_dir = fs::symlink_metadata(dst).is_ok_and(|m| m.is_dir());
    match (source_is_file, dest_is_dir, src.file_name()) {
        (true, true, Some(name)) => dst.join(name).display().to_string(),
        _ => dest.to_string(),
    }
}

/// file_move(source, dest) - Move/rename a file or directory
fn bi_file_move(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::safety::arg_err(
            "file_move requires source and destination paths",
        ));
    }

    let source = match &args[0] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "file_move",
                "source: String",
                other.type_name(),
            ))
        }
    };

    let dest = match &args[1] {
        Value::Str(s) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "file_move",
                "destination: String",
                other.type_name(),
            ))
        }
    };

    // Probed where the move will look: in agent mode a relative source is in
    // the workspace, and probing the bare name asked about the working
    // directory instead, so a file the move would have found was not found.
    if !std::path::Path::new(&crate::safety::resolve_path_str(&source)).exists() {
        return Err(crate::safety::not_found("file_move", "source", &source));
    }

    // Classified `ReadLocal` while the body renamed one path over another —
    // which removes the source and can overwrite the destination. Both ends
    // are caller-supplied, and neither was jailed.
    let (written_source, written_dest) = (source.clone(), dest.clone());
    let (source, dest) = guard_local_move("file_move", &source, &dest)?;
    // A directory moved into its own tree has no place to go: the OS refused it
    // as "denied". Refused here, by name, as file_copy refuses an overlap.
    if fs::metadata(&source).is_ok_and(|m| m.is_dir()) {
        let source_real = fs::canonicalize(&source).ok();
        let dest_real = canonical_location(&crate::journal::normalized_path(&dest));
        if let Some(source_real) = source_real {
            if dest_real != source_real && dest_real.starts_with(&source_real) {
                return Err(crate::safety::arg_err(
                    "file_move: cannot move a directory into itself",
                ));
            }
        }
    }

    // Refused before the rename, which said "no file named" for a missing
    // destination folder (it reads as a missing source) and "denied" for an
    // existing directory. Both are named as what they are, with the fix.
    if !crate::safety::names_a_remote_share(&written_dest) {
        if let Some(parent) = std::path::Path::new(&dest).parent() {
            if !parent.as_os_str().is_empty()
                && fs::metadata(parent).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)
            {
                let folder = std::path::Path::new(&written_dest)
                    .parent()
                    .filter(|p| !p.as_os_str().is_empty())
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|| parent.display().to_string());
                return Err(crate::safety::not_found_with(
                    "file_move",
                    format!(
                        "file_move: the destination folder '{folder}' does not exist; create it with mkdir(\"{folder}\")"
                    ),
                    "mkdir creates the folder; then mv moves the file into it",
                ));
            }
        }
        if fs::metadata(&dest).is_ok_and(|m| m.is_dir()) {
            let base = std::path::Path::new(&written_source)
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| "name".to_string());
            return Err(crate::safety::bad_arg_with_hint(
                "file_move",
                "a destination file path",
                "a directory",
                &format!(
                    "'{written_dest}' is a directory; mv renames, so give the full target path: mv(\"{written_source}\", \"{written_dest}/{base}\")"
                ),
            ));
        }
    }

    let metadata =
        fs::metadata(&source).map_err(|e| crate::safety::fs_error("file_move", &source, &e))?;
    let bytes = metadata.len();

    // Both ends change: the source disappears and the destination is replaced
    // (or created). Rollback restores the source and removes or restores the
    // destination.
    crate::tx::snapshot(&source);
    crate::tx::snapshot(&dest);
    // Both ends are one journal step, recorded before the rename: one undo()
    // puts the source back and restores what the move replaced.
    crate::journal::record_group(
        "file_move",
        crate::safety::Effect::Destructive,
        vec![source.clone(), dest.clone()],
    );
    fs::rename(&source, &dest)
        .map_err(|error| crate::safety::fs_error("file_move", &dest, &error))?;

    let mut result = BTreeMap::new();
    result.insert("source".to_string(), Value::Str(source));
    result.insert("dest".to_string(), Value::Str(dest));
    result.insert("bytes".to_string(), Value::Int(bytes as i64));
    result.insert("success".to_string(), Value::Bool(true));

    Ok(Value::Record(result))
}

/// file_exists(path) - Check if a file or directory exists
fn bi_file_exists(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let path = match args.first().or(input.as_ref()) {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("file_exists requires a path")),
    };

    crate::security::check_read_jail("file_exists", &path)?;
    // Path::exists/is_file/is_dir answer false for any stat error, so a path
    // that could not be checked read as absent. Only NotFound is absent now.
    let p = std::path::Path::new(&path);
    let meta = match std::fs::metadata(p) {
        Ok(meta) => Some(meta),
        Err(e) if path_is_absent(&e) => None,
        Err(e) => return Err(crate::safety::fs_error("file_exists", p, &e)),
    };
    let exists = meta.is_some();
    let is_file = meta.as_ref().is_some_and(|m| m.is_file());
    let is_dir = meta.as_ref().is_some_and(|m| m.is_dir());

    let mut result = BTreeMap::new();
    result.insert("path".to_string(), Value::Str(path));
    result.insert("exists".to_string(), Value::Bool(exists));
    result.insert("is_file".to_string(), Value::Bool(is_file));
    result.insert("is_dir".to_string(), Value::Bool(is_dir));

    Ok(Value::Record(result))
}

/// file_mkdir(path) - Create a directory (and parents if needed)
fn bi_file_mkdir(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let path = match args.first().or(input.as_ref()) {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("file_mkdir requires a path")),
    };

    // An empty path names nothing: resolving it gave the working directory,
    // which "exists", and the call reported a creation that did not happen.
    if path.is_empty() {
        return Err(crate::safety::bad_arg(
            "file_mkdir",
            "path: a non-empty String",
            "an empty String",
        ));
    }
    // Creates a directory at a caller-named path, with no guard until now:
    // `WriteLocal` is not centrally enforced, so nothing jailed it.
    let path = guard_local_write("file_mkdir", &path)?;

    let already_exists = std::path::Path::new(&path).exists();
    // The journal's spelling of the path, so `sub/../m2` and `m2` are one name.
    let target = crate::journal::normalized_path(&path);

    // Inside a transaction, record the highest directory this call creates as
    // absent, so a rollback removes everything it made, parents included.
    if !already_exists {
        let mut top = std::path::Path::new(&target);
        while let Some(parent) = top.parent() {
            if parent.as_os_str().is_empty() || parent.exists() {
                break;
            }
            top = parent;
        }
        crate::tx::snapshot(&top.to_string_lossy());
    }

    // Every directory this call creates, outermost first. One step: undo removes
    // them innermost first, and only the ones still empty, so a directory that
    // something was put into afterwards is left alone and reported.
    let mut created = Vec::new();
    let mut cursor = Some(std::path::Path::new(&target));
    while let Some(dir) = cursor {
        if dir.as_os_str().is_empty() || dir.exists() {
            break;
        }
        created.push(dir.display().to_string());
        cursor = dir.parent();
    }
    created.reverse();
    if !created.is_empty() {
        crate::journal::record_group("file_mkdir", crate::safety::Effect::WriteLocal, created);
    }

    fs::create_dir_all(&target)
        .map_err(|error| crate::safety::fs_error("file_mkdir", &path, &error))?;

    let mut result = BTreeMap::new();
    result.insert("path".to_string(), Value::Str(path));
    result.insert("created".to_string(), Value::Bool(!already_exists));
    result.insert("success".to_string(), Value::Bool(true));

    Ok(Value::Record(result))
}

// ===================== A2A (Agent-to-Agent) Protocol =====================

lazy_static::lazy_static! {
    /// A2A agent registry - maps agent names to their connection info
    static ref A2A_REGISTRY: std::sync::RwLock<BTreeMap<String, BTreeMap<String, Value>>> = {
        std::sync::RwLock::new(BTreeMap::new())
    };

    /// A2A message queue - pending messages for each agent
    static ref A2A_MESSAGES: std::sync::RwLock<BTreeMap<String, Vec<Value>>> = {
        std::sync::RwLock::new(BTreeMap::new())
    };
}

/// Most undelivered messages one agent's queue holds.
const A2A_QUEUE_MAX: usize = 1024;
/// Largest message a2a_send accepts, measured as its display text.
const A2A_MESSAGE_MAX: usize = 64 * 1024;
/// Most agents one process registers (the registry was unbounded).
const A2A_AGENTS_MAX: usize = 256;
/// Most agents one a2a_broadcast reaches in a single call.
const A2A_BROADCAST_RECIPIENTS_MAX: usize = 64;
/// Largest info Record a2a_register stores, measured as its display text.
const A2A_INFO_MAX: usize = 64 * 1024;

/// a2a.send(target, message) - Queue a message for a registered agent. The
/// queue is in-process: nothing leaves the process, so it needs no network guard.
fn bi_a2a_send(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("a2a_send", &input)?;
    let target = collab_text_arg("a2a_send", "target", args.first(), 128)?;
    let message = args
        .get(1)
        .cloned()
        .ok_or_else(|| crate::safety::bad_arg("a2a_send", "message: any value", "nothing"))?;
    let size = message.to_display_string().len();
    if size > A2A_MESSAGE_MAX {
        return Err(crate::safety::budget_exceeded(
            "a2a_send",
            format!("a2a_send: the message is {size} bytes; at most {A2A_MESSAGE_MAX} are sent"),
            "send a reference to the data instead of the data",
        ));
    }
    let registry = A2A_REGISTRY
        .read()
        .map_err(|_| crate::safety::lock_poisoned("a2a_send", "the A2A agent registry"))?;
    if !registry.contains_key(&target) {
        return Err(crate::safety::not_found("a2a_send", "agent", &target));
    }
    drop(registry);

    let mut messages = A2A_MESSAGES
        .write()
        .map_err(|_| crate::safety::lock_poisoned("a2a_send", "the A2A message queue"))?;
    let queue = messages.entry(target.clone()).or_default();
    if queue.len() >= A2A_QUEUE_MAX {
        return Err(crate::safety::budget_exceeded(
            "a2a_send",
            format!("a2a_send: {target} has {A2A_QUEUE_MAX} undelivered messages"),
            "a2a_receive drains an agent's queue",
        ));
    }
    queue.push(message);

    let mut result = BTreeMap::new();
    result.insert("sent".to_string(), Value::Bool(true));
    result.insert("target".to_string(), Value::Str(target));
    Ok(Value::Record(result))
}

/// a2a.receive(agent_name?) - Receive pending messages
fn bi_a2a_receive(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let agent_name = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .unwrap_or_else(|| "default".to_string());
    let mut messages = A2A_MESSAGES.write().unwrap();
    let pending = messages.remove(&agent_name).unwrap_or_default();
    Ok(Value::Array(pending))
}

/// a2a.broadcast(message) - Broadcast to all agents. All or nothing: a refusal
/// (too large, too many recipients, a full queue) leaves every queue as it was.
fn bi_a2a_broadcast(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("a2a_broadcast", &input)?;
    if args.is_empty() {
        return Err(crate::safety::arg_err("a2a.broadcast: requires a message"));
    }
    if args.len() > 1 {
        return Err(crate::safety::bad_arg(
            "a2a_broadcast",
            "one message",
            &format!("{} arguments", args.len()),
        ));
    }
    let message = args[0].clone();
    let size = message.to_display_string().len();
    if size > A2A_MESSAGE_MAX {
        return Err(crate::safety::budget_exceeded(
            "a2a_broadcast",
            format!("the message is {size} bytes; at most {A2A_MESSAGE_MAX} are sent"),
            "send a reference to the data instead of the data",
        ));
    }
    let registry = A2A_REGISTRY
        .read()
        .map_err(|_| crate::safety::lock_poisoned("a2a_broadcast", "the A2A agent registry"))?;
    let agents: Vec<String> = registry.keys().cloned().collect();
    drop(registry);
    if agents.len() > A2A_BROADCAST_RECIPIENTS_MAX {
        return Err(crate::safety::budget_exceeded(
            "a2a_broadcast",
            format!(
                "{} agents are registered; a broadcast reaches at most {A2A_BROADCAST_RECIPIENTS_MAX}",
                agents.len()
            ),
            "send to the agents by name with a2a_send",
        ));
    }
    let mut messages = A2A_MESSAGES
        .write()
        .map_err(|_| crate::safety::lock_poisoned("a2a_broadcast", "the A2A message queue"))?;
    // Check every recipient's queue before pushing to any of them.
    for agent in &agents {
        if messages.get(agent).map_or(0, Vec::len) >= A2A_QUEUE_MAX {
            return Err(crate::safety::budget_exceeded(
                "a2a_broadcast",
                format!("{agent} has {A2A_QUEUE_MAX} undelivered messages"),
                "a2a_receive drains an agent's queue",
            ));
        }
    }
    for agent in &agents {
        messages
            .entry(agent.clone())
            .or_default()
            .push(message.clone());
    }
    let mut result = BTreeMap::new();
    result.insert("broadcast".to_string(), Value::Bool(true));
    result.insert("recipients".to_string(), Value::Int(agents.len() as i64));
    Ok(Value::Record(result))
}

/// a2a.discover() - Discover available agents
fn bi_a2a_discover(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let registry = A2A_REGISTRY.read().unwrap();
    let agents: Vec<Value> = registry
        .iter()
        .map(|(name, info)| {
            let mut agent = info.clone();
            agent.insert("name".to_string(), Value::Str(name.clone()));
            Value::Record(agent)
        })
        .collect();
    Ok(Value::Array(agents))
}

/// a2a.register(name, info?) - Register an agent
fn bi_a2a_register(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("a2a_register", &input)?;
    if args.is_empty() {
        return Err(crate::safety::arg_err("a2a.register: requires agent name"));
    }
    if args.len() > 2 {
        return Err(crate::safety::bad_arg(
            "a2a_register",
            "a name and an optional info Record",
            &format!("{} arguments", args.len()),
        ));
    }
    let name = collab_text_arg("a2a_register", "name", args.first(), 128)?;
    // An info that is not a Record used to be replaced by an empty one without
    // a word. Refuse it instead.
    let info = match args.get(1) {
        None | Some(Value::Null) => BTreeMap::new(),
        Some(Value::Record(rec)) => rec.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "a2a_register",
                "info: a Record",
                other.type_name(),
            ))
        }
    };
    let info_size = Value::Record(info.clone()).to_display_string().len();
    if info_size > A2A_INFO_MAX {
        return Err(crate::safety::budget_exceeded(
            "a2a_register",
            format!("info is {info_size} bytes; at most {A2A_INFO_MAX} are kept"),
            "register a name and a reference to the details",
        ));
    }
    let mut registry = A2A_REGISTRY
        .write()
        .map_err(|_| crate::safety::lock_poisoned("a2a_register", "the A2A agent registry"))?;
    // Re-registering a name replaces its info and does not grow the registry.
    if !registry.contains_key(&name) && registry.len() >= A2A_AGENTS_MAX {
        return Err(crate::safety::budget_exceeded(
            "a2a_register",
            format!("{A2A_AGENTS_MAX} agents are already registered"),
            "a2a_unregister an agent that is no longer running",
        ));
    }
    registry.insert(name.clone(), info);
    let mut result = BTreeMap::new();
    result.insert("registered".to_string(), Value::Bool(true));
    result.insert("name".to_string(), Value::Str(name.to_string()));
    Ok(Value::Record(result))
}

/// a2a.unregister(name) - Unregister an agent
fn bi_a2a_unregister(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if args.is_empty() {
        return Err(crate::safety::arg_err(
            "a2a.unregister: requires agent name",
        ));
    }
    let name = args[0]
        .as_str()
        .map_err(|_| crate::safety::arg_err("a2a.unregister: name must be a string"))?;
    let mut registry = A2A_REGISTRY.write().unwrap();
    let removed = registry.remove(name).is_some();
    let mut messages = A2A_MESSAGES.write().unwrap();
    messages.remove(name);
    let mut result = BTreeMap::new();
    result.insert("unregistered".to_string(), Value::Bool(removed));
    result.insert("name".to_string(), Value::Str(name.to_string()));
    Ok(Value::Record(result))
}

/// a2a.status() - Get A2A subsystem status
fn bi_a2a_status(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let registry = A2A_REGISTRY.read().unwrap();
    let messages = A2A_MESSAGES.read().unwrap();
    let pending_count: usize = messages.values().map(|v| v.len()).sum();
    let mut result = BTreeMap::new();
    result.insert("active".to_string(), Value::Bool(true));
    result.insert("agents".to_string(), Value::Int(registry.len() as i64));
    result.insert(
        "pending_messages".to_string(),
        Value::Int(pending_count as i64),
    );
    Ok(Value::Record(result))
}

/// a2a.agents() - List all registered agents
fn bi_a2a_agents(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let registry = A2A_REGISTRY.read().unwrap();
    let agents: Vec<Value> = registry
        .keys()
        .map(|name| Value::Str(name.clone()))
        .collect();
    Ok(Value::Array(agents))
}

// ===================== NANDA (Consensus) Protocol =====================

// A local tally, not a distributed consensus. A proposal names its electorate
// (`electorate`, an Int 1..=1024, default 1) and each vote is one ballot cast
// against it. Nothing identifies the voter, so the electorate is the caller's
// assertion and one caller can cast every ballot. Quorum is half the
// electorate: a proposal commits only when that many ballots are in and the
// approval ratio is at least its threshold. A decided proposal takes no
// further ballots. The store holds at most NANDA_MAX_PROPOSALS and evicts the
// oldest decided proposal when a new one needs the room.

const NANDA_MAX_PROPOSALS: usize = 256;
const NANDA_MAX_ELECTORATE: i64 = 1024;
const NANDA_MAX_DATA_FIELDS: usize = 64;
/// Keys the proposal record owns. A caller's `data` cannot overwrite them.
const NANDA_RESERVED: &[&str] = &[
    "id",
    "name",
    "threshold",
    "electorate",
    "status",
    "votes_cast",
    "approvals",
];

struct NandaProposal {
    seq: u64,
    name: String,
    threshold: f64,
    electorate: usize,
    ballots: Vec<bool>,
    status: &'static str,
    data: BTreeMap<String, Value>,
}

static NANDA_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

lazy_static::lazy_static! {
    static ref NANDA_PROPOSALS: std::sync::RwLock<BTreeMap<String, NandaProposal>> = {
        std::sync::RwLock::new(BTreeMap::new())
    };
}

fn nanda_uuid() -> String {
    use rand::Rng;
    let mut rng = rand::thread_rng();
    let bytes: [u8; 16] = rng.gen();
    format!(
        "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
        u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
        u16::from_be_bytes([bytes[4], bytes[5]]),
        u16::from_be_bytes([bytes[6], bytes[7]]) & 0x0fff,
        (u16::from_be_bytes([bytes[8], bytes[9]]) & 0x3fff) | 0x8000,
        u64::from_be_bytes([
            0, 0, bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]
        ])
    )
}

/// `(cast, approvals)` for a proposal.
fn nanda_tally(p: &NandaProposal) -> (usize, usize) {
    let cast = p.ballots.len();
    let approvals = p.ballots.iter().filter(|b| **b).count();
    (cast, approvals)
}

/// Half the electorate has balloted. An electorate of at least one means a
/// quorum always has at least one ballot behind it, so no ratio divides by zero.
fn nanda_has_quorum(p: &NandaProposal) -> bool {
    2 * p.ballots.len() >= p.electorate
}

fn nanda_record(id: &str, p: &NandaProposal) -> BTreeMap<String, Value> {
    let (cast, approvals) = nanda_tally(p);
    let mut rec = p.data.clone();
    rec.insert("id".to_string(), Value::Str(id.to_string()));
    rec.insert("name".to_string(), Value::Str(p.name.clone()));
    rec.insert("threshold".to_string(), Value::Float(p.threshold));
    rec.insert("electorate".to_string(), Value::Int(p.electorate as i64));
    rec.insert("status".to_string(), Value::Str(p.status.to_string()));
    rec.insert("votes_cast".to_string(), Value::Int(cast as i64));
    rec.insert("approvals".to_string(), Value::Int(approvals as i64));
    rec
}

/// Refuse pipeline input for a builtin that documents no subject. What was
/// piped in would otherwise be dropped without a word.
fn refuse_piped_subject(builtin: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            builtin,
            "no pipeline input",
            "piped input",
        ));
    }
    Ok(())
}

/// A required, non-empty String of at most `max` bytes.
fn collab_text_arg(builtin: &str, what: &str, v: Option<&Value>, max: usize) -> Result<String> {
    match v {
        Some(Value::Str(s)) if !s.trim().is_empty() && s.len() <= max => Ok(s.clone()),
        Some(Value::Str(s)) if s.len() > max => Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: a String of at most {max} bytes"),
            &format!("a String of {} bytes", s.len()),
        )),
        Some(Value::Str(_)) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: a non-empty String"),
            "an empty String",
        )),
        other => Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: a non-empty String"),
            other.map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

/// The value of a scalar as it should appear in a refusal: `0.7`, not `Float`.
fn collab_got(v: &Value) -> String {
    match v {
        Value::Int(n) => n.to_string(),
        Value::Float(x) => crate::value::float_text(*x),
        other => other.type_name().to_string(),
    }
}

/// nanda_propose(name, data) - Open a proposal in the local tally.
/// `data.threshold` is a Float in (0, 1] (default 0.5); `data.electorate` an
/// Int in 1..=1024 (default 1). Other fields are kept on the record.
fn bi_nanda_propose(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("nanda_propose", &input)?;
    let name = collab_text_arg("nanda_propose", "name", args.first(), 256)?;
    let data = match args.get(1) {
        Some(Value::Record(r)) => r,
        other => {
            return Err(crate::safety::bad_arg(
                "nanda_propose",
                "data: Record",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let threshold = match data.get("threshold") {
        None => 0.5,
        Some(Value::Float(t)) if *t > 0.0 && *t <= 1.0 => *t,
        Some(Value::Int(1)) => 1.0,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "nanda_propose",
                "threshold: a Float in (0, 1]",
                &collab_got(other),
            ))
        }
    };
    let electorate = match data.get("electorate") {
        None => 1,
        Some(Value::Int(n)) if (1..=NANDA_MAX_ELECTORATE).contains(n) => *n as usize,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "nanda_propose",
                "electorate: an Int in 1..=1024",
                &collab_got(other),
            ))
        }
    };
    if data.len() > NANDA_MAX_DATA_FIELDS {
        return Err(crate::safety::budget_exceeded(
            "nanda_propose",
            format!(
                "nanda_propose: data has {} fields; a proposal holds at most {NANDA_MAX_DATA_FIELDS}",
                data.len()
            ),
            "send the proposal's detail in fewer fields",
        ));
    }
    let mut extra = data.clone();
    for key in NANDA_RESERVED {
        extra.remove(*key);
    }

    let id = format!("prop_{}", nanda_uuid());
    let mut proposals = NANDA_PROPOSALS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("nanda_propose", "the NANDA proposal table"))?;
    if proposals.len() >= NANDA_MAX_PROPOSALS {
        let oldest_decided = proposals
            .iter()
            .filter(|(_, p)| p.status != "pending")
            .min_by_key(|(_, p)| p.seq)
            .map(|(k, _)| k.clone());
        match oldest_decided {
            Some(k) => {
                proposals.remove(&k);
            }
            None => {
                return Err(crate::safety::budget_exceeded(
                    "nanda_propose",
                    format!(
                        "nanda_propose: {NANDA_MAX_PROPOSALS} proposals are pending and none is decided"
                    ),
                    "commit or abort a pending proposal, then propose again",
                ))
            }
        }
    }
    let proposal = NandaProposal {
        seq: NANDA_SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
        name,
        threshold,
        electorate,
        ballots: Vec::new(),
        status: "pending",
        data: extra,
    };
    let rec = nanda_record(&id, &proposal);
    proposals.insert(id, proposal);
    Ok(Value::Record(rec))
}

/// nanda_vote(proposal_id, approve) - Cast one ballot on a pending proposal.
fn bi_nanda_vote(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("nanda_vote", &input)?;
    let proposal_id = collab_text_arg("nanda_vote", "proposal_id", args.first(), 128)?;
    let approve = match args.get(1) {
        Some(Value::Bool(b)) => *b,
        other => {
            return Err(crate::safety::bad_arg(
                "nanda_vote",
                "approve: Bool",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let mut proposals = NANDA_PROPOSALS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("nanda_vote", "the NANDA proposal table"))?;
    let p = proposals
        .get_mut(&proposal_id)
        .ok_or_else(|| crate::safety::not_found("nanda_vote", "proposal", &proposal_id))?;
    if p.status != "pending" {
        return Err(crate::safety::bad_state(
            "nanda_vote",
            &format!(
                "proposal {proposal_id} is {}; a decided proposal takes no votes",
                p.status
            ),
            "nanda_status",
        ));
    }
    if p.ballots.len() >= p.electorate {
        return Err(crate::safety::budget_exceeded(
            "nanda_vote",
            format!(
                "nanda_vote: all {} ballots of {proposal_id} are cast",
                p.electorate
            ),
            "a proposal takes exactly its electorate's ballots; commit it or propose another",
        ));
    }
    p.ballots.push(approve);
    let mut rec = BTreeMap::new();
    rec.insert("voted".to_string(), Value::Bool(true));
    rec.insert("proposal_id".to_string(), Value::Str(proposal_id));
    rec.insert("approve".to_string(), Value::Bool(approve));
    rec.insert("ballot".to_string(), Value::Int(p.ballots.len() as i64));
    rec.insert("votes_cast".to_string(), Value::Int(p.ballots.len() as i64));
    rec.insert("electorate".to_string(), Value::Int(p.electorate as i64));
    Ok(Value::Record(rec))
}

/// nanda_commit(proposal_id) - Commit a pending proposal with quorum and an
/// approval ratio at or above its threshold. Below the threshold it is rejected.
fn bi_nanda_commit(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("nanda_commit", &input)?;
    let proposal_id = collab_text_arg("nanda_commit", "proposal_id", args.first(), 128)?;
    let mut proposals = NANDA_PROPOSALS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("nanda_commit", "the NANDA proposal table"))?;
    let p = proposals
        .get_mut(&proposal_id)
        .ok_or_else(|| crate::safety::not_found("nanda_commit", "proposal", &proposal_id))?;
    if p.status != "pending" {
        return Err(crate::safety::bad_state(
            "nanda_commit",
            &format!(
                "proposal {proposal_id} is {}; only a pending proposal commits",
                p.status
            ),
            "nanda_status",
        ));
    }
    if !nanda_has_quorum(p) {
        let (cast, _) = nanda_tally(p);
        return Err(crate::safety::bad_state(
            "nanda_commit",
            &format!(
                "no quorum: {cast} of {} ballots are cast and at least half are needed",
                p.electorate
            ),
            "nanda_vote",
        ));
    }
    let (cast, approvals) = nanda_tally(p);
    let ratio = approvals as f64 / cast as f64;
    if ratio < p.threshold {
        p.status = "rejected";
        return Err(crate::safety::policy_deny(
            "nanda_commit",
            format!(
                "consensus not reached: approval {:.0}% is below the threshold {:.0}%; {proposal_id} is now rejected",
                ratio * 100.0,
                p.threshold * 100.0
            ),
            "a rejected proposal takes no further ballots; propose again",
        ));
    }
    p.status = "committed";
    let mut rec = BTreeMap::new();
    rec.insert("committed".to_string(), Value::Bool(true));
    rec.insert("proposal_id".to_string(), Value::Str(proposal_id));
    rec.insert("approval_ratio".to_string(), Value::Float(ratio));
    rec.insert("threshold".to_string(), Value::Float(p.threshold));
    rec.insert("votes_cast".to_string(), Value::Int(cast as i64));
    rec.insert("electorate".to_string(), Value::Int(p.electorate as i64));
    Ok(Value::Record(rec))
}

/// nanda_abort(proposal_id) - Abort a pending proposal.
fn bi_nanda_abort(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("nanda_abort", &input)?;
    let proposal_id = collab_text_arg("nanda_abort", "proposal_id", args.first(), 128)?;
    let mut proposals = NANDA_PROPOSALS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("nanda_abort", "the NANDA proposal table"))?;
    let p = proposals
        .get_mut(&proposal_id)
        .ok_or_else(|| crate::safety::not_found("nanda_abort", "proposal", &proposal_id))?;
    if p.status != "pending" {
        return Err(crate::safety::bad_state(
            "nanda_abort",
            &format!(
                "proposal {proposal_id} is {}; only a pending proposal aborts",
                p.status
            ),
            "nanda_status",
        ));
    }
    p.status = "aborted";
    let mut rec = BTreeMap::new();
    rec.insert("aborted".to_string(), Value::Bool(true));
    rec.insert("proposal_id".to_string(), Value::Str(proposal_id));
    rec.insert("status".to_string(), Value::Str("aborted".to_string()));
    Ok(Value::Record(rec))
}

/// nanda_status(proposal_id?) - One proposal's record, or every proposal's.
fn bi_nanda_status(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("nanda_status", &input)?;
    let proposals = NANDA_PROPOSALS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("nanda_status", "the NANDA proposal table"))?;
    match args.first() {
        None => Ok(Value::Array(
            proposals
                .iter()
                .map(|(id, p)| Value::Record(nanda_record(id, p)))
                .collect(),
        )),
        Some(Value::Str(id)) => {
            let p = proposals
                .get(id)
                .ok_or_else(|| crate::safety::not_found("nanda_status", "proposal", id))?;
            Ok(Value::Record(nanda_record(id, p)))
        }
        Some(other) => Err(crate::safety::bad_arg(
            "nanda_status",
            "proposal_id: String",
            other.type_name(),
        )),
    }
}

/// nanda_consensus(proposal_id) - Whether the tally reaches consensus now: a
/// quorum of ballots, and an approval ratio at or above the threshold.
fn bi_nanda_consensus(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("nanda_consensus", &input)?;
    let proposal_id = collab_text_arg("nanda_consensus", "proposal_id", args.first(), 128)?;
    let proposals = NANDA_PROPOSALS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("nanda_consensus", "the NANDA proposal table"))?;
    let p = proposals
        .get(&proposal_id)
        .ok_or_else(|| crate::safety::not_found("nanda_consensus", "proposal", &proposal_id))?;
    let (cast, approvals) = nanda_tally(p);
    let ratio = if cast > 0 {
        approvals as f64 / cast as f64
    } else {
        0.0
    };
    let quorum = nanda_has_quorum(p);
    let mut rec = BTreeMap::new();
    rec.insert(
        "reached".to_string(),
        Value::Bool(quorum && cast > 0 && ratio >= p.threshold),
    );
    rec.insert("quorum_reached".to_string(), Value::Bool(quorum));
    rec.insert("approval_ratio".to_string(), Value::Float(ratio));
    rec.insert("threshold".to_string(), Value::Float(p.threshold));
    rec.insert("total_votes".to_string(), Value::Int(cast as i64));
    rec.insert("approvals".to_string(), Value::Int(approvals as i64));
    rec.insert("electorate".to_string(), Value::Int(p.electorate as i64));
    rec.insert("status".to_string(), Value::Str(p.status.to_string()));
    Ok(Value::Record(rec))
}

/// nanda_quorum(proposal_id) - How much of the electorate has balloted.
fn bi_nanda_quorum(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("nanda_quorum", &input)?;
    let proposal_id = collab_text_arg("nanda_quorum", "proposal_id", args.first(), 128)?;
    let proposals = NANDA_PROPOSALS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("nanda_quorum", "the NANDA proposal table"))?;
    let p = proposals
        .get(&proposal_id)
        .ok_or_else(|| crate::safety::not_found("nanda_quorum", "proposal", &proposal_id))?;
    let (cast, _) = nanda_tally(p);
    let mut rec = BTreeMap::new();
    rec.insert(
        "quorum_reached".to_string(),
        Value::Bool(nanda_has_quorum(p)),
    );
    rec.insert(
        "participation".to_string(),
        Value::Float(cast as f64 / p.electorate as f64),
    );
    rec.insert("votes_cast".to_string(), Value::Int(cast as i64));
    rec.insert("electorate".to_string(), Value::Int(p.electorate as i64));
    Ok(Value::Record(rec))
}

// ============== AI CODING ASSISTANT BUILTINS ==============

// Git module implementations
//
// Every git builtin refuses pipeline input and surplus arguments (the
// declarations in src/signature.rs enforce the arity and types), runs git
// with an argv vector and no shell, and turns a failed git into a coded
// error: E_BAD_STATE outside a repository, E_TOOL_FAILED with the tail of
// what git printed otherwise. None answers a failure with false, "" or [].

/// `git`, with the repository's fsmonitor hook switched off. `core.fsmonitor`
/// names a program that `git status` and `git diff` run, so a repository's
/// own config could otherwise make a ReadLocal builtin execute code. It is a
/// speed-up only; git answers the same without it.
fn git_command() -> std::process::Command {
    let mut cmd = crate::safety::child_command("git");
    cmd.args(["-c", "core.fsmonitor=false"]);
    cmd
}

/// Refuse pipeline input: a git builtin acts on the repository, and what was
/// piped in would otherwise be dropped without a word.
fn git_refuse_input(builtin: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            builtin,
            "no pipeline input",
            "piped input",
        ));
    }
    Ok(())
}

/// The last 4 KiB of what git printed when it failed: stderr, or stdout when
/// stderr is empty (`git commit` says "nothing to commit" on stdout alone).
fn git_failure_tail(output: &std::process::Output) -> String {
    const TAIL: usize = 4096;
    let raw = if output.stderr.iter().all(|b| b.is_ascii_whitespace()) {
        &output.stdout
    } else {
        &output.stderr
    };
    let text = String::from_utf8_lossy(raw);
    if text.len() <= TAIL {
        return text.into_owned();
    }
    let mut start = text.len() - TAIL;
    while !text.is_char_boundary(start) {
        start += 1;
    }
    format!("...{}", &text[start..])
}

/// `git` exited non-zero. Every git builtin read stdout and ignored the
/// status, so outside a repository -- where git prints only to stderr --
/// `git_status()` was `[]`, `git_branch()` was `""` and `git_log()` was `[]`,
/// all at exit 0: "clean", "detached" and "no history", none of them true.
fn git_succeeded(builtin: &str, output: &std::process::Output, dir: &str) -> Result<()> {
    if output.status.success() {
        return Ok(());
    }
    // Ask git rather than read its stderr: outside a repository `git status`
    // says "not a git repository", `git diff` says "Not a git repository" and
    // prints usage, `git diff --staged` says only "unknown option", and all
    // of it is translated under a non-English locale.
    let mut cmd = git_command();
    cmd.args(["rev-parse", "--is-inside-work-tree"]);
    cmd.current_dir(dir);
    let in_repo = bounded_cmd_output("git_succeeded", "git", cmd, TOOL_DEADLINE_SECS)
        .is_ok_and(|o| o.status.success());
    if !in_repo {
        return Err(crate::safety::bad_state_with_hint(
            builtin,
            "the working directory is not inside a git repository",
            "cd into a repository (or pass its path where the builtin takes one)",
        ));
    }
    Err(crate::safety::tool_failed(
        builtin,
        "git",
        output.status.code(),
        &git_failure_tail(output),
    ))
}

/// The directory a read-only git builtin runs in. It is the child's working
/// directory rather than an argument, and spawning into a missing directory
/// fails the same way a missing git does, so it is named here first.
fn git_dir_arg(builtin: &str, path: &str) -> Result<String> {
    if std::path::Path::new(path).is_dir() {
        Ok(path.to_string())
    } else {
        Err(crate::safety::not_found(builtin, "directory", path))
    }
}

/// The first argument as a ref, branch or commit name. Empty and NUL-bearing
/// values are refused before they reach argv. The caller refuses a leading
/// '-' at its own spawn site, where `reject_option_like` must be visible.
fn git_ref_arg(builtin: &str, args: &[Value], what: &str) -> Result<String> {
    let value = match args.first() {
        Some(v) => expect_string(builtin, v)?.to_string(),
        None => return Err(crate::safety::arg_err(format!("{builtin} requires {what}"))),
    };
    if value.trim().is_empty() || value.contains('\0') {
        return Err(crate::safety::bad_arg(builtin, what, &format!("{value:?}")));
    }
    Ok(value)
}

fn bi_git_status(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_status", &input)?;
    let path = match args.first() {
        Some(v) => expect_string("git_status", v)?.to_string(),
        None => ".".to_string(),
    };
    let path = git_dir_arg("git_status", &path)?;
    let mut cmd = git_command();
    cmd.args(["status", "--porcelain", "-b"]);
    cmd.current_dir(&path);
    let output = bounded_cmd_output("git_status", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_status", &output, &path)?;
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let lines: Vec<Value> = stdout.lines().map(|l| Value::Str(l.to_string())).collect();
    Ok(Value::Array(lines))
}

fn bi_git_diff(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_diff", &input)?;
    let path = match args.first() {
        Some(v) => expect_string("git_diff", v)?.to_string(),
        None => ".".to_string(),
    };
    let path = git_dir_arg("git_diff", &path)?;
    let mut cmd = git_command();
    cmd.args(["diff", "--no-ext-diff", "--no-textconv"]);
    cmd.current_dir(&path);
    let output = bounded_cmd_output("git_diff", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_diff", &output, &path)?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).to_string(),
    ))
}

fn bi_git_diff_staged(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_diff_staged", &input)?;
    let path = match args.first() {
        Some(v) => expect_string("git_diff_staged", v)?.to_string(),
        None => ".".to_string(),
    };
    let path = git_dir_arg("git_diff_staged", &path)?;
    let mut cmd = git_command();
    cmd.args(["diff", "--no-ext-diff", "--no-textconv", "--staged"]);
    cmd.current_dir(&path);
    let output = bounded_cmd_output("git_diff_staged", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_diff_staged", &output, &path)?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).to_string(),
    ))
}

fn bi_git_log(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_log", &input)?;
    let count = match args.first() {
        Some(v) => expect_int("git_log", v)?,
        None => 10,
    };
    // The declaration bounds it to 1..=10000. It is interpolated into a
    // `-N` flag, so a negative count (`--5`) must never reach git.
    if !(1..=10_000).contains(&count) {
        return Err(crate::safety::bad_arg(
            "git_log",
            "count: Int in 1..=10000",
            &format!("{count}"),
        ));
    }
    let mut cmd = git_command();
    cmd.args(["log", &format!("-{}", count), "--oneline"]);
    let output = bounded_cmd_output("git_log", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_log", &output, ".")?;
    let lines: Vec<Value> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(lines))
}

fn bi_git_blame(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_blame", &input)?;
    let file = git_ref_arg("git_blame", &args, "a file path")?;
    crate::safety::reject_option_like("git_blame", std::slice::from_ref(&file))?;
    let mut cmd = git_command();
    cmd.args(["blame", "--", &file]);
    let output = bounded_cmd_output("git_blame", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_blame", &output, ".")?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).to_string(),
    ))
}

fn bi_git_branch(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = git_command();
    cmd.args(["branch", "--show-current"]);
    let output = bounded_cmd_output("git_branch", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_branch", &output, ".")?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).trim().to_string(),
    ))
}

fn bi_git_branches(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = git_command();
    cmd.args(["branch", "-a"]);
    let output = bounded_cmd_output("git_branches", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_branches", &output, ".")?;
    let branches: Vec<Value> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|l| Value::Str(l.trim().trim_start_matches("* ").to_string()))
        .collect();
    Ok(Value::Array(branches))
}

fn bi_git_checkout(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_checkout", &input)?;
    let branch = git_ref_arg("git_checkout", &args, "a branch name")?;
    crate::safety::reject_option_like("git_checkout", std::slice::from_ref(&branch))?;
    // The `--` makes git resolve the name as a revision only. Without it,
    // `git checkout README.md` restores that file from the index and silently
    // discards its uncommitted edits. With it, a path is "invalid reference".
    let mut cmd = git_command();
    cmd.args(["checkout", &branch, "--"]);
    let output = bounded_cmd_output("git_checkout", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_checkout", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_commit(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_commit", &input)?;
    let msg = match args.first() {
        Some(v) => expect_string("git_commit", v)?.to_string(),
        None => return Err(crate::safety::arg_err("commit message required")),
    };
    if msg.contains('\0') {
        return Err(crate::safety::bad_arg(
            "git_commit",
            "a message without NUL",
            "NUL",
        ));
    }
    // The message is the argument of `-m`, which consumes it, so a message
    // beginning with '-' is text, not an option.
    let mut cmd = git_command();
    cmd.args(["commit", "-m", &msg]);
    let output = bounded_cmd_output("git_commit", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_commit", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_add", &input)?;
    // The declaration requires at least one path and types each one as a
    // String, so a non-string is refused rather than dropped from the list.
    let files: Vec<String> = args
        .iter()
        .map(|v| expect_string("git_add", v).map(str::to_string))
        .collect::<Result<_>>()?;
    if files.is_empty() {
        return Err(crate::safety::arg_err("git_add requires at least one path"));
    }
    crate::safety::reject_option_like("git_add", &files)?;
    if let Some(bad) = files.iter().find(|f| f.contains('\0')) {
        return Err(crate::safety::bad_arg(
            "git_add",
            "paths without NUL",
            &format!("{bad:?}"),
        ));
    }
    let mut cmd = git_command();
    cmd.arg("add");
    cmd.arg("--");
    cmd.args(&files);
    let output = bounded_cmd_output("git_add", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_add", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_reset(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_reset", &input)?;
    let target = match args.first() {
        Some(v) => expect_string("git_reset", v)?.to_string(),
        None => "--mixed".to_string(),
    };
    const MODES: [&str; 4] = ["--soft", "--mixed", "--hard", "--keep"];
    // A leading '-' is an option and must be one of the four modes; anything
    // else is a revision. Either way it is an argv element, never a flag that
    // git would take from a caller's string.
    if target.starts_with('-') {
        if !MODES.contains(&target.as_str()) {
            return Err(crate::safety::bad_arg(
                "git_reset",
                "a mode: --soft, --mixed, --hard or --keep",
                &format!("{target:?}"),
            ));
        }
    } else if target.trim().is_empty() || target.contains('\0') {
        return Err(crate::safety::bad_arg(
            "git_reset",
            "a mode or a revision",
            &format!("{target:?}"),
        ));
    }
    // A revision is followed by `--`, so git never reads it as a pathspec
    // position it could mistake for an option.
    let mut argv = vec!["reset", target.as_str()];
    if !target.starts_with('-') {
        argv.push("--");
    }
    let mut cmd = git_command();
    cmd.args(&argv);
    let output = bounded_cmd_output("git_reset", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_reset", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_stash(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_stash", &input)?;
    let mut cmd = git_command();
    cmd.args(["stash"]);
    let output = bounded_cmd_output("git_stash", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_stash", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_stash_pop(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_stash_pop", &input)?;
    let mut cmd = git_command();
    cmd.args(["stash", "pop"]);
    let output = bounded_cmd_output("git_stash_pop", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_stash_pop", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_stash_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = git_command();
    cmd.args(["stash", "list"]);
    let output = bounded_cmd_output("git_stash_list", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_stash_list", &output, ".")?;
    let stashes: Vec<Value> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(stashes))
}

fn bi_git_remote(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = git_command();
    cmd.args(["remote", "-v"]);
    let output = bounded_cmd_output("git_remote", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_remote", &output, ".")?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).to_string(),
    ))
}

fn bi_git_fetch(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_fetch", &input)?;
    crate::safety::check_git_remote_egress("git_fetch", false)?;
    let mut cmd = git_command();
    cmd.args(["fetch"]);
    let output = bounded_cmd_output("git_fetch", "git", cmd, NETWORK_DEADLINE_SECS)?;
    git_succeeded("git_fetch", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_pull(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_pull", &input)?;
    crate::safety::check_git_remote_egress("git_pull", false)?;
    let mut cmd = git_command();
    cmd.args(["pull"]);
    let output = bounded_cmd_output("git_pull", "git", cmd, NETWORK_DEADLINE_SECS)?;
    git_succeeded("git_pull", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_push(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_push", &input)?;
    crate::safety::check_git_remote_egress("git_push", true)?;
    let mut cmd = git_command();
    cmd.args(["push"]);
    let output = bounded_cmd_output("git_push", "git", cmd, NETWORK_DEADLINE_SECS)?;
    git_succeeded("git_push", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_merge(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_merge", &input)?;
    let branch = git_ref_arg("git_merge", &args, "a branch name")?;
    crate::safety::reject_option_like("git_merge", std::slice::from_ref(&branch))?;
    // --no-edit: never open an editor for the merge message.
    let mut cmd = git_command();
    cmd.args(["merge", "--no-edit", &branch]);
    let output = bounded_cmd_output("git_merge", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_merge", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_rebase(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_rebase", &input)?;
    let branch = git_ref_arg("git_rebase", &args, "a branch name")?;
    crate::safety::reject_option_like("git_rebase", std::slice::from_ref(&branch))?;
    let mut cmd = git_command();
    cmd.args(["rebase", &branch]);
    let output = bounded_cmd_output("git_rebase", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_rebase", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_cherry_pick(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_cherry_pick", &input)?;
    let commit = git_ref_arg("git_cherry_pick", &args, "a commit")?;
    crate::safety::reject_option_like("git_cherry_pick", std::slice::from_ref(&commit))?;
    let mut cmd = git_command();
    cmd.args(["cherry-pick", &commit]);
    let output = bounded_cmd_output("git_cherry_pick", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_cherry_pick", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_git_tags(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = git_command();
    cmd.args(["tag", "-l"]);
    let output = bounded_cmd_output("git_tags", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_tags", &output, ".")?;
    let tags: Vec<Value> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(tags))
}

fn bi_git_show(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_show", &input)?;
    let commit = if args.is_empty() {
        "HEAD".to_string()
    } else {
        let value = git_ref_arg("git_show", &args, "a commit")?;
        crate::safety::reject_option_like("git_show", std::slice::from_ref(&value))?;
        value
    };
    let mut cmd = git_command();
    cmd.args(["show", "--no-ext-diff", "--no-textconv", &commit]);
    let output = bounded_cmd_output("git_show", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_show", &output, ".")?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).to_string(),
    ))
}

fn bi_git_rev_parse(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_rev_parse", &input)?;
    let rev = if args.is_empty() {
        "HEAD".to_string()
    } else {
        let value = git_ref_arg("git_rev_parse", &args, "a revision")?;
        crate::safety::reject_option_like("git_rev_parse", std::slice::from_ref(&value))?;
        value
    };
    let mut cmd = git_command();
    cmd.args(["rev-parse", &rev]);
    let output = bounded_cmd_output("git_rev_parse", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_rev_parse", &output, ".")?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).trim().to_string(),
    ))
}

fn bi_git_root(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = git_command();
    cmd.args(["rev-parse", "--show-toplevel"]);
    let output = bounded_cmd_output("git_root", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_root", &output, ".")?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).trim().to_string(),
    ))
}

fn bi_git_ignore(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_ignore", &input)?;
    let pattern = match args.first() {
        Some(v) => expect_string("git_ignore", v)?.to_string(),
        None => return Err(crate::safety::arg_err("pattern required")),
    };
    // One pattern per call: a newline in it wrote several.
    if pattern.contains(['\n', '\r']) || pattern.trim().is_empty() {
        return Err(crate::safety::bad_arg(
            "git_ignore",
            "one non-empty pattern without line breaks",
            &format!("{pattern:?}"),
        ));
    }
    // A .gitignore written outside a repository is a file nobody asked for,
    // so the refusal is the same one the other git builtins give.
    let mut cmd = git_command();
    cmd.args(["rev-parse", "--is-inside-work-tree"]);
    let inside = bounded_cmd_output("git_ignore", "git", cmd, TOOL_DEADLINE_SECS)?;
    if !(inside.status.success() && inside.stdout.starts_with(b"true")) {
        return Err(crate::safety::bad_state_with_hint(
            "git_ignore",
            "the working directory is not inside a git repository",
            "cd into a repository",
        ));
    }
    // The repository is the working directory's, so the file is
    // `<cwd>/.gitignore`, named absolutely: the jail judges that file (a
    // relative name would be judged in the workspace while the write landed in
    // the working directory), and the journal is given the same path.
    let cwd =
        std::env::current_dir().map_err(|e| crate::safety::fs_error("git_ignore", ".", &e))?;
    let path = guard_local_write("git_ignore", &cwd.join(".gitignore").to_string_lossy())?;
    // A .gitignore that exists but cannot be read is an error, not an empty
    // file: treating it as empty and writing would replace its contents.
    let existing = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(crate::safety::fs_error("git_ignore", &path, &e)),
    };
    // Idempotent: the same pattern was appended again on every call.
    if existing.lines().any(|l| l.trim() == pattern.trim()) {
        return Ok(Value::Bool(false));
    }
    let mut text = existing;
    if !text.is_empty() && !text.ends_with('\n') {
        text.push('\n'); // or the pattern was glued onto the last line
    }
    text.push_str(pattern.trim());
    text.push('\n');
    crate::safety::refuse_hard_linked_write("git_ignore", &path)?;
    crate::tx::snapshot(&path);
    use std::io::Write as _;
    let mut file = crate::safety::open_in_place("git_ignore", std::path::Path::new(&path), false)
        .map_err(|e| crate::safety::in_place_error("git_ignore", &path, e))?;
    file.write_all(text.as_bytes())
        .map_err(|e| crate::safety::fs_error("git_ignore", &path, &e))?;
    Ok(Value::Bool(true))
}

fn bi_git_clean(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("git_clean", &input)?;
    // A non-Bool used to become a dry run without a word. The declaration
    // types it, and the match below refuses anything else too.
    let dry_run = match args.first() {
        Some(Value::Bool(b)) => *b,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "git_clean",
                "dry_run: Bool",
                other.type_name(),
            ))
        }
        None => true,
    };
    let flag = if dry_run { "-n" } else { "-f" };
    let mut cmd = git_command();
    cmd.args(["clean", "-d", flag]);
    let output = bounded_cmd_output("git_clean", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("git_clean", &output, ".")?;
    let files: Vec<Value> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(files))
}

#[path = "source_navigation.rs"]
mod source_navigation;

// Code module implementations
fn bi_code_parse(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file path required"))?;
    let content = read_text_capped("code_parse", &file)?;
    let lines = content.lines().count();
    let mut result = BTreeMap::new();
    result.insert("path".to_string(), Value::Str(file));
    result.insert("lines".to_string(), Value::Int(lines as i64));
    result.insert("size".to_string(), Value::Int(content.len() as i64));
    Ok(Value::Record(result))
}

fn bi_code_symbols(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file path required"))?;
    let content = read_text_capped("code_symbols", &file)?;
    let mut symbols = Vec::new();
    for (i, line) in content.lines().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("fn ")
            || trimmed.starts_with("pub fn ")
            || trimmed.starts_with("struct ")
            || trimmed.starts_with("pub struct ")
            || trimmed.starts_with("enum ")
            || trimmed.starts_with("pub enum ")
            || trimmed.starts_with("impl ")
            || trimmed.starts_with("trait ")
            || trimmed.starts_with("def ")
            || trimmed.starts_with("class ")
            || trimmed.starts_with("function ")
            || trimmed.starts_with("const ")
        {
            let mut sym = BTreeMap::new();
            sym.insert("line".to_string(), Value::Int((i + 1) as i64));
            sym.insert("text".to_string(), Value::Str(trimmed.to_string()));
            symbols.push(Value::Record(sym));
        }
    }
    Ok(Value::Array(symbols))
}

fn bi_code_outline(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    bi_code_symbols(args, input)
}

fn bi_code_references(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    source_navigation::analyze("code_references", args, input)
}

fn bi_code_definition(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    source_navigation::analyze("code_definition", args, input)
}

fn bi_code_imports(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file path required"))?;
    let content = read_text_capped("code_imports", &file)?;
    let imports: Vec<Value> = content
        .lines()
        .filter(|l| {
            l.trim().starts_with("use ")
                || l.trim().starts_with("import ")
                || l.trim().starts_with("from ")
                || l.trim().starts_with("#include")
        })
        .map(|l| Value::Str(l.trim().to_string()))
        .collect();
    Ok(Value::Array(imports))
}

fn bi_code_exports(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file path required"))?;
    let content = read_text_capped("code_exports", &file)?;
    let exports: Vec<Value> = content
        .lines()
        .filter(|l| l.trim().starts_with("pub ") || l.trim().starts_with("export "))
        .map(|l| Value::Str(l.trim().to_string()))
        .collect();
    Ok(Value::Array(exports))
}

fn bi_code_dependencies(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_code_imports(args, _input)
}

fn bi_code_callers(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    source_navigation::analyze("code_callers", args, input)
}

fn bi_code_callees(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    source_navigation::analyze("code_callees", args, input)
}

fn bi_code_hover(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    source_navigation::analyze("code_hover", args, input)
}

fn bi_code_signature(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    source_navigation::analyze("code_signature", args, input)
}

fn bi_code_completions(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    source_navigation::analyze("code_completions", args, input)
}

fn bi_code_format(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file path required"))?;
    let ext = std::path::Path::new(&file)
        .extension()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    // The path goes to the formatter positionally.
    crate::safety::reject_option_like("code_format", std::slice::from_ref(&file))?;
    // Each formatter rewrites the file in place, and none was jailed.
    let file = guard_local_write("code_format", &file)?;
    crate::tx::snapshot(&file);
    let (program, cmd) = match ext {
        "rs" => {
            let mut cmd = crate::safety::child_command("rustfmt");
            cmd.arg(&file);
            ("rustfmt", cmd)
        }
        "py" => {
            let mut cmd = crate::safety::child_command("black");
            cmd.arg(&file);
            ("black", cmd)
        }
        "js" | "ts" => {
            let mut cmd = crate::safety::child_command("prettier");
            cmd.args(["--write", &file]);
            ("prettier", cmd)
        }
        // An unsupported extension, a missing formatter and a formatter that
        // failed were all `false`.
        other => {
            return Err(crate::safety::bad_arg(
                "code_format",
                "a .rs, .py, .js or .ts file",
                &format!("a .{other} file"),
            ))
        }
    };
    let output = bounded_cmd_output("code_format", program, cmd, TOOL_DEADLINE_SECS)?;
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "code_format",
            program,
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    Ok(Value::Bool(true))
}

fn bi_code_language(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file path required"))?;
    let ext = std::path::Path::new(&file)
        .extension()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    let lang = match ext {
        "rs" => "rust",
        "py" => "python",
        "js" => "javascript",
        "ts" => "typescript",
        "go" => "go",
        "java" => "java",
        "c" | "h" => "c",
        "cpp" | "hpp" | "cc" => "cpp",
        "rb" => "ruby",
        "sh" => "shell",
        "md" => "markdown",
        "json" => "json",
        "toml" => "toml",
        "yaml" | "yml" => "yaml",
        _ => "unknown",
    };
    Ok(Value::Str(lang.to_string()))
}

fn bi_code_comments(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file path required"))?;
    let content = read_text_capped("code_comments", &file)?;
    let comments: Vec<Value> = content
        .lines()
        .enumerate()
        .filter(|(_, l)| {
            let t = l.trim();
            t.starts_with("//") || t.starts_with("#") || t.starts_with("/*") || t.starts_with("*")
        })
        .map(|(i, l)| {
            let mut rec = BTreeMap::new();
            rec.insert("line".to_string(), Value::Int((i + 1) as i64));
            rec.insert("text".to_string(), Value::Str(l.trim().to_string()));
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(comments))
}

fn bi_code_todos(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file path required"))?;
    let content = read_text_capped("code_todos", &file)?;
    let todos: Vec<Value> = content
        .lines()
        .enumerate()
        .filter(|(_, l)| l.to_uppercase().contains("TODO") || l.to_uppercase().contains("FIXME"))
        .map(|(i, l)| {
            let mut rec = BTreeMap::new();
            rec.insert("line".to_string(), Value::Int((i + 1) as i64));
            rec.insert("text".to_string(), Value::Str(l.trim().to_string()));
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(todos))
}

// Project module implementations
fn bi_project_type(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if std::path::Path::new("Cargo.toml").exists() {
        return Ok(Value::Str("rust".to_string()));
    }
    if std::path::Path::new("package.json").exists() {
        return Ok(Value::Str("node".to_string()));
    }
    if std::path::Path::new("pyproject.toml").exists() || std::path::Path::new("setup.py").exists()
    {
        return Ok(Value::Str("python".to_string()));
    }
    if std::path::Path::new("go.mod").exists() {
        return Ok(Value::Str("go".to_string()));
    }
    if std::path::Path::new("pom.xml").exists() {
        return Ok(Value::Str("java".to_string()));
    }
    Ok(Value::Str("unknown".to_string()))
}

fn bi_project_root(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = git_command();
    cmd.args(["rev-parse", "--show-toplevel"]);
    // The doc promises no fallback, so a directory that is not a repository
    // (or no git at all) is not reported as the root. It used to answer the
    // current directory for every failure, which named a subdirectory as the
    // project root.
    let output = bounded_cmd_output("project_root", "git", cmd, TOOL_DEADLINE_SECS);
    let cwd = std::env::current_dir()?.to_string_lossy().to_string();
    match output {
        Ok(o) if o.status.success() => Ok(Value::Str(
            String::from_utf8_lossy(&o.stdout).trim().to_string(),
        )),
        Ok(o) if String::from_utf8_lossy(&o.stderr).contains("not a git repository") => Err(
            crate::safety::not_found("project_root", "project root", &cwd),
        ),
        Ok(o) => Err(crate::safety::tool_failed(
            "project_root",
            "git rev-parse --show-toplevel",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        // No git is E_TOOL_MISSING from the spawn, not "no project root".
        Err(e) => Err(e),
    }
}

/// Read a manifest that may be absent. `None` means the file does not exist.
/// Other read errors are coded errors, not an empty answer.
fn project_manifest_optional(builtin: &str, path: &str) -> Result<Option<String>> {
    match std::fs::read_to_string(path) {
        Ok(text) => Ok(Some(text)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(crate::safety::fs_error(builtin, path, &e)),
    }
}

/// Read a Cargo.toml that must exist. A missing file is a coded not_found.
fn project_cargo_text(builtin: &str) -> Result<String> {
    match project_manifest_optional(builtin, "Cargo.toml")? {
        Some(text) => Ok(text),
        None => Err(crate::safety::not_found(
            builtin,
            "Cargo.toml",
            "Cargo.toml",
        )),
    }
}

/// The `name = "..."` value in Cargo.toml text. Old code returned "unknown"
/// when the value was absent or malformed.
fn cargo_name_from_text(builtin: &str, text: &str) -> Result<String> {
    for line in text.lines() {
        if line.starts_with("name = ") {
            if let Some(name) = line.split('"').nth(1) {
                return Ok(name.to_string());
            }
        }
    }
    Err(crate::safety::bad_state(
        builtin,
        "Cargo.toml has no name = line",
        "project_type",
    ))
}

/// The `version = "..."` value in Cargo.toml text. Old code returned "0.0.0"
/// when the value was absent or malformed.
fn cargo_version_from_text(builtin: &str, text: &str) -> Result<String> {
    for line in text.lines() {
        if line.starts_with("version = ") {
            if let Some(version) = line.split('"').nth(1) {
                return Ok(version.to_string());
            }
        }
    }
    Err(crate::safety::bad_state(
        builtin,
        "Cargo.toml has no version = line",
        "project_type",
    ))
}

/// A top-level string field of package.json text, such as `"name"`.
fn package_json_field(content: &str, field: &str) -> Option<String> {
    match serde_json::from_str::<serde_json::Value>(content)
        .ok()?
        .get(field)?
    {
        serde_json::Value::String(v) => Some(v.clone()),
        _ => None,
    }
}

/// The keys listed under one Cargo.toml table header (for example
/// `[dependencies]`). A table with no entries gives an empty list, which is a
/// real answer; a missing Cargo.toml is handled by the caller.
fn cargo_section_keys(text: &str, header: &str) -> Vec<Value> {
    let mut keys = Vec::new();
    let mut in_section = false;
    for line in text.lines() {
        if line.starts_with(header) {
            in_section = true;
            continue;
        }
        if line.starts_with("[") {
            in_section = false;
        }
        if in_section && line.contains("=") {
            keys.push(Value::Str(
                line.split('=').next().unwrap_or("").trim().to_string(),
            ));
        }
    }
    keys
}

fn bi_project_name(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    const B: &str = "project_name";
    let cargo = project_manifest_optional(B, "Cargo.toml")?;
    if let Some(text) = &cargo {
        if let Ok(name) = cargo_name_from_text(B, text) {
            return Ok(Value::Str(name));
        }
    }
    let pkg = project_manifest_optional(B, "package.json")?;
    if let Some(name) = pkg.as_deref().and_then(|t| package_json_field(t, "name")) {
        return Ok(Value::Str(name));
    }
    if cargo.is_none() && pkg.is_none() {
        return Err(crate::safety::not_found(B, "Cargo.toml", "Cargo.toml"));
    }
    Err(crate::safety::bad_state(
        B,
        "no name in Cargo.toml or package.json",
        "project_type",
    ))
}

fn bi_project_version(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    const B: &str = "project_version";
    // A Node project has no Cargo.toml; read its package.json as
    // project_name does, rather than answer "0.0.0" or refuse it.
    if let Some(text) = project_manifest_optional(B, "Cargo.toml")? {
        return Ok(Value::Str(cargo_version_from_text(B, &text)?));
    }
    match project_manifest_optional(B, "package.json")? {
        Some(text) => package_json_field(&text, "version")
            .map(Value::Str)
            .ok_or_else(|| {
                crate::safety::bad_state(B, "package.json has no \"version\"", "project_type")
            }),
        None => Err(crate::safety::not_found(
            B,
            "Cargo.toml or package.json",
            ".",
        )),
    }
}

fn bi_project_dependencies(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let text = project_cargo_text("project_dependencies")?;
    Ok(Value::Array(cargo_section_keys(&text, "[dependencies]")))
}

fn bi_project_dev_dependencies(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let text = project_cargo_text("project_dev_dependencies")?;
    Ok(Value::Array(cargo_section_keys(
        &text,
        "[dev-dependencies]",
    )))
}

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

    #[test]
    fn cargo_version_is_read_from_package_section() {
        let text = "[package]\nname = \"ae\"\nversion = \"1.2.3\"\n";
        assert_eq!(
            cargo_version_from_text("project_version", text).unwrap(),
            "1.2.3"
        );
    }

    #[test]
    fn cargo_version_missing_is_an_error_not_0_0_0() {
        let text = "[package]\nname = \"ae\"\n";
        assert!(cargo_version_from_text("project_version", text).is_err());
    }

    #[test]
    fn cargo_name_is_read_from_package_section() {
        let text = "[package]\nname = \"ae\"\nversion = \"1.2.3\"\n";
        assert_eq!(cargo_name_from_text("project_name", text).unwrap(), "ae");
    }

    #[test]
    fn cargo_name_missing_is_an_error_not_unknown() {
        let text = "[package]\nversion = \"1.2.3\"\n";
        assert!(cargo_name_from_text("project_name", text).is_err());
    }

    #[test]
    fn cargo_section_keys_empty_table_is_a_real_empty_list() {
        let text = "[package]\nname = \"ae\"\n\n[dependencies]\n\n[dev-dependencies]\nx = \"1\"\n";
        assert!(cargo_section_keys(text, "[dependencies]").is_empty());
        assert_eq!(cargo_section_keys(text, "[dev-dependencies]").len(), 1);
    }
}

#[path = "project_manifest.rs"]
mod project_manifest;
fn bi_project_scripts(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    project_manifest::guard_and_discover(args, input)
}

fn bi_project_structure(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut files = Vec::new();
    // An unreadable directory used to be skipped, so its entries silently
    // vanished from a listing that looked complete. It is an error now.
    fn walk(dir: &std::path::Path, files: &mut Vec<Value>, depth: usize) -> Result<()> {
        if depth > 3 {
            return Ok(());
        }
        let entries = match std::fs::read_dir(dir) {
            Ok(entries) => entries,
            // Removed since its parent listed it: nothing left to report.
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(crate::safety::fs_error("project_structure", dir, &e)),
        };
        for entry in entries {
            let entry = entry.map_err(|e| crate::safety::fs_error("project_structure", dir, &e))?;
            let path = entry.path();
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            if name.starts_with(".") || name == "target" || name == "node_modules" {
                continue;
            }
            files.push(Value::Str(path.to_string_lossy().to_string()));
            if entry_is_dir("project_structure", &path)? {
                walk(&path, files, depth + 1)?;
            }
        }
        Ok(())
    }
    walk(std::path::Path::new("."), &mut files, 0)?;
    Ok(Value::Array(files))
}

fn bi_project_entry_points(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut entries = Vec::new();
    if std::path::Path::new("src/main.rs").exists() {
        entries.push(Value::Str("src/main.rs".to_string()));
    }
    if std::path::Path::new("src/lib.rs").exists() {
        entries.push(Value::Str("src/lib.rs".to_string()));
    }
    if std::path::Path::new("index.js").exists() {
        entries.push(Value::Str("index.js".to_string()));
    }
    if std::path::Path::new("main.py").exists() {
        entries.push(Value::Str("main.py".to_string()));
    }
    Ok(Value::Array(entries))
}

fn bi_project_test_files(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut tests = Vec::new();
    // A tests/ directory that cannot be listed used to read as no tests.
    let dir = std::path::Path::new("tests");
    if entry_is_dir("project_test_files", dir)? {
        let entries = std::fs::read_dir(dir)
            .map_err(|e| crate::safety::fs_error("project_test_files", dir, &e))?;
        for entry in entries {
            let entry =
                entry.map_err(|e| crate::safety::fs_error("project_test_files", dir, &e))?;
            tests.push(Value::Str(entry.path().to_string_lossy().to_string()));
        }
    }
    Ok(Value::Array(tests))
}

fn bi_project_config_files(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let configs = [
        "Cargo.toml",
        "package.json",
        "pyproject.toml",
        "tsconfig.json",
        ".eslintrc.json",
        "rustfmt.toml",
    ];
    let found: Vec<Value> = configs
        .iter()
        .filter(|c| std::path::Path::new(c).exists())
        .map(|c| Value::Str(c.to_string()))
        .collect();
    Ok(Value::Array(found))
}

// Each reader used to turn any read error (permission, not UTF-8, I/O) into
// Null, the same answer as "no such file". Only a missing file is Null now.
fn bi_project_readme(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    first_project_text(
        "project_readme",
        &["README.md", "README.txt", "README", "readme.md"],
    )
}

fn bi_project_license(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    first_project_text("project_license", &["LICENSE", "LICENSE.md", "LICENSE.txt"])
}

fn bi_project_gitignore(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    first_project_text("project_gitignore", &[".gitignore"])
}

fn bi_project_languages(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut langs = std::collections::HashSet::new();
    fn check_ext(path: &std::path::Path, langs: &mut std::collections::HashSet<String>) {
        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
            let lang = match ext {
                "rs" => "Rust",
                "py" => "Python",
                "js" => "JavaScript",
                "ts" => "TypeScript",
                "go" => "Go",
                "java" => "Java",
                "rb" => "Ruby",
                "c" | "h" => "C",
                "cpp" | "hpp" => "C++",
                "sh" => "Shell",
                _ => return,
            };
            langs.insert(lang.to_string());
        }
    }
    // An unreadable directory used to be skipped, so its languages silently
    // dropped out of the answer. It is an error now.
    fn walk(
        dir: &std::path::Path,
        langs: &mut std::collections::HashSet<String>,
        depth: usize,
    ) -> Result<()> {
        if depth > 3 {
            return Ok(());
        }
        let entries = match std::fs::read_dir(dir) {
            Ok(entries) => entries,
            // Removed since its parent listed it: nothing left to report.
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(crate::safety::fs_error("project_languages", dir, &e)),
        };
        for entry in entries {
            let entry = entry.map_err(|e| crate::safety::fs_error("project_languages", dir, &e))?;
            let path = entry.path();
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            if name.starts_with(".") || name == "target" || name == "node_modules" {
                continue;
            }
            if entry_is_dir("project_languages", &path)? {
                walk(&path, langs, depth + 1)?;
            } else if entry_is_file("project_languages", &path)? {
                check_ext(&path, langs);
            }
        }
        Ok(())
    }
    walk(std::path::Path::new("."), &mut langs, 0)?;
    Ok(Value::Array(langs.into_iter().map(Value::Str).collect()))
}

/// Source lines under the working directory.
///
/// This ran `wc -l src/*.rs`. There is no shell between `Command::new` and
/// `wc`, so nothing expanded the glob: `wc` was handed a file literally named
/// `src/*.rs`, failed, and the function fell through to `Ok(Value::Int(0))`.
/// It reported 0 lines for every project on every platform, and reported it as
/// a fact rather than a failure. Counting in Rust removes both the glob and
/// the subprocess.
fn bi_project_loc(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Int(project_loc_in(std::path::Path::new("."))?))
}

/// The count behind `project_loc`, over `root`. Split out so that the tests
/// can point it at a temporary tree; the builtin itself always counts `.`.
fn project_loc_in(root: &std::path::Path) -> Result<i64> {
    const SOURCE_EXT: &[&str] = &[
        "rs", "py", "js", "ts", "tsx", "jsx", "go", "java", "c", "h", "cc", "cpp", "hpp", "cs",
        "rb", "sh", "ish", "lua", "kt", "swift", "php", "scala",
    ];
    // Directories that are build output or vendored code: counting them
    // measures someone else's project, and on a Rust tree `target/` alone
    // dwarfs the source.
    const SKIP: &[&str] = &[
        "target",
        "node_modules",
        ".git",
        "dist",
        "build",
        "vendor",
        ".venv",
        "__pycache__",
    ];

    /// Lines as `str::lines` counts them: one per newline, plus a final line
    /// that has no newline after it.
    fn count_lines(bytes: &[u8]) -> i64 {
        let newlines = bytes.iter().filter(|b| **b == b'\n').count();
        let unterminated = !bytes.is_empty() && bytes.last() != Some(&b'\n');
        (newlines + usize::from(unterminated)) as i64
    }

    fn count(dir: &std::path::Path, total: &mut i64, budget: &mut u32) -> Result<()> {
        // A budget rather than unbounded recursion: this is called from an
        // agent loop, and a symlinked or pathological tree must not cost the
        // whole turn. Exhausting it is reported as E_BUDGET_EXCEEDED, never as
        // a number -- a partial count returned as an Int is indistinguishable
        // from a small project, which is the defect this replaced.
        if *budget == 0 {
            return Ok(());
        }
        // An unreadable directory used to be skipped, so its sources were
        // missing from the total and the total was returned as the count.
        let entries =
            std::fs::read_dir(dir).map_err(|e| crate::safety::fs_error("project_loc", dir, &e))?;
        for entry in entries {
            let entry = entry.map_err(|e| crate::safety::fs_error("project_loc", dir, &e))?;
            *budget = budget.saturating_sub(1);
            if *budget == 0 {
                return Ok(());
            }
            let path = entry.path();
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if entry_is_dir("project_loc", &path)? {
                if !SKIP.contains(&name.as_ref()) && !name.starts_with('.') {
                    count(&path, total, budget)?;
                }
            } else if path
                .extension()
                .and_then(|e| e.to_str())
                .is_some_and(|e| SOURCE_EXT.contains(&e))
            {
                // Bytes, not `read_to_string`: that refused any non-UTF-8 file
                // (Latin-1 source, say), and the file counted as 0 lines.
                let bytes = match read_bytes_capped("project_loc", &path) {
                    Ok(bytes) => bytes,
                    // Removed since it was listed, or a dangling symlink.
                    Err(e) if capped_read_not_found(&e) => continue,
                    Err(e) => return Err(e),
                };
                *total += count_lines(&bytes);
            }
        }
        Ok(())
    }

    let mut total = 0i64;
    const BUDGET: u32 = 200_000;
    let mut budget = BUDGET;
    count(root, &mut total, &mut budget)?;
    if budget == 0 {
        return Err(crate::safety::budget_exceeded(
            "project_loc",
            format!("stopped after {BUDGET} directory entries; the count is partial"),
            "run it against a subdirectory, or exclude generated trees",
        ));
    }
    Ok(total)
}

fn bi_project_size(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut total: u64 = 0;
    // An unreadable directory or entry used to be skipped, and a failed stat
    // counted as 0 bytes: the size was the sum of what happened to be readable.
    fn walk(dir: &std::path::Path, total: &mut u64, depth: usize) -> Result<()> {
        if depth > 5 {
            return Ok(());
        }
        let entries =
            std::fs::read_dir(dir).map_err(|e| crate::safety::fs_error("project_size", dir, &e))?;
        for entry in entries {
            let path = entry
                .map_err(|e| crate::safety::fs_error("project_size", dir, &e))?
                .path();
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            if name.starts_with(".") || name == "target" || name == "node_modules" {
                continue;
            }
            if entry_is_dir("project_size", &path)? {
                walk(&path, total, depth + 1)?;
            } else {
                match std::fs::metadata(&path) {
                    Ok(meta) if meta.is_file() => *total += meta.len(),
                    Ok(_) => {}
                    // Removed since it was listed, or a dangling symlink.
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                    Err(e) => return Err(crate::safety::fs_error("project_size", &path, &e)),
                }
            }
        }
        Ok(())
    }
    walk(std::path::Path::new("."), &mut total, 0)?;
    Ok(Value::Int(total as i64))
}
// ---------------------------------------------------------------------------
// Recursive search helpers for the `search_*` family
// ---------------------------------------------------------------------------

/// Directories a code search must never descend into.
///
/// `search_fixmes` ran `grep -rn FIXME .` with no exclusions. From a project
/// root that walks `node_modules`, `.git` and build output: slow, and full of
/// third-party noise -- `search_todos` returned a TODO from
/// `.git/hooks/sendemail-validate.sample`. Under WSL2, two such walks running
/// at once over `/mnt/c` stalled in 9P (`wchan = p9_client_rpc`, state D)
/// inside `node_modules/lucide-react/dist/esm/icons`, and because
/// `Command::output()` waits forever, the builtin never returned.
const SEARCH_SKIP_DIRS: &[&str] = &[
    "node_modules",
    ".git",
    "target",
    "dist",
    "build",
    "vendor",
    ".venv",
    "__pycache__",
    // IronShell's own state (the audit log, sessions, journal). A search for a
    // word the shell itself logged found the log, not the project.
    ".ironshell",
];

/// A search that has not finished in this long is not going to be useful to
/// an agent, and a bounded refusal is worth more than an unbounded wait.
const SEARCH_TIMEOUT_SECS: u64 = 30;

/// Everything a search needs to know about one directory entry.
struct SearchEntry {
    /// `./relative/path`, the form `find .` and `grep -r .` printed.
    shown: String,
    path: std::path::PathBuf,
    is_file: bool,
    meta: std::fs::Metadata,
}

/// Walk `.` in sorted order, skipping [`SEARCH_SKIP_DIRS`] and symlinks, and
/// hand each entry to `visit`.
///
/// This replaces shelling out to `find` and `grep`. The subprocesses were the
/// problem three times over: on Windows `find` is System32\find.exe, `grep` is
/// only present when Git's tools happen to be on PATH, and on WSL two
/// concurrent walks over /mnt/c stalled in 9P until the builtin never returned.
/// A walk in-process is the same everywhere, and it is sorted, where `find`
/// and `grep` printed in whatever order the directory happened to list --
/// which made two identical searches differ.
///
/// Symlinks are skipped, matching what the subprocesses did: `find -type f`
/// excludes them and `grep -r` follows only those named on the command line.
fn search_walk(builtin: &str, visit: &mut dyn FnMut(&SearchEntry) -> Result<()>) -> Result<()> {
    const BUDGET: u32 = 200_000;
    let started = std::time::Instant::now();
    let mut budget = BUDGET;
    let mut stack = vec![(std::path::PathBuf::from("."), String::from("."))];
    while let Some((dir, shown_dir)) = stack.pop() {
        // A directory that cannot be listed used to be skipped with `continue`,
        // and an entry that could not be read was dropped by `flatten`. The
        // search then reported the matches it had found as if they were all.
        let rd = std::fs::read_dir(&dir).map_err(|e| crate::safety::fs_error(builtin, &dir, &e))?;
        let mut entries = Vec::new();
        for entry in rd {
            entries.push(entry.map_err(|e| crate::safety::fs_error(builtin, &dir, &e))?);
        }
        entries.sort_by_key(|e| e.file_name());
        let mut subdirs = Vec::new();
        for entry in entries {
            // A search that has not finished in this long is not going to be
            // useful to an agent. Refusing is worth more than an unbounded wait,
            // and a partial list returned as the whole answer would be the
            // silent wrong answer this family used to give.
            if budget == 0 || started.elapsed().as_secs() >= SEARCH_TIMEOUT_SECS {
                return Err(crate::safety::budget_exceeded(
                    builtin,
                    format!(
                        "stopped after {} entries and {}s; the result would be partial, \
                         so nothing was returned",
                        BUDGET - budget,
                        started.elapsed().as_secs()
                    ),
                    "search a narrower directory",
                ));
            }
            budget -= 1;
            let meta = match std::fs::symlink_metadata(entry.path()) {
                Ok(meta) => meta,
                // Removed since it was listed: nothing left to report.
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
                Err(e) => return Err(crate::safety::fs_error(builtin, entry.path(), &e)),
            };
            if meta.file_type().is_symlink() {
                continue;
            }
            let name = entry.file_name().to_string_lossy().to_string();
            let shown = format!("{shown_dir}/{name}");
            if meta.is_dir() && SEARCH_SKIP_DIRS.contains(&name.as_str()) {
                continue;
            }
            let item = SearchEntry {
                shown: shown.clone(),
                path: entry.path(),
                is_file: meta.is_file(),
                meta,
            };
            visit(&item)?;
            if item.meta.is_dir() {
                subdirs.push((item.path, shown));
            }
        }
        // Reverse so that popping visits subdirectories in sorted order.
        stack.extend(subdirs.into_iter().rev());
    }
    Ok(())
}

/// Shell-style glob on a file name: `*`, `?` and `[...]` (with `!` or `^`
/// negation and `a-z` ranges) -- what `find -name` accepted.
fn shell_glob(pat: &[char], name: &[char]) -> bool {
    match pat.first() {
        None => name.is_empty(),
        Some('*') => (0..=name.len()).any(|i| shell_glob(&pat[1..], &name[i..])),
        Some('?') => !name.is_empty() && shell_glob(&pat[1..], &name[1..]),
        Some('[') => {
            let Some(close) = pat.iter().skip(2).position(|&c| c == ']').map(|p| p + 2) else {
                // No closing bracket: `[` is a literal, as in the shell.
                return name.first() == Some(&'[') && shell_glob(&pat[1..], &name[1..]);
            };
            let Some(&c) = name.first() else {
                return false;
            };
            let class = &pat[1..close];
            let (negate, class) = match class.first() {
                Some('!') | Some('^') => (true, &class[1..]),
                _ => (false, class),
            };
            let mut hit = false;
            let mut i = 0;
            while i < class.len() {
                if i + 2 < class.len() && class[i + 1] == '-' {
                    hit |= class[i] <= c && c <= class[i + 2];
                    i += 3;
                } else {
                    hit |= class[i] == c;
                    i += 1;
                }
            }
            hit != negate && shell_glob(&pat[close + 1..], &name[1..])
        }
        Some(&p) => name.first() == Some(&p) && shell_glob(&pat[1..], &name[1..]),
    }
}

/// `find .`'s `-size` test: `[+|-]N[c|k|M|G|b]`, where a size is rounded UP
/// to whole units before comparing, and a bare number means 512-byte blocks.
/// `+1M` is "more than one MiB", `-10k` "under ten KiB".
fn find_size_matches(builtin: &str, spec: &str, bytes: u64) -> Result<bool> {
    let (cmp, rest) = match spec.chars().next() {
        Some('+') => ('+', &spec[1..]),
        Some('-') => ('-', &spec[1..]),
        _ => ('=', spec),
    };
    let (digits, unit) = match rest.chars().last() {
        Some(u) if u.is_ascii_alphabetic() => (&rest[..rest.len() - 1], u),
        _ => (rest, 'b'),
    };
    let unit_bytes: u64 = match unit {
        'c' => 1,
        'k' => 1024,
        'M' => 1024 * 1024,
        'G' => 1024 * 1024 * 1024,
        'b' => 512,
        _ => {
            return Err(crate::safety::bad_arg(
                builtin,
                "a find-style size such as +1M, -10k or 100c",
                spec,
            ))
        }
    };
    let n: u64 = digits.parse().map_err(|_| {
        crate::safety::bad_arg(builtin, "a find-style size such as +1M, -10k or 100c", spec)
    })?;
    let units = bytes.div_ceil(unit_bytes);
    Ok(match cmp {
        '+' => units > n,
        '-' => units < n,
        _ => units == n,
    })
}

/// Search file contents for `pattern` under `.`, as `grep -rnI` did: lines
/// printed as `./path:line:text`, binary files skipped.
///
/// The pattern is a Rust regular expression. `grep` read a POSIX basic
/// regular expression, and the two agree on the literals every caller in this
/// file passes (`TODO`, `FIXME`). They differ on grouping -- `foo(` is a
/// literal `(` to grep and an unclosed group here -- so a pattern that does not
/// compile is refused with the reason, never searched for as something else.
fn search_grep(builtin: &str, pattern: &str) -> Result<Vec<String>> {
    let re = regex::Regex::new(pattern).map_err(|e| {
        crate::safety::bad_arg(
            builtin,
            "a regular expression (Rust regex syntax)",
            &e.to_string(),
        )
    })?;
    let mut out = Vec::new();
    search_walk(builtin, &mut |e| {
        if !e.is_file {
            return Ok(());
        }
        let Some(text) = search_read_text(builtin, &e.path, &e.shown)? else {
            return Ok(());
        };
        for (i, line) in text.lines().enumerate() {
            if re.is_match(line) {
                if out.len() >= SEARCH_MAX_RESULTS {
                    return Err(search_budget(builtin));
                }
                out.push(format!("{}:{}:{}", e.shown, i + 1, line));
            }
        }
        Ok(())
    })?;
    Ok(out)
}

/// Find files under `.` by the subset of `find` predicates the `search_*`
/// builtins use: `-type f`, `-name GLOB`, `-mtime -N` and `-size SPEC`.
///
/// Without `-type f` a matching directory is listed too, as `find` did.
fn search_find(builtin: &str, predicates: &[&str]) -> Result<Vec<String>> {
    let mut files_only = false;
    let mut name: Option<Vec<char>> = None;
    let mut newer_than_days: Option<u64> = None;
    let mut size: Option<String> = None;
    let mut it = predicates.iter();
    while let Some(&p) = it.next() {
        match (p, it.next()) {
            ("-type", Some(&"f")) => files_only = true,
            ("-name", Some(&g)) => name = Some(g.chars().collect()),
            ("-mtime", Some(&d)) if d.starts_with('-') => {
                newer_than_days =
                    Some(d[1..].parse().map_err(|_| {
                        crate::safety::bad_arg(builtin, "a whole number of days", d)
                    })?)
            }
            ("-size", Some(&spec)) => size = Some(spec.to_string()),
            (other, _) => {
                // Only reachable by a change to this file, never by a caller:
                // every predicate list is a literal above.
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: unsupported search predicate {other}"
                )));
            }
        }
    }
    let now = std::time::SystemTime::now();
    let mut out = Vec::new();
    search_walk(builtin, &mut |e| {
        if files_only && !e.is_file {
            return Ok(());
        }
        if let Some(g) = &name {
            let base: Vec<char> = e
                .path
                .file_name()
                .map(|n| n.to_string_lossy().chars().collect())
                .unwrap_or_default();
            if !shell_glob(g, &base) {
                return Ok(());
            }
        }
        if let Some(days) = newer_than_days {
            let age = e
                .meta
                .modified()
                .ok()
                .and_then(|m| now.duration_since(m).ok())
                .map(|d| d.as_secs())
                .unwrap_or(u64::MAX);
            if age >= days.saturating_mul(86_400) {
                return Ok(());
            }
        }
        if let Some(spec) = &size {
            if !find_size_matches(builtin, spec, e.meta.len())? {
                return Ok(());
            }
        }
        out.push(e.shown.clone());
        Ok(())
    })?;
    Ok(out)
}

// Search module implementations
fn bi_search_code(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    search_pattern_builtin("search_code", args, input)
}

fn bi_search_grep(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    search_pattern_builtin("search_grep", args, input)
}

fn bi_search_regex(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    search_pattern_builtin("search_regex", args, input)
}

/// The content search behind `search_code`, `search_grep` and `search_regex`:
/// one regular expression, under the workspace, capped at [`SEARCH_MAX_RESULTS`].

fn bi_search_symbols(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let pattern = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("pattern required"))?;
    // This ran `grep -rn "fn X|struct X|class X|def X" .`. Without `-E`, grep
    // reads a BASIC regular expression, in which `|` is a literal pipe -- so it
    // searched for that whole string, matched nothing, and returned [] for
    // every symbol in every project. `search_grep` takes a Rust regex, where
    // `|` alternates as intended; the symbol itself is escaped so that `a.b`
    // means `a.b`.
    let found = search_grep(
        "search_symbols",
        &format!(r"(?:fn|struct|class|def)\s+{}\b", regex::escape(&pattern)),
    )?;
    let matches: Vec<Value> = found
        .iter()
        .take(50)
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(matches))
}

fn bi_search_files(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let pattern = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("pattern required"))?;
    let found = search_find("search_files", &["-name", &pattern])?;
    let files: Vec<Value> = found.iter().map(|l| Value::Str(l.to_string())).collect();
    Ok(Value::Array(files))
}

fn bi_search_recent(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let found = search_find("search_recent", &["-type", "f", "-mtime", "-1"])?;
    let files: Vec<Value> = found
        .iter()
        .take(50)
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(files))
}

fn bi_search_modified(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let days = args.first().and_then(|v| v.as_int().ok()).unwrap_or(7);
    let found = search_find(
        "search_modified",
        &["-type", "f", "-mtime", &format!("-{}", days)],
    )?;
    let files: Vec<Value> = found
        .iter()
        .take(100)
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(files))
}

fn bi_search_by_type(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let ext = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("extension required"))?;
    let found = search_find("search_by_type", &["-name", &format!("*.{}", ext)])?;
    let files: Vec<Value> = found.iter().map(|l| Value::Str(l.to_string())).collect();
    Ok(Value::Array(files))
}

fn bi_search_by_size(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "search_by_size";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let size = match args.first() {
        None => "+1M".to_string(),
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                B,
                "a find-style size such as +1M, -10k or 100c",
                other.type_name(),
            ))
        }
    };
    // Checked before the walk: an empty tree would otherwise answer [] for a
    // size that was never understood.
    find_size_matches(B, &size, 0)?;
    let found = search_find(B, &["-type", "f", "-size", size.as_str()])?;
    search_list(B, found)
}

#[path = "code_search.rs"]
mod code_search;

fn bi_search_duplicates(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    code_search::run("search_duplicates", args, input)
}

fn bi_search_todos(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let found = search_grep("search_todos", "TODO")?;
    let todos: Vec<Value> = found
        .iter()
        .take(100)
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(todos))
}

fn bi_search_fixmes(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let found = search_grep("search_fixmes", "FIXME")?;
    let fixmes: Vec<Value> = found
        .iter()
        .take(100)
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(fixmes))
}

fn bi_search_semantic(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    code_search::run("search_semantic", args, input)
}

fn bi_search_similar(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    code_search::run("search_similar", args, input)
}

// Test and diagnostics builtins run cargo on an explicit project directory
// inside the workspace; see cargo_project.rs for the checks and the deadline.
#[path = "cargo_project.rs"]
mod cargo_project;
use cargo_project::{at_level, cargo_done, cargo_text, diagnostics, is_error_level, project_dir};

/// A cargo test selector (a test target or a test-name filter), checked
/// against `allowed` characters beyond letters, digits and `_`. A leading `-`
/// would be read by cargo as an option, so it is refused by the charset.
fn test_selector(
    builtin: &str,
    what: &str,
    value: Option<&Value>,
    allowed: &str,
) -> Result<String> {
    let s = match value {
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                &format!("{what}: String"),
                other.type_name(),
            ))
        }
        None => return Err(crate::safety::arg_err(format!("{builtin} requires {what}"))),
    };
    let well_formed = !s.is_empty()
        && s.len() <= 256
        && !s.starts_with('-')
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || allowed.contains(c));
    if !well_formed {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: 1 to 256 letters, digits, '_' or {allowed:?}, not starting with '-'"),
            &format!("{s:?}"),
        ));
    }
    crate::safety::reject_option_like(builtin, std::slice::from_ref(&s))?;
    Ok(s)
}

// Test module implementations
fn bi_test_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "test_run";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    let out = cargo_text(B, &dir, &["test"], Keep::Tail(TOOL_KEEP_TAIL))?;
    Ok(Value::Str(out))
}

fn bi_test_run_file(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "test_run_file";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    let file = test_selector(
        B,
        "file: the name of an integration test target",
        args.get(1),
        "-",
    )?;
    let out = cargo_text(
        B,
        &dir,
        &["test", "--test", &file],
        Keep::Tail(TOOL_KEEP_TAIL),
    )?;
    Ok(Value::Str(out))
}

fn bi_test_run_function(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "test_run_function";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    let name = test_selector(B, "name: a test name or path filter", args.get(1), ":")?;
    let out = cargo_text(B, &dir, &["test", &name], Keep::Tail(TOOL_KEEP_TAIL))?;
    Ok(Value::Str(out))
}

fn bi_test_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "test_list";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    // Head, not tail: a listing cut short would look like a complete one.
    let out = cargo_text(
        B,
        &dir,
        &["test", "--", "--list"],
        Keep::Head(TOOL_MAX_TEXT),
    )?;
    let tests: Vec<Value> = out
        .lines()
        .filter_map(|l| l.strip_suffix(": test"))
        .map(|name| Value::Str(name.to_string()))
        .collect();
    Ok(Value::Array(tests))
}

#[path = "test_reports.rs"]
mod test_reports;
fn bi_test_coverage(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    test_reports::coverage(args, input)
}
fn bi_test_failing(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    test_reports::outcomes("test_failing", args, input)
}
fn bi_test_passing(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    test_reports::outcomes("test_passing", args, input)
}
fn bi_test_skipped(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    test_reports::outcomes("test_skipped", args, input)
}

#[path = "test_watch.rs"]
mod test_watch;
fn bi_test_watch(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    test_watch::run("test_watch", args, input)
}

fn bi_test_bench(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "test_bench";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    let out = cargo_text(B, &dir, &["bench"], Keep::Tail(TOOL_KEEP_TAIL))?;
    Ok(Value::Str(out))
}

#[path = "testing_backend.rs"]
mod testing_backend;

fn bi_test_snapshot(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    testing_backend::run("test_snapshot", args, input)
}

fn bi_test_generate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    testing_backend::run("test_generate", args, input)
}

// Diagnostics module implementations
/// diag_check(dir) - cargo check's errors and warnings, as Records.
fn bi_diag_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "diag_check";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    Ok(Value::Array(diagnostics(B, &dir, &["check"])?))
}

/// diag_lint(dir) - cargo clippy's errors and warnings, as Records.
fn bi_diag_lint(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "diag_lint";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    Ok(Value::Array(diagnostics(B, &dir, &["clippy"])?))
}

/// diag_errors(dir) - only the errors of cargo check.
fn bi_diag_errors(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "diag_errors";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    let found = diagnostics(B, &dir, &["check"])?;
    Ok(Value::Array(at_level(found, is_error_level)))
}

/// diag_warnings(dir) - only the warnings of cargo check.
fn bi_diag_warnings(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "diag_warnings";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    let found = diagnostics(B, &dir, &["check"])?;
    Ok(Value::Array(at_level(found, |l| l == "warning")))
}

/// diag_all(dir) - cargo check over every target: library, binaries, tests,
/// examples and benches. Compiler errors in test code appear here and not in
/// diag_check, which checks the default targets.
fn bi_diag_all(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "diag_all";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    Ok(Value::Array(diagnostics(
        B,
        &dir,
        &["check", "--all-targets"],
    )?))
}

/// diag_fix(dir) - cargo fix, which applies the compiler's machine-applicable
/// suggestions to the project's files. It refuses a version-controlled tree
/// with uncommitted changes, as cargo does by default; --allow-dirty is not
/// passed, so the rewrite never lands on uncommitted work silently.
fn bi_diag_fix(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "diag_fix";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    cargo_done(B, &dir, &["fix"])?;
    Ok(Value::Bool(true))
}

fn bi_diag_explain(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let code = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("error code required"))?;
    crate::safety::reject_option_like("diag_explain", std::slice::from_ref(&code))?;
    let mut cmd = crate::safety::child_command("rustc");
    cmd.args(["--explain", &code]);
    let output = bounded_cmd_output("diag_explain", "rustc", cmd, TOOL_DEADLINE_SECS)?;
    // A code rustc does not know ("E9999") answered "".
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "diag_explain",
            "rustc --explain",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).to_string(),
    ))
}

fn bi_diag_suppress(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    diagnostic_filter::run(args, input)
}
#[path = "diagnostic_filter.rs"]
mod diagnostic_filter;

fn bi_diag_config(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if let Ok(content) = std::fs::read_to_string("clippy.toml") {
        return Ok(Value::Str(content));
    }
    if let Ok(content) = std::fs::read_to_string(".clippy.toml") {
        return Ok(Value::Str(content));
    }
    Ok(Value::Null)
}

// Refactor module implementations
#[path = "expression_refactor.rs"]
mod expression_refactor;
#[path = "rename_refactor.rs"]
mod rename_refactor;
fn bi_refactor_rename(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    rename_refactor::run("refactor_rename", args, input)
}

/// Renames `from` to `to` without replacing an existing `to`. The check that the
/// destination is free is the caller's, and it is not enough on its own: another
/// process can create `to` between the check and the rename. So the rename
/// itself refuses an existing destination, atomically, where the platform has a
/// primitive for it:
///
/// - Linux and Android: `renameat2` with `RENAME_NOREPLACE`. It applies to files,
///   directories and symlinks alike.
/// - macOS: `renamex_np` with `RENAME_EXCL`. Also every kind of entry.
/// - Windows: `MoveFileExW` with no replace flag, which fails with
///   `ERROR_ALREADY_EXISTS` for a directory as well as a file. `std::fs::rename`
///   passes `MOVEFILE_REPLACE_EXISTING`, which is why it is not used here.
///
/// An existing destination is reported as `AlreadyExists`, whatever the entry.
///
/// Where the primitive is missing or refuses for another reason (a filesystem
/// or kernel without it, `EINVAL` or `ENOSYS` on Linux, `ENOTSUP` or `EINVAL`
/// on macOS, any other failure on Windows), the older fallback runs. A
/// directory, or a symlink, takes the plain `std::fs::rename`, which replaces
/// its destination. A file first gets a hard link to `to`, which fails with
/// `AlreadyExists` when `to` is taken, and only then is `from` removed; if that
/// removal fails the new link is removed too, so the file is left under both
/// names only when that removal fails as well, and the error then says so. A volume
/// that cannot hard-link (FAT, some network shares) falls
/// back to `std::fs::rename` on any hard-link error other than `AlreadyExists`.
/// So on those systems the caller's check is the only guard, as before. On
/// other targets the fallback is all there is.
pub fn rename_file_no_replace(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> {
    if let Some(done) = rename_no_replace_atomic(from, to) {
        return done;
    }
    if !std::fs::symlink_metadata(from)?.is_file() {
        return std::fs::rename(from, to);
    }
    match std::fs::hard_link(from, to) {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Err(e),
        Err(_) => return std::fs::rename(from, to),
    }
    if let Err(e) = std::fs::remove_file(from) {
        if let Err(undo) = std::fs::remove_file(to) {
            if undo.kind() != std::io::ErrorKind::NotFound {
                return Err(std::io::Error::new(
                    e.kind(),
                    format!(
                        "{e}; and the new name {} could not be removed, so the file now has both names",
                        to.display()
                    ),
                ));
            }
        }
        return Err(e);
    }
    Ok(())
}

/// The atomic no-replace rename for this platform, or `None` when the primitive
/// is not there or refuses in a way the fallback handles (see
/// `rename_file_no_replace`). `Some` is the final answer.
#[cfg(any(target_os = "linux", target_os = "android"))]
fn rename_no_replace_atomic(
    from: &std::path::Path,
    to: &std::path::Path,
) -> Option<std::io::Result<()>> {
    const RENAME_NOREPLACE: libc::c_uint = 1;
    let (from, to) = match c_paths(from, to) {
        Ok(pair) => pair,
        Err(e) => return Some(Err(e)),
    };
    // SAFETY: both strings are NUL-terminated and outlive the call. AT_FDCWD makes
    // relative paths resolve against the working directory, as std::fs does.
    let rc = unsafe {
        libc::syscall(
            libc::SYS_renameat2,
            libc::AT_FDCWD,
            from.as_ptr(),
            libc::AT_FDCWD,
            to.as_ptr(),
            RENAME_NOREPLACE,
        )
    };
    if rc == 0 {
        return Some(Ok(()));
    }
    let err = std::io::Error::last_os_error();
    match err.raw_os_error() {
        // No renameat2 in the kernel (ENOSYS), or no RENAME_NOREPLACE on this
        // filesystem (EINVAL): the fallback.
        Some(libc::EINVAL) | Some(libc::ENOSYS) => None,
        _ => Some(Err(err)),
    }
}

#[cfg(target_os = "macos")]
fn rename_no_replace_atomic(
    from: &std::path::Path,
    to: &std::path::Path,
) -> Option<std::io::Result<()>> {
    extern "C" {
        fn renamex_np(
            from: *const libc::c_char,
            to: *const libc::c_char,
            flags: libc::c_uint,
        ) -> libc::c_int;
    }
    const RENAME_EXCL: libc::c_uint = 0x4;
    let (from, to) = match c_paths(from, to) {
        Ok(pair) => pair,
        Err(e) => return Some(Err(e)),
    };
    // SAFETY: both strings are NUL-terminated and outlive the call.
    let rc = unsafe { renamex_np(from.as_ptr(), to.as_ptr(), RENAME_EXCL) };
    if rc == 0 {
        return Some(Ok(()));
    }
    let err = std::io::Error::last_os_error();
    match err.raw_os_error() {
        // The volume does not support exclusive renames: the fallback.
        Some(libc::ENOTSUP) | Some(libc::EINVAL) => None,
        _ => Some(Err(err)),
    }
}

#[cfg(windows)]
fn rename_no_replace_atomic(
    from: &std::path::Path,
    to: &std::path::Path,
) -> Option<std::io::Result<()>> {
    extern "system" {
        fn MoveFileExW(existing: *const u16, new: *const u16, flags: u32) -> i32;
    }
    let from = match wide_path(from) {
        Ok(w) => w,
        Err(e) => return Some(Err(e)),
    };
    let to = match wide_path(to) {
        Ok(w) => w,
        Err(e) => return Some(Err(e)),
    };
    // SAFETY: both buffers are NUL-terminated and outlive the call. Flags 0 means
    // no MOVEFILE_REPLACE_EXISTING, so an existing destination is an error.
    let ok = unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), 0) };
    if ok != 0 {
        return Some(Ok(()));
    }
    let err = std::io::Error::last_os_error();
    match err.raw_os_error() {
        // ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS: the destination is taken.
        Some(80) | Some(183) => Some(Err(std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            err,
        ))),
        _ => None,
    }
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_os = "macos",
    windows
)))]
fn rename_no_replace_atomic(
    _from: &std::path::Path,
    _to: &std::path::Path,
) -> Option<std::io::Result<()>> {
    None
}

/// Both paths as NUL-terminated C strings. A path with an interior NUL cannot be
/// passed to the kernel, so it is refused as `InvalidInput`.
#[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]
fn c_paths(
    from: &std::path::Path,
    to: &std::path::Path,
) -> std::io::Result<(std::ffi::CString, std::ffi::CString)> {
    use std::os::unix::ffi::OsStrExt;
    let bad = || std::io::Error::from(std::io::ErrorKind::InvalidInput);
    let from = std::ffi::CString::new(from.as_os_str().as_bytes()).map_err(|_| bad())?;
    let to = std::ffi::CString::new(to.as_os_str().as_bytes()).map_err(|_| bad())?;
    Ok((from, to))
}

/// A path as NUL-terminated UTF-16, for the Windows calls. An interior NUL would
/// cut the path short, so it is refused as `InvalidInput`.
#[cfg(windows)]
fn wide_path(path: &std::path::Path) -> std::io::Result<Vec<u16>> {
    use std::os::windows::ffi::OsStrExt;
    let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
    if wide.contains(&0) {
        return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput));
    }
    wide.push(0);
    Ok(wide)
}

#[cfg(test)]
mod rename_no_replace_tests {
    use super::rename_file_no_replace;
    use std::io::ErrorKind;
    use std::path::PathBuf;

    /// A scratch directory for one test, removed when the test ends.
    struct Scratch(PathBuf);

    impl Scratch {
        fn new(tag: &str) -> Self {
            let dir = std::env::temp_dir()
                .join(format!("ish-rename-noreplace-{tag}-{}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            Scratch(dir)
        }
    }

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

    /// A directory renamed onto an existing empty directory is refused, and both
    /// directories are as they were. On Windows this is the case that a plain
    /// `std::fs::rename` (MOVEFILE_REPLACE_EXISTING) would change.
    #[test]
    fn directory_onto_an_existing_empty_directory_is_refused_and_both_stay() {
        let s = Scratch::new("dir_onto_empty_dir");
        let src = s.0.join("src_dir");
        let dst = s.0.join("dst_dir");
        std::fs::create_dir(&src).unwrap();
        std::fs::write(src.join("marker.txt"), "src").unwrap();
        std::fs::create_dir(&dst).unwrap();
        let err =
            rename_file_no_replace(&src, &dst).expect_err("an existing destination must refuse");
        assert_eq!(err.kind(), ErrorKind::AlreadyExists);
        assert_eq!(
            std::fs::read_to_string(src.join("marker.txt")).unwrap(),
            "src",
            "source directory changed"
        );
        assert!(dst.is_dir(), "destination directory was removed");
        assert_eq!(
            std::fs::read_dir(&dst).unwrap().count(),
            0,
            "destination directory gained entries"
        );
    }

    /// A file renamed onto an existing file is refused, and both are as they were.
    #[test]
    fn file_onto_an_existing_file_is_refused_and_both_stay() {
        let s = Scratch::new("file_onto_file");
        let a = s.0.join("a.txt");
        let b = s.0.join("b.txt");
        std::fs::write(&a, "alpha").unwrap();
        std::fs::write(&b, "beta").unwrap();
        let err = rename_file_no_replace(&a, &b).expect_err("an existing destination must refuse");
        assert_eq!(err.kind(), ErrorKind::AlreadyExists);
        assert_eq!(
            std::fs::read_to_string(&a).unwrap(),
            "alpha",
            "source changed"
        );
        assert_eq!(
            std::fs::read_to_string(&b).unwrap(),
            "beta",
            "destination replaced"
        );
    }

    /// A directory renamed to a free name moves, and nothing is left at the source.
    #[test]
    fn directory_to_a_free_name_succeeds() {
        let s = Scratch::new("dir_free");
        let src = s.0.join("src_dir");
        let dst = s.0.join("moved_dir");
        std::fs::create_dir(&src).unwrap();
        std::fs::write(src.join("marker.txt"), "src").unwrap();
        rename_file_no_replace(&src, &dst).expect("rename to a free name");
        assert!(!src.exists(), "source still present");
        assert_eq!(
            std::fs::read_to_string(dst.join("marker.txt")).unwrap(),
            "src"
        );
    }
}

/// refactor_rename_file(from, to) - rename a file or directory inside the
/// workspace. The destination must not exist: the rename would otherwise
/// replace it without a word. Both paths are inside the workspace, checked
/// before anything changes, and the rename is recorded for an active
/// transaction.
fn bi_refactor_rename_file(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "refactor_rename_file";
    k8s_no_input(B, &input)?;
    let from = cargo_project::in_workspace_path(B, "from", args.first())?;
    let to = cargo_project::in_workspace_path(B, "to", args.get(1))?;
    if from == to {
        return Err(crate::safety::bad_arg(
            B,
            "a destination that differs from the source",
            "the same path",
        ));
    }
    if std::fs::symlink_metadata(&from).is_err() {
        return Err(crate::safety::not_found(B, "file or directory", &from));
    }
    if std::fs::symlink_metadata(&to).is_ok() {
        return Err(crate::safety::bad_arg(
            B,
            "a destination that does not exist yet",
            &format!("the existing path {to}"),
        ));
    }
    // The containment above is the first check, and it does not see protected
    // paths: a file moved to `.git/hooks/*` or into `.ironshell/` is inside the
    // workspace and used to pass. `guard_local_write` applies the same jail and
    // protected-path refusal that file_write and the other WriteLocal writers
    // use, and audits both ends. The rename then uses the paths it checked.
    let from = guard_local_write(B, &from)?;
    let to = guard_local_write(B, &to)?;
    crate::tx::snapshot(&from);
    crate::tx::snapshot(&to);
    // The destination was checked free above. `rename_file_no_replace` keeps it free
    // at the rename too, where a plain rename would replace one that appeared since.
    match rename_file_no_replace(std::path::Path::new(&from), std::path::Path::new(&to)) {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            return Err(crate::safety::bad_arg(
                B,
                "a destination that does not exist yet",
                &format!("the existing path {to}"),
            ));
        }
        Err(e) => return Err(crate::safety::fs_error(B, &from, &e)),
    }
    Ok(Value::Bool(true))
}

#[path = "extract_function_refactor.rs"]
mod extract_function_refactor;
fn bi_refactor_extract_function(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    extract_function_refactor::run("refactor_extract_function", args, input)
}

fn bi_refactor_extract_variable(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    expression_refactor::run("refactor_extract_variable", args, input)
}

fn bi_refactor_extract_constant(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    expression_refactor::run("refactor_extract_constant", args, input)
}

fn bi_refactor_inline(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    expression_refactor::run("refactor_inline", args, input)
}

#[path = "move_refactor.rs"]
mod move_refactor;
fn bi_refactor_move_to_file(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    move_refactor::run("refactor_move_to_file", args, input)
}

#[path = "signature_refactor.rs"]
mod signature_refactor;
fn bi_refactor_change_signature(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    signature_refactor::run("refactor_change_signature", args, input)
}
fn bi_refactor_add_parameter(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    signature_refactor::run("refactor_add_parameter", args, input)
}
fn bi_refactor_remove_parameter(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    signature_refactor::run("refactor_remove_parameter", args, input)
}

fn bi_refactor_organize_imports(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("file required"))?;
    let content = read_text_capped("refactor_organize_imports", &file)?;
    let mut imports: Vec<&str> = content.lines().filter(|l| l.starts_with("use ")).collect();
    imports.sort();
    Ok(Value::Array(
        imports
            .into_iter()
            .map(|s| Value::Str(s.to_string()))
            .collect(),
    ))
}

/// refactor_remove_unused(dir) - cargo fix over one project.
///
/// This is not a targeted removal. `cargo fix` applies every machine-applicable
/// suggestion the compiler gives, and removing unused imports is one of them; so
/// are the other fixes for the lints that are enabled. The earlier body also
/// passed --allow-dirty, so it rewrote uncommitted work. Like diag_fix, this
/// refuses a version-controlled tree with uncommitted changes.
fn bi_refactor_remove_unused(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "refactor_remove_unused";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    cargo_done(B, &dir, &["fix"])?;
    Ok(Value::Bool(true))
}

// Session module implementations
use std::sync::atomic::{AtomicU64, Ordering};
static SESSION_COUNTER: AtomicU64 = AtomicU64::new(0);

fn bi_session_start(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let id = SESSION_COUNTER.fetch_add(1, Ordering::SeqCst);
    Ok(Value::Int(id as i64))
}

/// Refuse arguments and pipeline input for a builtin that takes neither.
fn no_args_or_input(name: &str, args: &[Value], input: &Option<Value>) -> Result<()> {
    if !args.is_empty() {
        return Err(crate::safety::bad_arg(
            name,
            "no arguments",
            &format!("{} argument(s)", args.len()),
        ));
    }
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            name,
            "no pipeline input",
            "piped input",
        ));
    }
    Ok(())
}

/// The optional step count of `session_undo` and `session_redo`: none means 1,
/// otherwise one Int from 1 to 10000. Anything else is refused, not clamped.
fn step_count_arg(name: &str, args: &[Value], input: &Option<Value>) -> Result<usize> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            name,
            "no pipeline input",
            "piped input",
        ));
    }
    match args {
        [] => Ok(1),
        [Value::Int(n)] if (1..=10_000).contains(n) => Ok(*n as usize),
        [Value::Int(n)] => Err(crate::safety::bad_arg(
            name,
            "a step count from 1 to 10000",
            &n.to_string(),
        )),
        [other] => Err(crate::safety::bad_arg(
            name,
            "an Int step count",
            other.type_name(),
        )),
        more => Err(crate::safety::bad_arg(
            name,
            "at most one step count",
            &format!("{} arguments", more.len()),
        )),
    }
}

/// `session_end()` — keep every change and forget the journal. No files are
/// touched; after this, nothing recorded can be undone or redone.
fn bi_session_end(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("session_end", &args, &input)?;
    let entries = crate::journal::entries();
    let kept = entries.len();
    let irreversible = entries.iter().filter(|e| !e.reversible()).count();
    let discarded_redo = crate::journal::redo_count();
    clear_journal_or_refuse("session_end")?;
    let mut m = std::collections::BTreeMap::new();
    m.insert("kept".to_string(), Value::Int(kept as i64));
    m.insert("irreversible".to_string(), Value::Int(irreversible as i64));
    m.insert(
        "discarded_redo".to_string(),
        Value::Int(discarded_redo as i64),
    );
    m.insert(
        "note".to_string(),
        Value::Str("no files changed; these steps can no longer be undone or redone".to_string()),
    );
    Ok(Value::Record(m))
}

fn bi_session_id(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Int(SESSION_COUNTER.load(Ordering::SeqCst) as i64))
}

/// `session_history()` — the steps that can be undone (`done`) and the steps
/// that can be re-applied (`undone`, most recent last).
fn bi_session_history(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("session_history", &args, &input)?;
    let done = crate::journal::entries();
    let undone: Vec<Value> = crate::journal::undone()
        .iter()
        .map(|r| {
            let mut m = std::collections::BTreeMap::new();
            m.insert("seq".to_string(), Value::Int(r.seq as i64));
            m.insert("builtin".to_string(), Value::Str(r.builtin.clone()));
            m.insert("effect".to_string(), Value::Str(r.effect.clone()));
            if !r.path.is_empty() {
                m.insert("path".to_string(), Value::Str(r.path.clone()));
            }
            Value::Record(m)
        })
        .collect();
    let mut out = std::collections::BTreeMap::new();
    out.insert(
        "enabled".to_string(),
        Value::Bool(crate::journal::enabled()),
    );
    out.insert("done".to_string(), Value::Array(journal_rows(&done)));
    out.insert("undone".to_string(), Value::Array(undone));
    Ok(Value::Record(out))
}

/// `session_undo(n = 1)` — the same record `undo(n)` returns.
fn bi_session_undo(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let counts: Vec<Value> = args
        .iter()
        .filter(|v| !matches!(v, Value::Record(_)))
        .cloned()
        .collect();
    let n = step_count_arg("session_undo", &counts, &input)?;
    let force = undo_force("session_undo", &args)?;
    refuse_unless_recording("session_undo")?;
    undo_record("session_undo", n, force)
}

/// `session_redo(n = 1)` — re-apply the last `n` undone steps.
fn bi_session_redo(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let n = step_count_arg("session_redo", &args, &input)?;
    refuse_unless_recording("session_redo")?;
    let outcomes: Vec<crate::journal::Rewound> = crate::journal::redo(n)
        .into_iter()
        .map(|outcome| crate::journal::Rewound { seq: None, outcome })
        .collect();
    Ok(Value::Record(rewind_record(&outcomes, "reapplied")))
}

fn bi_session_checkpoint(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("session_checkpoint", &input)?;
    // A non-string label used to fall back silently to "checkpoint".
    let name = match args.first() {
        Some(v) => expect_string("session_checkpoint", v)?.to_string(),
        None => "checkpoint".to_string(),
    };
    // This ran `git stash push`, which saves the changes and then REMOVES
    // them from the working tree: a "checkpoint" that erased the work it was
    // meant to protect. With nothing to save git exits 0, so it also answered
    // true having saved nothing. `stash create` records the changes without
    // touching the tree; `stash store` keeps that record in the stash list.
    // Both git calls are checked the same way: outside a repository these
    // are E_BAD_STATE, a failed git is E_TOOL_FAILED with its stderr tail.
    let mut cmd = git_command();
    cmd.args(["stash", "create"]);
    let output = bounded_cmd_output("session_checkpoint", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("session_checkpoint", &output, ".")?;
    let sha = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if sha.is_empty() {
        // Not an error: the tree has no changes, so there is nothing to keep.
        return Ok(Value::Bool(false));
    }
    let mut cmd = git_command();
    cmd.args(["stash", "store", "-m", &name, &sha]);
    let output = bounded_cmd_output("session_checkpoint", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("session_checkpoint", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_session_restore(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("session_restore", &input)?;
    let index = args
        .first()
        .map(|v| expect_int("session_restore", v))
        .transpose()?
        .unwrap_or(0);
    let mut cmd = git_command();
    cmd.args([
        "rev-parse",
        "--verify",
        "--quiet",
        &format!("stash@{{{}}}", index),
    ]);
    let check = bounded_cmd_output("session_restore", "git", cmd, TOOL_DEADLINE_SECS)?;
    if !check.status.success() {
        // A missing checkpoint is not a git failure: git's own answer for it
        // is exit 1 with no text, which the generic path reported as E_TOOL_FAILED.
        let mut cmd = git_command();
        cmd.args(["rev-parse", "--is-inside-work-tree"]);
        let in_repo = bounded_cmd_output("session_restore", "git", cmd, TOOL_DEADLINE_SECS)
            .is_ok_and(|o| o.status.success());
        if in_repo {
            return Err(crate::safety::not_found(
                "session_restore",
                "checkpoint",
                &index.to_string(),
            ));
        }
        git_succeeded("session_restore", &check, ".")?;
    }
    let mut cmd = git_command();
    cmd.args(["stash", "apply", &format!("stash@{{{}}}", index)]);
    let output = bounded_cmd_output("session_restore", "git", cmd, TOOL_DEADLINE_SECS)?;
    // `false` said "not restored" and dropped why: no repository, no such
    // checkpoint, or a conflict. Those need different next steps.
    git_succeeded("session_restore", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_session_checkpoints(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("session_checkpoints", &input)?;
    bi_git_stash_list(args, None)
}

fn bi_session_diff_since(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("session_diff_since", &input)?;
    let commit = args
        .first()
        .map(|v| expect_string("session_diff_since", v).map(str::to_string))
        .transpose()?
        .unwrap_or("HEAD~1".to_string());
    crate::safety::reject_option_like("session_diff_since", std::slice::from_ref(&commit))?;
    let mut cmd = git_command();
    cmd.args(["diff", "--no-ext-diff", "--no-textconv", &commit]);
    let output = bounded_cmd_output("session_diff_since", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("session_diff_since", &output, ".")?;
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stdout).to_string(),
    ))
}

fn bi_session_changes(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("session_changes", &input)?;
    bi_git_status(vec![], None)
}

fn bi_session_rollback(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("session_rollback", &input)?;
    // A non-string commit used to fall back silently to HEAD and still reset.
    let commit = match args.first() {
        Some(v) => expect_string("session_rollback", v)?.to_string(),
        None => "HEAD".to_string(),
    };
    crate::safety::reject_option_like("session_rollback", std::slice::from_ref(&commit))?;
    let mut cmd = git_command();
    cmd.args(["reset", "--hard", &commit]);
    let output = bounded_cmd_output("session_rollback", "git", cmd, TOOL_DEADLINE_SECS)?;
    // Was `Bool(success)`: a failed reset answered false with no reason.
    git_succeeded("session_rollback", &output, ".")?;
    Ok(Value::Bool(true))
}

fn bi_session_export(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    git_refuse_input("session_export", &input)?;
    let file = args
        .first()
        .map(|v| expect_string("session_export", v).map(str::to_string))
        .transpose()?
        .unwrap_or("session.patch".to_string());
    // Same again: labelled `ReadLocal`, writes an arbitrary path.
    let file = guard_local_write("session_export", &file)?;
    let mut cmd = git_command();
    cmd.args(["diff", "--no-ext-diff", "--no-textconv"]);
    let output = bounded_cmd_output("session_export", "git", cmd, TOOL_DEADLINE_SECS)?;
    git_succeeded("session_export", &output, ".")?;
    crate::tx::snapshot(&file); // record pre-export state if a transaction is active
    write_file_atomically("session_export", &file, &output.stdout)?;
    Ok(Value::Str(file))
}

// Docs module implementations
/// docs_generate(dir) - cargo doc --no-deps for one project. Like every cargo
/// call here it runs in that directory, under the long deadline.
fn bi_docs_generate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "docs_generate";
    k8s_no_input(B, &input)?;
    let dir = project_dir(B, args.first())?;
    cargo_done(B, &dir, &["doc", "--no-deps"])?;
    Ok(Value::Bool(true))
}

fn bi_docs_search(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // In-process, as "file:line: text" like the grep it replaces. That grep
    // took the query as a pattern (a leading `-` was an option), does not
    // exist on Windows, and exited 2 with [] when there were no docs, which
    // read as "no matches".
    let query = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("query required"))?;
    let root = std::path::Path::new("target/doc");
    if !entry_is_dir("docs_search", root)? {
        return Err(crate::safety::not_found(
            "docs_search",
            "documentation directory",
            "target/doc (run `cargo doc` first)",
        ));
    }
    const LIMIT: usize = 20;
    let mut matches = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    // An unreadable directory or entry used to be skipped, so the match list
    // looked complete when it was not. Those are errors now. A file that is
    // not UTF-8 is searched as lossy text, not skipped.
    while let Some(dir) = stack.pop() {
        let mut entries = Vec::new();
        for entry in
            std::fs::read_dir(&dir).map_err(|e| crate::safety::fs_error("docs_search", &dir, &e))?
        {
            let entry = entry.map_err(|e| crate::safety::fs_error("docs_search", &dir, &e))?;
            entries.push(entry.path());
        }
        entries.sort();
        for p in entries {
            if entry_is_dir("docs_search", &p)? {
                stack.push(p);
                continue;
            }
            // Capped like every whole-file read: a doc over the limit is an
            // error, not a search of part of it.
            let bytes = match read_bytes_capped("docs_search", &p) {
                Ok(bytes) => bytes,
                // A dangling link has no text to search.
                Err(e) if capped_read_not_found(&e) => continue,
                Err(e) => return Err(e),
            };
            let text = String::from_utf8_lossy(&bytes);
            for (i, line) in text.lines().enumerate() {
                if line.contains(&query) {
                    matches.push(Value::Str(format!(
                        "{}:{}: {}",
                        p.display(),
                        i + 1,
                        line.trim()
                    )));
                    if matches.len() == LIMIT {
                        return Ok(Value::Array(matches));
                    }
                }
            }
        }
    }
    Ok(Value::Array(matches))
}

fn bi_docs_api(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    code_search::run("docs_api", args, input)
}

fn bi_docs_readme(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    bi_project_readme(_args, _input)
}

fn bi_docs_changelog(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    first_project_text(
        "docs_changelog",
        &["CHANGELOG.md", "CHANGELOG", "CHANGES.md", "HISTORY.md"],
    )
}

fn bi_docs_examples(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut examples = Vec::new();
    if std::path::Path::new("examples").is_dir() {
        if let Ok(entries) = std::fs::read_dir("examples") {
            for entry in entries.flatten() {
                examples.push(Value::Str(entry.path().to_string_lossy().to_string()));
            }
        }
    }
    // read_dir's order is the filesystem's, not a stable one.
    examples.sort_by_key(|v| v.to_display_string());
    Ok(Value::Array(examples))
}

fn bi_docs_types(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    extract_rust_documentation("docs_types", args, input, false)
}

fn bi_docs_signatures(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    extract_rust_documentation("docs_signatures", args, input, true)
}

fn extract_rust_documentation(
    name: &str,
    args: Vec<Value>,
    input: Option<Value>,
    functions: bool,
) -> Result<Value> {
    use quote::ToTokens;
    if args.len() != 1 || input.is_some() {
        return Err(crate::safety::bad_arg(
            name,
            "one Rust source String; no pipeline input",
            "invalid call shape",
        ));
    }
    let Value::Str(source) = &args[0] else {
        return Err(crate::safety::bad_arg(
            name,
            "Rust source String",
            args[0].type_name(),
        ));
    };
    if source.len() > 1024 * 1024 {
        return Err(crate::safety::budget_exceeded(
            name,
            "Rust source exceeds 1 MiB".into(),
            "extract from a smaller source unit",
        ));
    }
    // Conservative complexity preflight before token-tree/AST construction.
    // Count punctuation even inside strings/comments so they cannot hide nested
    // syntax from this budget. Callers can submit smaller source units.
    if source
        .bytes()
        .filter(u8::is_ascii_punctuation)
        .take(129)
        .count()
        > 128
    {
        return Err(crate::safety::budget_exceeded(name, "raw syntax punctuation exceeds 128".into(), "extract from smaller source units; the conservative budget includes strings and comments"));
    }
    let file = syn::parse_file(source)
        .map_err(|_| crate::safety::bad_arg(name, "valid Rust source", "syntax error"))?;
    let mut rows = Vec::new();
    for item in file.items {
        let mut row = std::collections::BTreeMap::new();
        if functions {
            if let syn::Item::Fn(function) = item {
                row.insert("name".into(), Value::Str(function.sig.ident.to_string()));
                row.insert(
                    "signature".into(),
                    Value::Str(function.sig.to_token_stream().to_string()),
                );
                row.insert(
                    "async".into(),
                    Value::Bool(function.sig.asyncness.is_some()),
                );
            } else {
                continue;
            }
        } else {
            let (ident, kind) = match &item {
                syn::Item::Struct(x) => (&x.ident, "struct"),
                syn::Item::Enum(x) => (&x.ident, "enum"),
                syn::Item::Union(x) => (&x.ident, "union"),
                syn::Item::Trait(x) => (&x.ident, "trait"),
                syn::Item::Type(x) => (&x.ident, "alias"),
                _ => continue,
            };
            row.insert("name".into(), Value::Str(ident.to_string()));
            row.insert("kind".into(), Value::Str(kind.into()));
            row.insert(
                "definition".into(),
                Value::Str(item.to_token_stream().to_string()),
            );
        }
        rows.push(Value::Record(row));
    }
    rows.sort_by(|a, b| {
        let Value::Record(a) = a else { unreachable!() };
        let Value::Record(b) = b else { unreachable!() };
        a.get("name")
            .unwrap()
            .to_display_string()
            .cmp(&b.get("name").unwrap().to_display_string())
    });
    Ok(Value::Array(rows))
}

// Environment module implementations
fn bi_env_detect(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut env = BTreeMap::new();
    env.insert(
        "os".to_string(),
        Value::Str(std::env::consts::OS.to_string()),
    );
    env.insert(
        "arch".to_string(),
        Value::Str(std::env::consts::ARCH.to_string()),
    );
    env.insert(
        "family".to_string(),
        Value::Str(std::env::consts::FAMILY.to_string()),
    );
    Ok(Value::Record(env))
}

fn bi_env_python(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("python");
    cmd.args(["--version"]);
    let output = bounded_cmd_output("env_python", "python", cmd, PROBE_DEADLINE_SECS)?;
    // The exit status was ignored, so a failed command's output came
    // back as the answer. On WSL, `docker` is a shim that exists,
    // prints "could not be found in this WSL 2 distro" and exits
    // non-zero -- and this returned that sentence as the version.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "env_python",
            "python",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    // Several of these print their version to stderr rather than
    // stdout, so an empty stdout on a SUCCESSFUL run is not an error.
    let out = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !out.is_empty() {
        return Ok(Value::Str(out));
    }
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stderr).trim().to_string(),
    ))
}

fn bi_env_node(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("node");
    cmd.args(["--version"]);
    let output = bounded_cmd_output("env_node", "node", cmd, PROBE_DEADLINE_SECS)?;
    // The exit status was ignored, so a failed command's output came
    // back as the answer. On WSL, `docker` is a shim that exists,
    // prints "could not be found in this WSL 2 distro" and exits
    // non-zero -- and this returned that sentence as the version.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "env_node",
            "node",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    // Several of these print their version to stderr rather than
    // stdout, so an empty stdout on a SUCCESSFUL run is not an error.
    let out = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !out.is_empty() {
        return Ok(Value::Str(out));
    }
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stderr).trim().to_string(),
    ))
}

fn bi_env_rust(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("rustc");
    cmd.args(["--version"]);
    let output = bounded_cmd_output("env_rust", "rustc", cmd, PROBE_DEADLINE_SECS)?;
    // The exit status was ignored, so a failed command's output came
    // back as the answer. On WSL, `docker` is a shim that exists,
    // prints "could not be found in this WSL 2 distro" and exits
    // non-zero -- and this returned that sentence as the version.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "env_rust",
            "rustc",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    // Several of these print their version to stderr rather than
    // stdout, so an empty stdout on a SUCCESSFUL run is not an error.
    let out = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !out.is_empty() {
        return Ok(Value::Str(out));
    }
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stderr).trim().to_string(),
    ))
}

fn bi_env_go(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("go");
    cmd.args(["version"]);
    cmd.env("GOTOOLCHAIN", "local");
    let output = bounded_cmd_output("env_go", "go", cmd, PROBE_DEADLINE_SECS)?;
    // The exit status was ignored, so a failed command's output came
    // back as the answer. On WSL, `docker` is a shim that exists,
    // prints "could not be found in this WSL 2 distro" and exits
    // non-zero -- and this returned that sentence as the version.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "env_go",
            "go",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    // Several of these print their version to stderr rather than
    // stdout, so an empty stdout on a SUCCESSFUL run is not an error.
    let out = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !out.is_empty() {
        return Ok(Value::Str(out));
    }
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stderr).trim().to_string(),
    ))
}

fn bi_env_java(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("java");
    cmd.args(["--version"]);
    let output = bounded_cmd_output("env_java", "java", cmd, PROBE_DEADLINE_SECS)?;
    // Same exit-status gap as the rest of the family; this one takes only
    // the first line, so a multi-line failure message was truncated into
    // something that looked even more like a version string.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "env_java",
            "java",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    let first = |s: &str| s.lines().next().unwrap_or("").to_string();
    let out = first(&String::from_utf8_lossy(&output.stdout));
    if !out.is_empty() {
        return Ok(Value::Str(out));
    }
    // `java -version` writes to stderr on older JDKs.
    Ok(Value::Str(first(&String::from_utf8_lossy(&output.stderr))))
}

fn bi_env_dotnet(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("dotnet");
    cmd.args(["--version"]);
    let output = bounded_cmd_output("env_dotnet", "dotnet", cmd, PROBE_DEADLINE_SECS)?;
    // The exit status was ignored, so a failed command's output came
    // back as the answer. On WSL, `docker` is a shim that exists,
    // prints "could not be found in this WSL 2 distro" and exits
    // non-zero -- and this returned that sentence as the version.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "env_dotnet",
            "dotnet",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    // Several of these print their version to stderr rather than
    // stdout, so an empty stdout on a SUCCESSFUL run is not an error.
    let out = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !out.is_empty() {
        return Ok(Value::Str(out));
    }
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stderr).trim().to_string(),
    ))
}

fn bi_env_ruby(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("ruby");
    cmd.args(["--version"]);
    let output = bounded_cmd_output("env_ruby", "ruby", cmd, PROBE_DEADLINE_SECS)?;
    // The exit status was ignored, so a failed command's output came
    // back as the answer. On WSL, `docker` is a shim that exists,
    // prints "could not be found in this WSL 2 distro" and exits
    // non-zero -- and this returned that sentence as the version.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "env_ruby",
            "ruby",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    // Several of these print their version to stderr rather than
    // stdout, so an empty stdout on a SUCCESSFUL run is not an error.
    let out = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !out.is_empty() {
        return Ok(Value::Str(out));
    }
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stderr).trim().to_string(),
    ))
}

fn bi_env_shell(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Neither variable set was "", which names no shell. It is not an answer.
    match std::env::var("SHELL").or_else(|_| std::env::var("COMSPEC")) {
        Ok(shell) => Ok(Value::Str(shell)),
        Err(_) => Err(crate::safety::not_found(
            "env_shell",
            "shell",
            "SHELL or COMSPEC",
        )),
    }
}

/// Read one environment variable for a builtin. `Ok(None)` is an unset
/// variable. A variable that is set but not valid UTF-8 is refused: it used
/// to read as unset, which is a different fact from absence.
fn env_read(
    builtin: &str,
    name: &str,
    read: Result<String, std::env::VarError>,
) -> Result<Option<String>> {
    match read {
        Ok(v) => Ok(Some(v)),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(std::env::VarError::NotUnicode(_)) => Err(crate::safety::bad_state(
            builtin,
            &format!("environment variable `{name}` is set, but its value is not valid UTF-8"),
            "env_set",
        )),
    }
}

fn bi_env_path(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // A PATH that is not valid UTF-8 read as an empty one.
    let path = env_read("env_path", "PATH", std::env::var("PATH"))?.unwrap_or_default();
    let parts: Vec<Value> = path
        .split(if cfg!(windows) { ";" } else { ":" })
        // An empty entry ("a::b", or PATH unset) is no directory.
        .filter(|p| !p.is_empty())
        .map(|p| Value::Str(p.to_string()))
        .collect();
    Ok(Value::Array(parts))
}

fn bi_env_var(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("variable name required"))?;
    // Unset was "", where env() and sys.env() answer null.
    Ok(match env_read("env_var", &name, std::env::var(&name))? {
        Some(v) => gate_env_secret(&name, v),
        None => Value::Null,
    })
}

/// env_vars() - every variable as a Record. In agent mode a value whose name
/// looks like a secret is replaced with a redaction marker, as env_var does.
/// Non-UTF-8 names and values are shown lossily: `std::env::vars` panics on
/// them, so this reads the OS strings.
fn bi_env_vars(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "env_vars";
    k8s_no_input(B, &input)?;
    if !args.is_empty() {
        return Err(crate::safety::bad_arg(
            B,
            "no arguments",
            &format!("{} argument(s)", args.len()),
        ));
    }
    let vars: BTreeMap<String, Value> = std::env::vars_os()
        .map(|(k, v)| {
            let k = k.to_string_lossy().into_owned();
            let gated = gate_env_secret(&k, v.to_string_lossy().into_owned());
            (k, gated)
        })
        .collect();
    Ok(Value::Record(vars))
}

/// env_set(name, value) - set an environment variable of this process.
fn bi_env_set(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "env_set";
    k8s_no_input(B, &input)?;
    if args.len() < 2 {
        return Err(crate::safety::arg_err("name and value required"));
    }
    let name = env_name(B, &args[0])?;
    refuse_gate_env(B, &name)?;
    let value = env_value(B, &args[1])?;
    std::env::set_var(&name, &value);
    Ok(Value::Bool(true))
}

fn bi_env_unset(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    const B: &str = "env_unset";
    let raw = args
        .first()
        .ok_or_else(|| crate::safety::arg_err("variable name required"))?;
    let name = env_name(B, raw)?;
    refuse_gate_env(B, &name)?;
    std::env::remove_var(&name);
    Ok(Value::Bool(true))
}

fn bi_env_docker(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("docker");
    cmd.args(["--version"]);
    let output = bounded_cmd_output("env_docker", "docker", cmd, PROBE_DEADLINE_SECS)?;
    // The exit status was ignored, so a failed command's output came
    // back as the answer. On WSL, `docker` is a shim that exists,
    // prints "could not be found in this WSL 2 distro" and exits
    // non-zero -- and this returned that sentence as the version.
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            "env_docker",
            "docker",
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    // Several of these print their version to stderr rather than
    // stdout, so an empty stdout on a SUCCESSFUL run is not an error.
    let out = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !out.is_empty() {
        return Ok(Value::Str(out));
    }
    Ok(Value::Str(
        String::from_utf8_lossy(&output.stderr).trim().to_string(),
    ))
}

fn bi_env_container(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let in_docker = std::path::Path::new("/.dockerenv").exists();
    let in_container = std::env::var("container").is_ok();
    Ok(Value::Bool(in_docker || in_container))
}

fn bi_env_venv(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Null when no virtualenv is active, as `env("VIRTUAL_ENV")` and
    // `sys.env(...)` answer for any unset variable. It was "", the one
    // exception, so an agent had to learn a second spelling of "absent".
    Ok(std::env::var("VIRTUAL_ENV")
        .ok()
        .filter(|v| !v.is_empty())
        .map_or(Value::Null, Value::Str))
}

fn bi_env_activate(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let venv = args
        .first()
        .and_then(|v| v.as_str().ok())
        .map(|s| s.to_string())
        .ok_or_else(|| crate::safety::arg_err("venv path required"))?;
    let activate = if cfg!(windows) {
        format!("{}\\Scripts\\activate", venv)
    } else {
        format!("{}/bin/activate", venv)
    };
    Ok(Value::Str(format!("source {}", activate)))
}

// ============================================================================
// Platform Versioning Module - Cross-platform determinism for AI agents
// ============================================================================

/// Path of the platform store: `$HOME/.ironshell/platform_db.json`, or under
/// `%USERPROFILE%` where HOME is unset. HOME relocates it; the tests use that.
///
/// With neither set there is no home to live in. This used to fall back to `.`,
/// which wrote the store into whatever directory the call happened to run from.
fn platform_db_path() -> Result<std::path::PathBuf> {
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map_err(|_| {
            crate::safety::bad_state(
                "platform_db",
                "neither HOME nor USERPROFILE is set, so the platform store has no home directory",
                "HOME",
            )
        })?;
    Ok(std::path::Path::new(&home)
        .join(".ironshell")
        .join("platform_db.json"))
}

/// Refuse piped input. The platform builtins answer from the host or from the
/// store, so a value piped into them would be dropped without a word.
fn platform_refuse_input(builtin: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            builtin,
            "no pipeline input",
            "piped input",
        ));
    }
    Ok(())
}

/// The string argument at `index`, or `None` when it was not passed. Any other
/// type is refused. (The declaration checks types too; this keeps the body from
/// ever substituting a default for a value it was given.)
fn platform_str_arg(builtin: &str, args: &[Value], index: usize) -> Result<Option<String>> {
    match args.get(index) {
        None => Ok(None),
        Some(Value::Str(s)) => Ok(Some(s.clone())),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            "a string",
            other.type_name(),
        )),
    }
}

/// Parse the platform store. A store that is not a JSON object is E_BAD_STATE:
/// read as empty and written back, it would lose every entry in it.
fn platform_store_parse(
    builtin: &str,
    path: &std::path::Path,
    content: &str,
) -> Result<serde_json::Map<String, serde_json::Value>> {
    serde_json::from_str(content).map_err(|e| {
        crate::safety::bad_state_with_hint(
            builtin,
            &format!(
                "the platform store {} is not valid JSON: {e}",
                path.display()
            ),
            "repair or delete the file; nothing was written",
        )
    })
}

/// Get tool version by running command with --version
/// Whether `name` is an executable on `PATH`, answered from an index of the
/// `PATH` directories that is built once and reused.
///
/// Looking a tool up used to stat every `PATH` entry, once per tool, per call.
/// Under WSL, 107 of 117 `PATH` entries are Windows directories reached over
/// 9P, so `platform_detect_tools` -- sixty `which` lookups -- took 14.5s, and
/// 0.1s with the Windows entries removed. Listing each directory once and
/// answering every later question from memory makes a missing tool free.
///
/// Keyed on the value of `PATH`, so a script that changes `PATH` gets a fresh
/// index rather than a stale answer. On Unix a hit must also be executable;
/// on Windows a name matches with any `PATHEXT` extension, as `which` did.
fn on_path(name: &str) -> bool {
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};
    static INDEX: Mutex<Option<(String, Arc<HashMap<String, std::path::PathBuf>>)>> =
        Mutex::new(None);

    if name.is_empty() || name.contains(['/', '\\']) {
        return std::path::Path::new(name).is_file();
    }
    let path_var = std::env::var("PATH").unwrap_or_default();
    let index = {
        let mut guard = INDEX.lock().unwrap_or_else(|e| e.into_inner());
        match guard.as_ref() {
            Some((key, idx)) if *key == path_var => Arc::clone(idx),
            _ => {
                let mut idx = HashMap::new();
                for dir in std::env::split_paths(&path_var) {
                    let Ok(rd) = std::fs::read_dir(&dir) else {
                        continue;
                    };
                    for e in rd.flatten() {
                        let file = e.file_name().to_string_lossy().to_string();
                        let key = if cfg!(windows) {
                            file.to_lowercase()
                        } else {
                            file
                        };
                        // First occurrence wins, as PATH order does.
                        idx.entry(key).or_insert_with(|| e.path());
                    }
                }
                let idx = Arc::new(idx);
                *guard = Some((path_var, Arc::clone(&idx)));
                idx
            }
        }
    };

    if cfg!(windows) {
        let exts = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
        let lower = name.to_lowercase();
        return index.contains_key(&lower)
            || exts
                .split(';')
                .filter(|x| !x.is_empty())
                .any(|x| index.contains_key(&format!("{lower}{}", x.to_lowercase())));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        return index.get(name).is_some_and(|p| {
            std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
        });
    }
    #[allow(unreachable_code)]
    index.contains_key(name)
}

/// The Azure CLI's version, read from its installed package metadata.
///
/// Running `az` at all can reach the network. With no version cache -- a new
/// home, anyone's first run -- it fetches the latest release list before
/// answering, `az version` included; the egress gate caught it doing so once
/// the probes stopped sharing the developer's HOME. The installed version is
/// in the name of an `azure_cli-<version>.dist-info` directory, found from the
/// launcher: its own tree (the Windows MSI, a Homebrew keg), or the Python
/// interpreter a launcher script names (`/usr/bin/az` runs
/// `/opt/az/bin/python3` in the Debian package).
fn az_version_offline() -> Option<String> {
    use std::path::{Path, PathBuf};
    let path_var = std::env::var_os("PATH")?;
    let names: &[&str] = if cfg!(windows) {
        &["az.cmd", "az.bat", "az"]
    } else {
        &["az"]
    };
    let az = std::env::split_paths(&path_var)
        .flat_map(|d| names.iter().map(move |n| d.join(n)))
        .find(|p| p.is_file())?;
    let real = std::fs::canonicalize(&az).unwrap_or(az);

    let mut roots: Vec<PathBuf> = real
        .ancestors()
        .skip(1)
        .take(3)
        .map(Path::to_path_buf)
        .collect();
    if let Ok(bytes) = std::fs::read(&real) {
        if bytes.len() < 16 * 1024 {
            let text = String::from_utf8_lossy(&bytes);
            for tok in text.split(|c: char| c.is_whitespace() || c == '"' || c == '\'') {
                let tok = tok.trim_start_matches("#!");
                if tok.starts_with('/') && tok.contains("python") {
                    if let Some(prefix) = Path::new(tok).parent().and_then(Path::parent) {
                        roots.push(prefix.to_path_buf());
                    }
                }
            }
        }
    }

    for root in roots {
        for lib in ["lib", "Lib", "libexec/lib"] {
            let lib = root.join(lib);
            let mut site_dirs = vec![lib.join("site-packages")];
            if let Ok(rd) = std::fs::read_dir(&lib) {
                for e in rd.flatten() {
                    if e.file_name().to_string_lossy().starts_with("python") {
                        site_dirs.push(e.path().join("site-packages"));
                    }
                }
            }
            for sp in site_dirs {
                let Ok(rd) = std::fs::read_dir(&sp) else {
                    continue;
                };
                for e in rd.flatten() {
                    let name = e.file_name().to_string_lossy().to_string();
                    if let Some(v) = name
                        .strip_prefix("azure_cli-")
                        .and_then(|r| r.strip_suffix(".dist-info"))
                    {
                        return Some(v.to_string());
                    }
                }
            }
        }
    }
    None
}

/// Whether the first `bazel` on PATH is bazelisk, which fetches a Bazel
/// release (hundreds of megabytes, over the network) to answer `--version`.
fn resolves_to_bazelisk() -> bool {
    let path_var = std::env::var_os("PATH").unwrap_or_default();
    std::env::split_paths(&path_var)
        .map(|d| d.join(if cfg!(windows) { "bazel.exe" } else { "bazel" }))
        .find(|p| p.is_file())
        .and_then(|p| std::fs::canonicalize(p).ok())
        .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase()))
        .is_some_and(|n| n.contains("bazelisk"))
}

/// How long one `<tool> --version` may take. A version string that has not
/// arrived by then is not going to be useful to an agent waiting on it.
const TOOL_VERSION_TIMEOUT_SECS: u64 = 5;

/// The first line of `<tool> --version`, or `None` if the tool is absent,
/// fails, or does not answer in time.
///
/// The exit status used to be ignored, so a tool that ran and failed had its
/// error line recorded as its version. On WSL the `docker` shim exists, prints
/// "The command 'docker' could not be found in this WSL 2 distro" and exits
/// non-zero -- and that sentence would have been reported as Docker's version.
/// It also waited forever: see [`probe_tool_versions`] for what that cost.
///
/// Asking a tool its version must not reach the network, and several did:
/// with IRONSHELL_MAX_NET=0, `benches/agentic/network-egress.mjs` traced
/// connections from the tools themselves. `kubectl version` contacts the API
/// server (localhost:8080 by default); `docker version` asks the daemon, and
/// exits non-zero when none runs, which read as "not installed"; packer
/// checked HashiCorp for updates; vcpkg and the Azure CLI sent telemetry; and
/// `bazel`, when it is bazelisk, downloads Bazel itself. So: client-only
/// subcommands, the vendors' documented opt-outs, and bazelisk is not run.
fn get_tool_version(tool: &str) -> Option<String> {
    let version_args: &[&str] = match tool {
        "java" => &["-version"],
        "go" => &["version"],
        "kubectl" => &["version", "--client"],
        _ => &["--version"],
    };
    if !on_path(tool) {
        return None;
    }
    if tool == "az" {
        // Never run: see az_version_offline.
        return Some(match az_version_offline() {
            Some(v) => format!("azure-cli {v}"),
            None => "azure-cli (installed; version not found offline)".to_string(),
        });
    }
    if tool == "bazel" && resolves_to_bazelisk() {
        return Some("bazelisk (Bazel is downloaded on first use; not run)".to_string());
    }
    let mut cmd = crate::safety::child_command(tool);
    cmd.args(version_args);
    for (k, v) in [
        ("CHECKPOINT_DISABLE", "1"),    // HashiCorp: packer, terraform, vault
        ("VCPKG_DISABLE_METRICS", "1"), // vcpkg
        ("AZURE_CORE_COLLECT_TELEMETRY", "no"), // az
        ("DOTNET_CLI_TELEMETRY_OPTOUT", "1"), // dotnet
        ("POWERSHELL_TELEMETRY_OPTOUT", "1"), // pwsh
        ("POWERSHELL_UPDATECHECK", "Off"), // pwsh
        ("GOTOOLCHAIN", "local"),       // go: never fetch a toolchain
        ("HOMEBREW_NO_AUTO_UPDATE", "1"), // brew
        ("HOMEBREW_NO_ANALYTICS", "1"),
        // gcloud: on a first run it resolves metadata.google.internal to ask
        // whether it is on Compute Engine; the egress gate caught that lookup.
        ("CLOUDSDK_CORE_CHECK_GCE_METADATA", "false"),
        ("CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK", "true"),
        ("CLOUDSDK_CORE_DISABLE_USAGE_REPORTING", "true"), // brew
    ] {
        cmd.env(k, v);
    }
    let o = crate::safety::output_with_timeout(cmd, TOOL_VERSION_TIMEOUT_SECS).ok()?;
    if !o.status.success() {
        return None;
    }
    let out = String::from_utf8_lossy(&o.stdout);
    let err = String::from_utf8_lossy(&o.stderr);
    // Several tools (`java -version` among them) print to stderr.
    let combined = if out.trim().is_empty() { err } else { out };
    combined
        .lines()
        .next()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Every tool in `tools` that answers, with its version, in the input order.
///
/// Probed in parallel. The `platform_*` builtins asked 20-60 tools one after
/// another, each with an unbounded wait, so their cost was the SUM of every
/// probe: 5-108 seconds per call on WSL, where looking up a missing tool walks
/// every PATH entry including the Windows ones over 9P.
/// `platform_tool_versions` took 108 seconds. In parallel, with each probe
/// bounded, the cost is roughly the slowest single tool.
fn probe_tool_versions(tools: &[&str]) -> Vec<(String, String)> {
    std::thread::scope(|scope| {
        let handles: Vec<_> = tools
            .iter()
            .map(|&t| scope.spawn(move || (t.to_string(), get_tool_version(t))))
            .collect();
        handles
            .into_iter()
            .filter_map(|h| h.join().ok())
            .filter_map(|(t, v)| v.map(|v| (t, v)))
            .collect()
    })
}

/// PRETTY_NAME from /etc/os-release text, without its quotes.
#[cfg(any(not(target_os = "windows"), test))]
fn os_release_pretty_name(content: &str) -> Option<String> {
    content
        .lines()
        .find_map(|line| line.strip_prefix("PRETTY_NAME="))
        .map(|name| name.trim_matches('"').to_string())
}

/// Complete system snapshot with all versioning info
fn bi_platform_snapshot(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_snapshot", &input)?;
    let mut snapshot = std::collections::BTreeMap::new();

    // Timestamp
    snapshot.insert(
        "timestamp".to_string(),
        Value::Str(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs().to_string())
                .unwrap_or_else(|_| "0".to_string()),
        ),
    );

    // OS info
    snapshot.insert(
        "os".to_string(),
        Value::Str(std::env::consts::OS.to_string()),
    );
    snapshot.insert(
        "arch".to_string(),
        Value::Str(std::env::consts::ARCH.to_string()),
    );
    snapshot.insert(
        "family".to_string(),
        Value::Str(std::env::consts::FAMILY.to_string()),
    );

    // The identity probes. A failed one refuses the whole snapshot: these
    // fields feed the fingerprint, so a missing or empty one would change it
    // silently. The old code left the field out, or wrote "" for a failed
    // `hostname` or `uname`. The hostname is read in-process, as
    // `sys_hostname` reads it, since minimal containers have no `hostname`.
    let hostname = bi_sys_hostname(Vec::new(), None)?;
    snapshot.insert("hostname".to_string(), hostname);

    #[cfg(target_os = "windows")]
    {
        // The same strings as when they came from `cmd /c ver`, so the
        // fingerprint is unchanged on an English host.
        let version = WindowsVersion::read("platform_snapshot")?;
        snapshot.insert("os_version".to_string(), Value::Str(version.ver_line()));
        snapshot.insert("build".to_string(), Value::Str(version.build.to_string()));
    }

    #[cfg(not(target_os = "windows"))]
    {
        let mut cmd = crate::safety::child_command("uname");
        cmd.arg("-r");
        let kernel = probe_text("platform_snapshot", "uname", cmd)?;
        snapshot.insert("kernel".to_string(), Value::Str(kernel));
        let mut cmd = crate::safety::child_command("uname");
        cmd.arg("-v");
        let build = probe_text("platform_snapshot", "uname", cmd)?;
        snapshot.insert("build".to_string(), Value::Str(build));
        // Optional by design: not every Unix ships /etc/os-release (macOS does
        // not). Then the record omits os_version rather than guessing one.
        if let Ok(content) = std::fs::read_to_string("/etc/os-release") {
            if let Some(name) = os_release_pretty_name(&content) {
                snapshot.insert("os_version".to_string(), Value::Str(name));
            }
        }
    }

    // Tool versions
    let tools = [
        "git",
        "python",
        "python3",
        "node",
        "npm",
        "cargo",
        "rustc",
        "go",
        "java",
        "docker",
        "kubectl",
        "terraform",
        "aws",
        "az",
        "gcloud",
    ];
    let mut tool_versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&tools) {
        let tool = tool.as_str();
        tool_versions.insert(tool.to_string(), Value::Str(ver));
    }
    snapshot.insert("tools".to_string(), Value::Record(tool_versions));

    // Environment variables that affect behavior
    let env_vars = [
        "PATH",
        "HOME",
        "USER",
        "SHELL",
        "TERM",
        "LANG",
        "LC_ALL",
        "CARGO_HOME",
        "RUSTUP_HOME",
        "GOPATH",
        "JAVA_HOME",
        "PYTHONPATH",
    ];
    let mut env_map = std::collections::BTreeMap::new();
    for var in env_vars {
        if let Ok(val) = std::env::var(var) {
            env_map.insert(var.to_string(), Value::Str(val));
        }
    }
    snapshot.insert("env".to_string(), Value::Record(env_map));

    // The fingerprint names the platform, so it hashes only the host's identity.
    // With the timestamp inside it, the same machine gave a different
    // fingerprint on every call; the tool probes are time-bounded and one can
    // miss under load, which did the same.
    let identity: std::collections::BTreeMap<&String, &Value> = snapshot
        .iter()
        .filter(|(k, _)| {
            matches!(
                k.as_str(),
                "os" | "arch" | "family" | "hostname" | "kernel" | "os_version" | "build"
            )
        })
        .collect();
    let fp = format!("{:?}", identity);
    let hash = format!("{:x}", md5_simple(&fp));
    snapshot.insert("fingerprint".to_string(), Value::Str(hash));

    Ok(Value::Record(snapshot))
}

/// Simple MD5-like hash for fingerprinting (not cryptographic)
fn md5_simple(s: &str) -> u64 {
    let mut hash: u64 = 0;
    for (i, b) in s.bytes().enumerate() {
        hash = hash.wrapping_add((b as u64).wrapping_mul((i as u64).wrapping_add(1)));
        hash = hash.rotate_left(7);
    }
    hash
}

/// Each platform's sources are tried in order, and a source that fails hands
/// over to the next. Only when every source has failed is the last failure
/// refused. The old code fell through to a literal "unknown", which read as an
/// answer.
fn bi_platform_os_version(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        // ver's line, as before, from the kernel instead of `cmd /c ver`.
        return Ok(Value::Str(
            WindowsVersion::read("platform_os_version")?.ver_line(),
        ));
    }
    #[allow(unreachable_code)]
    let mut failure: Option<anyhow::Error> = None;
    if cfg!(target_os = "macos") {
        let mut cmd = crate::safety::child_command("sw_vers");
        cmd.arg("-productVersion");
        match probe_text("platform_os_version", "sw_vers", cmd) {
            Ok(text) => return Ok(Value::Str(text)),
            Err(e) => failure = Some(e),
        }
    }
    if cfg!(target_os = "linux") {
        if let Ok(content) = std::fs::read_to_string("/etc/os-release") {
            for line in content.lines() {
                if line.starts_with("VERSION=") {
                    return Ok(Value::Str(
                        line.trim_start_matches("VERSION=")
                            .trim_matches('"')
                            .to_string(),
                    ));
                }
            }
        }
        let mut cmd = crate::safety::child_command("uname");
        cmd.arg("-r");
        match probe_text("platform_os_version", "uname", cmd) {
            Ok(text) => return Ok(Value::Str(text)),
            Err(e) => failure = Some(e),
        }
    }
    Err(failure.unwrap_or_else(|| {
        crate::safety::unimplemented(
            "platform_os_version",
            "no OS version source on this platform",
            "read the OS version from the platform's own tools",
        )
    }))
}

/// The kernel release. On Windows that is major.minor.build, which is what
/// `wmic os get Version` printed; the update revision is not part of it.
fn bi_platform_kernel(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        return Ok(Value::Str(
            WindowsVersion::read("platform_kernel")?.kernel(),
        ));
    }
    #[allow(unreachable_code)]
    let mut cmd = crate::safety::child_command("uname");
    cmd.arg("-r");
    Ok(Value::Str(probe_text("platform_kernel", "uname", cmd)?))
}

/// The OS build. On Windows it is the kernel's build number, the number
/// `wmic os get BuildNumber` gave.
fn bi_platform_build(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        return Ok(Value::Str(
            WindowsVersion::read("platform_build")?.build.to_string(),
        ));
    }
    #[allow(unreachable_code)]
    let build = if cfg!(target_os = "macos") {
        let mut cmd = crate::safety::child_command("sw_vers");
        cmd.arg("-buildVersion");
        probe_text("platform_build", "sw_vers", cmd)?
    } else if cfg!(target_os = "linux") {
        let mut cmd = crate::safety::child_command("uname");
        cmd.arg("-v");
        probe_text("platform_build", "uname", cmd)?
    } else {
        return Err(crate::safety::unimplemented(
            "platform_build",
            "no build source on this platform",
            "read the OS build from the platform's own tools",
        ));
    };
    Ok(Value::Str(build))
}

fn bi_platform_arch(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Str(std::env::consts::ARCH.to_string()))
}

fn bi_platform_hostname(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Its own copy ran `hostname` and answered the string "unknown" when that
    // failed. One implementation, which reports a failure as one.
    bi_sys_hostname(args, input)
}

/// The machine's identifier. A source that cannot answer is refused: an empty
/// or missing identifier used to come back as "unknown", a value that looks
/// like one. Windows reads the system UUID through PowerShell, as
/// `bi_sys_uptime` does, because `wmic` is absent from current Windows 11 installs.
fn bi_platform_machine_id(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if cfg!(target_os = "linux") {
        let id = std::fs::read_to_string("/etc/machine-id")
            .map_err(|e| crate::safety::fs_error("platform_machine_id", "/etc/machine-id", &e))?;
        return non_empty_machine_id(id.trim().to_string());
    }
    if cfg!(target_os = "macos") {
        let mut cmd = crate::safety::child_command("ioreg");
        cmd.args(["-rd1", "-c", "IOPlatformExpertDevice"]);
        let text = probe_text("platform_machine_id", "ioreg", cmd)?;
        let uuid = text
            .lines()
            .find(|line| line.contains("IOPlatformUUID"))
            .and_then(|line| line.split('"').nth(3))
            .unwrap_or("");
        return non_empty_machine_id(uuid.to_string());
    }
    if cfg!(target_os = "windows") {
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-NoProfile",
            "-Command",
            "(Get-CimInstance Win32_ComputerSystemProduct).UUID",
        ]);
        let uuid = probe_text("platform_machine_id", "powershell", cmd)?;
        return non_empty_machine_id(uuid);
    }
    Err(crate::safety::unimplemented(
        "platform_machine_id",
        "no machine identifier source on this platform",
        "read the machine identifier from the platform's own tools",
    ))
}

fn non_empty_machine_id(id: String) -> Result<Value> {
    if id.is_empty() {
        return Err(crate::safety::bad_state_with_hint(
            "platform_machine_id",
            "the platform reported no machine identifier",
            "a host with a machine identifier (/etc/machine-id, IOPlatformUUID or the system UUID)",
        ));
    }
    Ok(Value::Str(id))
}

#[cfg(all(test, any(unix, windows)))]
mod probe_status_tests {
    use super::*;

    /// An `Output` with exit `code`, built the way the at_queue tests build one.
    fn output(code: i32, stdout: &str, stderr: &str) -> std::process::Output {
        #[cfg(unix)]
        let status = {
            use std::os::unix::process::ExitStatusExt;
            std::process::ExitStatus::from_raw(code << 8)
        };
        #[cfg(windows)]
        let status = {
            use std::os::windows::process::ExitStatusExt;
            std::process::ExitStatus::from_raw(code as u32)
        };
        std::process::Output {
            status,
            stdout: stdout.as_bytes().to_vec(),
            stderr: stderr.as_bytes().to_vec(),
        }
    }

    #[test]
    fn a_failed_probe_is_refused_with_its_code_even_when_it_printed_something() {
        let err = probe_stdout("sys_kernel", "uname", output(3, "5.15.0\n", "uname: boom"))
            .unwrap_err()
            .to_string();
        assert!(err.contains("E_TOOL_FAILED"), "{err}");
        assert!(err.contains("exited 3"), "{err}");
        assert!(err.contains("uname: boom"), "{err}");
    }

    #[test]
    fn a_failed_probe_with_empty_stdout_is_not_an_empty_answer() {
        let err = probe_stdout("platform_kernel", "uname", output(1, "", ""))
            .unwrap_err()
            .to_string();
        assert!(err.contains("E_TOOL_FAILED"), "{err}");
    }

    #[test]
    fn a_successful_probe_returns_its_trimmed_stdout() {
        let text = probe_stdout(
            "sys_kernel",
            "uname",
            output(0, "  6.8.0-45-generic \n", ""),
        )
        .unwrap();
        assert_eq!(text, "6.8.0-45-generic");
    }

    #[test]
    fn a_session_listing_is_its_sessions() {
        let Ok(Value::Array(rows)) = screen_sessions(
            true,
            Some(0),
            "There is a screen on:\n\t4242.work\t(04/01/2026 10:00:00 AM)\t(Detached)\n1 Socket in /run/screen/S-u.\n",
            "",
        ) else {
            panic!("expected an array of sessions")
        };
        assert_eq!(rows.len(), 1);
        let Value::Record(row) = &rows[0] else {
            panic!("expected a record")
        };
        assert_eq!(row.get("id"), Some(&Value::Str("4242.work".into())));
    }

    #[test]
    fn no_sockets_is_an_empty_list_whichever_stream_says_it() {
        for (stdout, stderr) in [
            ("No Sockets found in /run/screen/S-u.\n", ""),
            ("", "No Sockets found in /run/screen/S-u.\n"),
        ] {
            let Ok(Value::Array(rows)) = screen_sessions(false, Some(1), stdout, stderr) else {
                panic!("'no sockets' should be an empty array")
            };
            assert!(rows.is_empty());
        }
    }

    #[test]
    fn a_listing_of_only_dead_sessions_is_still_the_answer() {
        let Ok(Value::Array(rows)) = screen_sessions(
            false,
            Some(10),
            "\t77.old\t(04/01/2026 09:00:00 AM)\t(Dead ???)\n",
            "",
        ) else {
            panic!("dead sessions are an answer, not a failure")
        };
        assert_eq!(rows.len(), 1);
    }

    #[test]
    fn a_failed_listing_with_no_sessions_is_refused_not_reported_as_none() {
        let err = match screen_sessions(
            false,
            Some(1),
            "",
            "screen: cannot open /run/screen/S-u: Permission denied",
        ) {
            Err(e) => e.to_string(),
            Ok(v) => panic!("a failed listing returned {v:?}"),
        };
        assert!(err.contains("E_TOOL_FAILED"), "{err}");
        assert!(err.contains("exited 1"), "{err}");
        assert!(err.contains("Permission denied"), "{err}");
    }
}

fn bi_platform_tool_version(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // A missing or non-string argument used to query a tool literally named
    // "unknown". It is refused, as the sibling platform_* builtins refuse theirs.
    let tool = match args.first() {
        Some(v) => v.as_str().map_err(|_| {
            crate::safety::bad_arg(
                "platform_tool_version",
                "a tool name: String",
                v.type_name(),
            )
        })?,
        None => {
            return Err(crate::safety::bad_arg(
                "platform_tool_version",
                "a tool name: String",
                "nothing",
            ))
        }
    };
    match get_tool_version(tool) {
        Some(ver) => Ok(Value::Str(ver)),
        None => Ok(Value::Null),
    }
}

fn bi_platform_tool_versions(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut versions = std::collections::BTreeMap::new();
    // Every group is collected first and probed in ONE parallel batch.
    // Probing the seventeen groups one after another made this cost the sum
    // of seventeen slowest-tools: 108s under WSL, and still over ten seconds
    // on the CI runner, where the probe gate killed it as hung.
    let mut pending: Vec<(&str, &[&str])> = Vec::new();

    // Compilers & Build Tools
    let compilers = [
        "gcc", "g++", "clang", "clang++", "rustc", "go", "javac", "swift", "kotlinc", "scalac",
        "ghc", "ocaml", "fpc", "gfortran", "nvcc", "hipcc", "dmd", "ldc2", "gdc", "zig", "nim",
        "crystal",
    ];
    pending.push(("compiler", &compilers[..]));

    // Build Systems
    let build_systems = [
        "make", "cmake", "ninja", "meson", "bazel", "buck2", "scons", "gradle", "maven", "ant",
        "cargo", "cabal", "stack", "mix", "dune", "zig", "xmake", "premake5", "waf",
    ];
    pending.push(("build", &build_systems[..]));

    // Linkers
    let linkers = ["ld", "lld", "gold", "mold", "link"];
    pending.push(("linker", &linkers[..]));

    // Language Runtimes
    let runtimes = [
        "python", "python3", "node", "deno", "bun", "ruby", "php", "perl", "lua", "luajit",
        "julia", "R", "java", "dotnet", "mono", "erlang", "elixir", "racket", "sbcl", "clisp",
    ];
    pending.push(("runtime", &runtimes[..]));

    // Package Managers (Language)
    let pkg_lang = [
        "pip", "pip3", "pipx", "poetry", "pdm", "uv", "conda", "mamba", "npm", "yarn", "pnpm",
        "bun", "gem", "bundler", "composer", "cargo", "go", "nuget", "dotnet", "maven", "gradle",
        "cabal", "stack", "opam", "mix", "hex", "rebar3", "cpan", "luarocks",
    ];
    pending.push(("pkg", &pkg_lang[..]));

    // Package Managers (System)
    let pkg_sys = [
        "apt", "apt-get", "dnf", "yum", "pacman", "zypper", "apk", "brew", "port", "nix", "guix",
        "snap", "flatpak", "choco", "winget", "scoop", "vcpkg", "conan",
    ];
    pending.push(("syspkg", &pkg_sys[..]));

    // Version Control
    let vcs = ["git", "hg", "svn", "fossil", "darcs", "bzr", "cvs"];
    pending.push(("vcs", &vcs[..]));

    // Containers & Virtualization
    let containers = [
        "docker",
        "podman",
        "buildah",
        "skopeo",
        "containerd",
        "runc",
        "nerdctl",
        "crictl",
        "ctr",
        "lxc",
        "lxd",
        "vagrant",
        "packer",
        "qemu-system-x86_64",
        "vboxmanage",
        "multipass",
    ];
    pending.push(("container", &containers[..]));

    // Orchestration & IaC
    let orchestration = [
        "kubectl",
        "helm",
        "kustomize",
        "k3s",
        "k3d",
        "kind",
        "minikube",
        "terraform",
        "terragrunt",
        "pulumi",
        "cdktf",
        "crossplane",
        "ansible",
        "ansible-playbook",
        "chef",
        "puppet",
        "salt",
    ];
    pending.push(("iac", &orchestration[..]));

    // Cloud CLIs
    let cloud = [
        "aws",
        "az",
        "gcloud",
        "doctl",
        "linode-cli",
        "vultr-cli",
        "oci",
        "ibmcloud",
        "hcloud",
        "exo",
        "scaleway",
        "flyctl",
    ];
    pending.push(("cloud", &cloud[..]));

    // Databases
    let databases = [
        "psql",
        "mysql",
        "sqlite3",
        "mongosh",
        "redis-cli",
        "mongod",
        "pg_dump",
        "mysqldump",
        "cqlsh",
        "influx",
        "clickhouse-client",
    ];
    pending.push(("db", &databases[..]));

    // Testing & Quality
    let testing = [
        "pytest", "jest", "mocha", "rspec", "phpunit", "go", "cargo", "valgrind", "gdb", "lldb",
        "strace", "dtrace", "perf",
    ];
    pending.push(("test", &testing[..]));

    // Linters & Formatters
    let linters = [
        "eslint",
        "prettier",
        "black",
        "ruff",
        "mypy",
        "pylint",
        "flake8",
        "rubocop",
        "clippy",
        "rustfmt",
        "gofmt",
        "golangci-lint",
        "shellcheck",
        "hadolint",
        "yamllint",
        "jsonlint",
        "tflint",
    ];
    pending.push(("lint", &linters[..]));

    // Documentation
    let docs = [
        "sphinx-build",
        "mkdocs",
        "hugo",
        "jekyll",
        "doxygen",
        "typedoc",
        "rustdoc",
        "godoc",
        "javadoc",
        "pdoc",
    ];
    pending.push(("docs", &docs[..]));

    // CI/CD & DevOps
    let cicd = [
        "gh",
        "gitlab-runner",
        "circleci",
        "drone",
        "act",
        "jenkins-cli",
        "argocd",
        "flux",
        "tekton",
        "skaffold",
        "tilt",
        "devspace",
    ];
    pending.push(("cicd", &cicd[..]));

    // Security
    let security = [
        "gpg",
        "openssl",
        "ssh",
        "ssh-keygen",
        "age",
        "sops",
        "vault",
        "trivy",
        "grype",
        "syft",
        "cosign",
        "sigstore",
    ];
    pending.push(("security", &security[..]));

    // Network Tools
    let network = [
        "curl",
        "wget",
        "httpie",
        "jq",
        "yq",
        "fx",
        "grpcurl",
        "nmap",
        "netcat",
        "socat",
        "tcpdump",
        "wireshark",
    ];
    pending.push(("net", &network[..]));

    let mut all: Vec<&str> = pending
        .iter()
        .flat_map(|(_, g)| g.iter().copied())
        .collect();
    all.sort_unstable();
    all.dedup();
    let found: std::collections::HashMap<String, String> =
        probe_tool_versions(&all).into_iter().collect();
    for (prefix, group) in &pending {
        for tool in group.iter() {
            if let Some(ver) = found.get(*tool) {
                versions.insert(format!("{prefix}.{tool}"), Value::Str(ver.clone()));
            }
        }
    }
    Ok(Value::Record(versions))
}

fn bi_platform_detect_tools(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let tools = [
        "git",
        "python",
        "python3",
        "node",
        "npm",
        "yarn",
        "pnpm",
        "cargo",
        "rustc",
        "go",
        "java",
        "javac",
        "docker",
        "podman",
        "kubectl",
        "helm",
        "terraform",
        "ansible",
        "aws",
        "az",
        "gcloud",
        "ruby",
        "gem",
        "php",
        "composer",
        "dotnet",
        "swift",
        "gcc",
        "g++",
        "clang",
        "make",
        "cmake",
        "ninja",
        "meson",
        "gradle",
        "maven",
        "pip",
        "pip3",
        "pipenv",
        "poetry",
        "conda",
        "mamba",
        "uv",
        "nvcc",
        "sqlite3",
        "psql",
        "mysql",
        "mongod",
        "redis-cli",
    ];

    let available: Vec<Value> = tools
        .iter()
        .filter(|t| on_path(t))
        .map(|t| Value::Str(t.to_string()))
        .collect();

    Ok(Value::Array(available))
}

fn bi_platform_has_tool(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // With no tool named this asked whether "" is installed, and said no.
    let tool = match args.first() {
        Some(v) => expect_string("platform_has_tool", v)?,
        None => {
            return Err(crate::safety::bad_arg(
                "platform_has_tool",
                "a tool name",
                "nothing",
            ))
        }
    };
    Ok(Value::Bool(on_path(tool)))
}

/// Whether this Windows process is elevated, read from its own token.
///
/// This was `net session` here and PowerShell's
/// `IsInRole(Administrator)` in sudo_check. Both answer the same question as
/// the token's elevation flag (under UAC an administrator's unelevated
/// process is not elevated for any of them), but each started a process, and
/// `net session` also failed, reading as "not admin", when the Server service
/// was stopped.
#[cfg(target_os = "windows")]
pub(crate) fn windows_is_admin(builtin: &str) -> Result<bool> {
    use std::ffi::c_void;
    #[link(name = "kernel32")]
    extern "system" {
        fn GetCurrentProcess() -> *mut c_void;
        fn CloseHandle(handle: *mut c_void) -> i32;
    }
    #[link(name = "advapi32")]
    extern "system" {
        fn OpenProcessToken(process: *mut c_void, access: u32, token: *mut *mut c_void) -> i32;
        fn GetTokenInformation(
            token: *mut c_void,
            class: u32,
            info: *mut c_void,
            len: u32,
            returned: *mut u32,
        ) -> i32;
    }
    const TOKEN_QUERY: u32 = 0x0008;
    const TOKEN_ELEVATION: u32 = 20;
    let failed = |call: &str| {
        crate::safety::bad_state_with_hint(
            builtin,
            &format!("{call} failed: {}", std::io::Error::last_os_error()),
            "a process token this process can query",
        )
    };
    let mut token: *mut c_void = std::ptr::null_mut();
    // SAFETY: GetCurrentProcess returns a pseudo-handle that needs no close;
    // `token` is a valid out-pointer.
    if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
        return Err(failed("OpenProcessToken"));
    }
    let mut elevated: u32 = 0;
    let mut returned: u32 = 0;
    // SAFETY: TOKEN_ELEVATION is a single DWORD, and `elevated` is one.
    let ok = unsafe {
        GetTokenInformation(
            token,
            TOKEN_ELEVATION,
            (&mut elevated as *mut u32).cast(),
            std::mem::size_of::<u32>() as u32,
            &mut returned,
        )
    };
    let result = if ok == 0 {
        Err(failed("GetTokenInformation"))
    } else {
        Ok(elevated != 0)
    };
    // SAFETY: `token` was opened above and is closed once.
    unsafe { CloseHandle(token) };
    result
}

/// The drive types Get-PSDrive -PSProvider FileSystem listed in
/// `bi_fs_df` and `bi_fs_mounts`: fixed, removable, network and RAM-disk
/// roots. CD-ROM drives are not in that set.
#[cfg(target_os = "windows")]
fn windows_listed_by_powershell(drive_type: u32) -> bool {
    matches!(
        drive_type,
        DRIVE_FIXED | DRIVE_REMOVABLE | DRIVE_REMOTE | DRIVE_RAMDISK
    )
}

#[cfg(target_os = "windows")]
const DRIVE_UNKNOWN: u32 = 0;
#[cfg(target_os = "windows")]
const DRIVE_NO_ROOT_DIR: u32 = 1;
#[cfg(target_os = "windows")]
const DRIVE_REMOVABLE: u32 = 2;
#[cfg(target_os = "windows")]
const DRIVE_FIXED: u32 = 3;
#[cfg(target_os = "windows")]
const DRIVE_REMOTE: u32 = 4;
#[cfg(target_os = "windows")]
const DRIVE_RAMDISK: u32 = 6;

/// One drive letter with a root, as kernel32 described it. A field is `None`
/// where the call that answers it failed: an empty card reader or a
/// disconnected network drive has no size and no file system.
#[cfg(target_os = "windows")]
struct WinVolume {
    /// The drive letter, such as 'C'.
    letter: char,
    /// GetDriveTypeW's answer, one of the DRIVE_* constants.
    drive_type: u32,
    /// Total bytes on the volume, from GetDiskFreeSpaceExW.
    total: Option<u64>,
    /// Free bytes, from GetDiskFreeSpaceExW's TotalNumberOfFreeBytes. This is
    /// the figure WMI's FreeSpace and Get-PSDrive's Free reported, not the
    /// caller-available figure.
    free: Option<u64>,
    /// The file system name from GetVolumeInformationW, such as "NTFS".
    fs_name: Option<String>,
    /// The volume label. `Some("")` is an unlabeled volume that answered.
    label: Option<String>,
}

/// [`windows_volumes_now`] on a worker thread, bounded by the probe deadline.
///
/// PowerShell's Get-PSDrive was bounded by it, and these calls need it too:
/// asking a disconnected network drive for its size waits on SMB, which can
/// take longer than that. The worker also turns off the "There is no disk in
/// the drive" dialog an empty removable drive could raise on the desktop.
#[cfg(target_os = "windows")]
fn windows_volumes(builtin: &str) -> Result<Vec<WinVolume>> {
    #[link(name = "kernel32")]
    extern "system" {
        fn SetThreadErrorMode(mode: u32, old: *mut u32) -> i32;
    }
    const SEM_FAILCRITICALERRORS: u32 = 0x0001;
    const SEM_NOOPENFILEERRORBOX: u32 = 0x8000;
    let (tx, rx) = std::sync::mpsc::channel();
    let name = builtin.to_string();
    std::thread::spawn(move || {
        // SAFETY: affects only this worker thread; the old mode is not needed
        // because the thread ends after the walk.
        unsafe {
            SetThreadErrorMode(
                SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX,
                std::ptr::null_mut(),
            )
        };
        let _ = tx.send(windows_volumes_now(&name));
    });
    match rx.recv_timeout(std::time::Duration::from_secs(PROBE_DEADLINE_SECS)) {
        Ok(result) => result,
        Err(_) => Err(crate::safety::budget_exceeded(
            builtin,
            format!("the drive table did not answer in {PROBE_DEADLINE_SECS}s"),
            "a network drive may be unreachable; disconnect it or retry",
        )),
    }
}

/// Every drive letter with a root (GetLogicalDrives, GetDriveTypeW). A zero
/// bitmask is a failed call, since no machine has no drive letters.
#[cfg(target_os = "windows")]
fn windows_volumes_now(builtin: &str) -> Result<Vec<WinVolume>> {
    #[link(name = "kernel32")]
    extern "system" {
        fn GetLogicalDrives() -> u32;
        fn GetDriveTypeW(root: *const u16) -> u32;
        fn GetDiskFreeSpaceExW(
            root: *const u16,
            free_to_caller: *mut u64,
            total: *mut u64,
            total_free: *mut u64,
        ) -> i32;
        fn GetVolumeInformationW(
            root: *const u16,
            name: *mut u16,
            name_len: u32,
            serial: *mut u32,
            max_component: *mut u32,
            flags: *mut u32,
            fs_name: *mut u16,
            fs_name_len: u32,
        ) -> i32;
    }
    // MAX_PATH + 1, the buffer size GetVolumeInformationW is documented with.
    const NAME_UNITS: usize = 261;
    let text = |buf: &[u16]| {
        let end = buf.iter().position(|&u| u == 0).unwrap_or(buf.len());
        String::from_utf16_lossy(&buf[..end])
    };
    // SAFETY: GetLogicalDrives takes no arguments and only reads the drive
    // table.
    let mask = unsafe { GetLogicalDrives() };
    if mask == 0 {
        return Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!(
                "GetLogicalDrives failed: {}",
                std::io::Error::last_os_error()
            ),
            "a readable drive table",
        ));
    }
    let mut volumes = Vec::new();
    for bit in 0..26u32 {
        if mask & (1 << bit) == 0 {
            continue;
        }
        let letter = char::from(b'A' + bit as u8);
        let root: Vec<u16> = format!("{letter}:\\")
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();
        // SAFETY: `root` is NUL-terminated and lives across the call.
        let drive_type = unsafe { GetDriveTypeW(root.as_ptr()) };
        if drive_type == DRIVE_UNKNOWN || drive_type == DRIVE_NO_ROOT_DIR {
            continue;
        }
        let (mut free_to_caller, mut total, mut total_free) = (0u64, 0u64, 0u64);
        // SAFETY: `root` is NUL-terminated, and each out-pointer is a valid
        // u64 for the call to write.
        let sized = unsafe {
            GetDiskFreeSpaceExW(
                root.as_ptr(),
                &mut free_to_caller,
                &mut total,
                &mut total_free,
            )
        } != 0;
        // An empty or disconnected drive fails here, and its size stays unknown.
        let (size, free) = if sized {
            (Some(total), Some(total_free))
        } else {
            (None, None)
        };
        let mut label_buf = [0u16; NAME_UNITS];
        let mut fs_buf = [0u16; NAME_UNITS];
        // SAFETY: both buffers hold NAME_UNITS units, and the lengths passed
        // say so. The serial, max-component and flags out-pointers are null,
        // which the call accepts.
        let described = unsafe {
            GetVolumeInformationW(
                root.as_ptr(),
                label_buf.as_mut_ptr(),
                NAME_UNITS as u32,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                fs_buf.as_mut_ptr(),
                NAME_UNITS as u32,
            )
        } != 0;
        let (label, fs_name) = if described {
            (Some(text(&label_buf)), Some(text(&fs_buf)))
        } else {
            (None, None)
        };
        volumes.push(WinVolume {
            letter,
            drive_type,
            total: size,
            free,
            fs_name,
            label,
        });
    }
    Ok(volumes)
}

/// A REG_DWORD under HKEY_LOCAL_MACHINE: `Ok(None)` when the key or value is
/// absent, `Err` with the Win32 status for anything else.
#[cfg(target_os = "windows")]
fn windows_hklm_dword(subkey: &str, value: &str) -> std::result::Result<Option<u32>, i32> {
    use std::ffi::c_void;
    #[link(name = "advapi32")]
    extern "system" {
        fn RegGetValueW(
            key: isize,
            subkey: *const u16,
            value: *const u16,
            flags: u32,
            kind: *mut u32,
            data: *mut c_void,
            len: *mut u32,
        ) -> i32;
    }
    const HKEY_LOCAL_MACHINE: isize = 0x8000_0002u32 as i32 as isize;
    const RRF_RT_REG_DWORD: u32 = 0x0000_0010;
    const ERROR_FILE_NOT_FOUND: i32 = 2;
    let wide = |s: &str| {
        s.encode_utf16()
            .chain(std::iter::once(0))
            .collect::<Vec<u16>>()
    };
    let (subkey, value) = (wide(subkey), wide(value));
    let mut data: u32 = 0;
    let mut len = std::mem::size_of::<u32>() as u32;
    // SAFETY: both names are NUL-terminated, and RRF_RT_REG_DWORD writes at
    // most `len` (4) bytes into `data`.
    let status = unsafe {
        RegGetValueW(
            HKEY_LOCAL_MACHINE,
            subkey.as_ptr(),
            value.as_ptr(),
            RRF_RT_REG_DWORD,
            std::ptr::null_mut(),
            (&mut data as *mut u32).cast(),
            &mut len,
        )
    };
    match status {
        0 => Ok(Some(data)),
        ERROR_FILE_NOT_FOUND => Ok(None),
        other => Err(other),
    }
}

/// A REG_SZ under HKEY_LOCAL_MACHINE, as [`windows_hklm_dword`] reads a
/// DWORD.
#[cfg(target_os = "windows")]
fn windows_hklm_string(subkey: &str, value: &str) -> std::result::Result<Option<String>, i32> {
    windows_hklm_string_from(subkey, value, 128)
}

/// [`windows_hklm_string`] starting from a buffer of `units` UTF-16 units,
/// so a test can make it grow.
#[cfg(target_os = "windows")]
fn windows_hklm_string_from(
    subkey: &str,
    value: &str,
    units: usize,
) -> std::result::Result<Option<String>, i32> {
    use std::ffi::c_void;
    #[link(name = "advapi32")]
    extern "system" {
        fn RegGetValueW(
            key: isize,
            subkey: *const u16,
            value: *const u16,
            flags: u32,
            kind: *mut u32,
            data: *mut c_void,
            len: *mut u32,
        ) -> i32;
    }
    const HKEY_LOCAL_MACHINE: isize = 0x8000_0002u32 as i32 as isize;
    const RRF_RT_REG_SZ: u32 = 0x0000_0002;
    const ERROR_FILE_NOT_FOUND: i32 = 2;
    let wide = |s: &str| {
        s.encode_utf16()
            .chain(std::iter::once(0))
            .collect::<Vec<u16>>()
    };
    let (subkey, value) = (wide(subkey), wide(value));
    let mut buf = vec![0u16; units.max(1)];
    loop {
        let mut len = (buf.len() * 2) as u32;
        // SAFETY: both names are NUL-terminated, and RegGetValueW writes at
        // most `len` bytes into `buf`, NUL included.
        let status = unsafe {
            RegGetValueW(
                HKEY_LOCAL_MACHINE,
                subkey.as_ptr(),
                value.as_ptr(),
                RRF_RT_REG_SZ,
                std::ptr::null_mut(),
                buf.as_mut_ptr().cast(),
                &mut len,
            )
        };
        match status {
            0 => {
                let units = (len as usize / 2).min(buf.len());
                let text = &buf[..units];
                let end = text.iter().position(|&u| u == 0).unwrap_or(text.len());
                return Ok(Some(String::from_utf16_lossy(&text[..end])));
            }
            ERROR_FILE_NOT_FOUND => return Ok(None),
            // ERROR_MORE_DATA: `len` is the size needed.
            234 if (len as usize) / 2 > buf.len() => buf = vec![0u16; len as usize / 2 + 1],
            other => return Err(other),
        }
    }
}

/// Processor 0's clock in MHz as the kernel measured it at boot, from the
/// registry, without starting PowerShell to ask WMI. It is not quite WMI's
/// MaxClockSpeed, the rated figure: on one host 4392 where WMI said 4400.
#[cfg(target_os = "windows")]
fn windows_cpu_mhz(builtin: &str) -> Result<Option<u32>> {
    windows_hklm_dword(r"HARDWARE\DESCRIPTION\System\CentralProcessor\0", "~MHz").map_err(
        |status| {
            crate::safety::bad_state_with_hint(
                builtin,
                &format!(
                    "the processor's ~MHz registry value could not be read: {}",
                    std::io::Error::from_raw_os_error(status)
                ),
                "a readable HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
            )
        },
    )
}

fn bi_platform_capabilities(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut caps = std::collections::BTreeMap::new();

    // Admin/sudo
    #[cfg(target_os = "windows")]
    {
        // Check if running as admin
        let is_admin = windows_is_admin("platform_capabilities")?;
        caps.insert("has_admin".to_string(), Value::Bool(is_admin));
        caps.insert("has_sudo".to_string(), Value::Bool(false));
    }
    #[cfg(not(target_os = "windows"))]
    {
        caps.insert(
            "has_admin".to_string(),
            Value::Bool(unsafe { libc::geteuid() } == 0),
        );
        caps.insert("has_sudo".to_string(), Value::Bool(on_path("sudo")));
    }

    // GUI
    #[cfg(target_os = "windows")]
    {
        caps.insert("has_gui".to_string(), Value::Bool(true));
    }
    #[cfg(target_os = "macos")]
    {
        caps.insert("has_gui".to_string(), Value::Bool(true));
    }
    #[cfg(target_os = "linux")]
    {
        let has_display =
            std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok();
        caps.insert("has_gui".to_string(), Value::Bool(has_display));
    }

    // Network: a routable interface address. This was a hard-coded true.
    caps.insert("has_network".to_string(), Value::Bool(host_has_network()));

    // Container runtimes
    caps.insert("has_docker".to_string(), Value::Bool(on_path("docker")));
    caps.insert("has_podman".to_string(), Value::Bool(on_path("podman")));
    caps.insert(
        "has_container".to_string(),
        Value::Bool(on_path("docker") || on_path("podman")),
    );

    // Package managers
    let mut pkg_mgrs = Vec::new();
    if on_path("apt") {
        pkg_mgrs.push("apt");
    }
    if on_path("dnf") {
        pkg_mgrs.push("dnf");
    }
    if on_path("yum") {
        pkg_mgrs.push("yum");
    }
    if on_path("pacman") {
        pkg_mgrs.push("pacman");
    }
    if on_path("brew") {
        pkg_mgrs.push("brew");
    }
    if on_path("choco") {
        pkg_mgrs.push("choco");
    }
    if on_path("winget") {
        pkg_mgrs.push("winget");
    }
    if on_path("scoop") {
        pkg_mgrs.push("scoop");
    }
    if on_path("snap") {
        pkg_mgrs.push("snap");
    }
    if on_path("flatpak") {
        pkg_mgrs.push("flatpak");
    }
    caps.insert(
        "pkg_managers".to_string(),
        Value::Array(
            pkg_mgrs
                .into_iter()
                .map(|s| Value::Str(s.to_string()))
                .collect(),
        ),
    );

    Ok(Value::Record(caps))
}

fn bi_platform_has_admin(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        Ok(Value::Bool(windows_is_admin("platform_has_admin")?))
    }
    #[cfg(not(target_os = "windows"))]
    {
        return Ok(Value::Bool(unsafe { libc::geteuid() } == 0));
    }
}

fn bi_platform_has_sudo(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Bool(on_path("sudo")))
}

fn bi_platform_has_gui(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        Ok(Value::Bool(true))
    }
    #[cfg(target_os = "macos")]
    {
        return Ok(Value::Bool(true));
    }
    #[cfg(target_os = "linux")]
    {
        let has_display =
            std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok();
        return Ok(Value::Bool(has_display));
    }
    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
    {
        return Ok(Value::Bool(false));
    }
}

/// Whether any address in `addrs` is one a peer could reach: not loopback and
/// not an IPv6 link-local (fe80::/10) address, which every IPv6 interface has
/// even when it has no route.
fn any_routable(addrs: &[std::net::IpAddr]) -> bool {
    addrs.iter().any(|addr| {
        !addr.is_loopback()
            && !matches!(addr, std::net::IpAddr::V6(v6) if (v6.segments()[0] & 0xffc0) == 0xfe80)
    })
}

/// Whether this host has a network interface with a routable address. The old
/// check bound 127.0.0.1:0, which succeeds offline, so it said yes everywhere.
fn host_has_network() -> bool {
    let networks = sysinfo::Networks::new_with_refreshed_list();
    let mut addrs = Vec::new();
    for (_, data) in &networks {
        for net in data.ip_networks() {
            addrs.push(net.addr);
        }
    }
    any_routable(&addrs)
}

fn bi_platform_has_network(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Bool(host_has_network()))
}

#[cfg(test)]
mod quiet_platform_tests {
    use super::*;
    use std::net::IpAddr;

    fn ip(text: &str) -> IpAddr {
        text.parse().unwrap()
    }

    #[test]
    fn loopback_only_is_not_routable() {
        assert!(!any_routable(&[ip("127.0.0.1"), ip("::1")]));
    }

    #[test]
    fn no_addresses_is_not_routable() {
        assert!(!any_routable(&[]));
    }

    #[test]
    fn ipv6_link_local_is_not_routable() {
        assert!(!any_routable(&[
            ip("127.0.0.1"),
            ip("::1"),
            ip("fe80::1"),
            ip("febf::2"),
        ]));
    }

    #[test]
    fn lan_address_is_routable() {
        assert!(any_routable(&[ip("127.0.0.1"), ip("192.168.1.5")]));
    }

    #[test]
    fn global_ipv6_is_routable() {
        assert!(any_routable(&[ip("::1"), ip("2001:db8::1")]));
    }

    #[test]
    fn site_local_ipv6_is_routable() {
        // fec0::/10 is not link-local (fe80::/10), so it counts.
        assert!(any_routable(&[ip("fec0::1")]));
    }
}

fn bi_platform_has_container(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Bool(on_path("docker") || on_path("podman")))
}

fn bi_platform_pkg_managers(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let managers = [
        ("apt", "apt"),
        ("apt-get", "apt-get"),
        ("dnf", "dnf"),
        ("yum", "yum"),
        ("pacman", "pacman"),
        ("zypper", "zypper"),
        ("brew", "brew"),
        ("port", "port"),
        ("choco", "choco"),
        ("winget", "winget"),
        ("scoop", "scoop"),
        ("snap", "snap"),
        ("flatpak", "flatpak"),
        ("nix", "nix"),
        ("guix", "guix"),
    ];

    let available: Vec<Value> = managers
        .iter()
        .filter(|(_, cmd)| on_path(cmd))
        .map(|(name, _)| Value::Str(name.to_string()))
        .collect();

    Ok(Value::Array(available))
}

fn bi_platform_normalize_path(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = args.first().and_then(|v| v.as_str().ok()).unwrap_or("");
    // Convert backslashes to forward slashes for cross-platform consistency
    let normalized = path.replace('\\', "/");
    Ok(Value::Str(normalized))
}

fn bi_platform_normalize_output(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let output = args.first().and_then(|v| v.as_str().ok()).unwrap_or("");
    // Normalize line endings to LF
    let normalized = output.replace("\r\n", "\n").replace('\r', "\n");
    Ok(Value::Str(normalized))
}

fn bi_platform_path_sep(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    Ok(Value::Str(std::path::MAIN_SEPARATOR.to_string()))
}

fn bi_platform_line_ending(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        Ok(Value::Str("\r\n".to_string()))
    }
    #[cfg(not(target_os = "windows"))]
    {
        return Ok(Value::Str("\n".to_string()));
    }
}

fn bi_platform_shell_type(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "windows")]
    {
        if std::env::var("PSModulePath").is_ok() {
            return Ok(Value::Str("powershell".to_string()));
        }
        Ok(Value::Str("cmd".to_string()))
    }
    #[cfg(not(target_os = "windows"))]
    {
        if let Ok(shell) = std::env::var("SHELL") {
            let shell_name = std::path::Path::new(&shell)
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or("sh");
            return Ok(Value::Str(shell_name.to_string()));
        }
        return Ok(Value::Str("sh".to_string()));
    }
}

/// The first dotted number in `s` ("Python 3.12.1" -> [3, 12, 1]).
fn first_version(s: &str) -> Option<Vec<u64>> {
    static RE: std::sync::LazyLock<regex::Regex> =
        std::sync::LazyLock::new(|| regex::Regex::new(r"\d+(?:\.\d+)*").unwrap());
    let m = RE.find(s)?;
    m.as_str().split('.').map(|p| p.parse().ok()).collect()
}

/// `">=3.10"` -> (">=", [3, 10]). A bare version means `>=`, which is what a
/// requirement written as `{python: "3.10"}` asks for.
fn parse_version_req(req: &str) -> Option<(&'static str, Vec<u64>)> {
    let req = req.trim();
    let (op, rest) = [">=", "<=", "==", ">", "<", "="]
        .iter()
        .find_map(|op| req.strip_prefix(op).map(|r| (*op, r)))
        .unwrap_or((">=", req));
    let op = if op == "=" { "==" } else { op };
    let rest = rest.trim();
    if rest.is_empty() || !rest.chars().all(|c| c.is_ascii_digit() || c == '.') {
        return None;
    }
    Some((op, first_version(rest)?))
}

fn version_satisfies(have: &[u64], op: &str, want: &[u64]) -> bool {
    // Compare over the requirement's precision: "3.10" is met by 3.10.4.
    let n = want.len();
    let have: Vec<u64> = (0..n).map(|i| have.get(i).copied().unwrap_or(0)).collect();
    let ord = have.as_slice().cmp(want);
    match op {
        ">=" => ord.is_ge(),
        "<=" => ord.is_le(),
        ">" => ord.is_gt(),
        "<" => ord.is_lt(),
        _ => ord.is_eq(),
    }
}

fn bi_platform_require(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_require", &input)?;
    // Expect a record like {os: "linux|windows", python: ">=3.10", docker: true}
    //
    // Four answers here were made without looking. A non-record argument was
    // "satisfied"; `os: 42` compared the OS against ""; a tool value that was
    // neither Bool nor String was skipped; and a version requirement was a
    // TODO, so {python: ">=3.10"} held whenever any python was installed.
    let spec =
        match args.first() {
            Some(Value::Record(r)) => r.clone(),
            None => {
                // No requirements: vacuously satisfied.
                return Ok(Value::Record({
                    let mut m = std::collections::BTreeMap::new();
                    m.insert("satisfied".to_string(), Value::Bool(true));
                    m.insert("missing".to_string(), Value::Array(vec![]));
                    m
                }));
            }
            Some(other) => return Err(crate::safety::bad_arg(
                "platform_require",
                "a record of requirements, e.g. {os: \"linux\", python: \">=3.10\", docker: true}",
                other.type_name(),
            )),
        };

    let mut missing = Vec::new();

    for (key, val) in &spec {
        match key.as_str() {
            "os" | "arch" => {
                let Value::Str(required) = val else {
                    return Err(crate::safety::bad_arg(
                        "platform_require",
                        &format!("{key} as a string such as \"linux|macos\""),
                        val.type_name(),
                    ));
                };
                let current = if key == "os" {
                    std::env::consts::OS
                } else {
                    std::env::consts::ARCH
                };
                if !required.split('|').any(|o| o.trim() == current) {
                    missing.push(Value::Str(format!(
                        "{key}: need {required}, have {current}"
                    )));
                }
            }
            _ => match val {
                Value::Bool(false) => {}
                Value::Bool(true) => {
                    if !on_path(key) {
                        missing.push(Value::Str(format!("{key}: not found")));
                    }
                }
                Value::Str(req) => {
                    let Some((op, want)) = parse_version_req(req) else {
                        return Err(crate::safety::bad_arg(
                            "platform_require",
                            &format!("{key} as a version requirement such as \">=3.10\""),
                            &format!("\"{req}\""),
                        ));
                    };
                    if !on_path(key) {
                        missing.push(Value::Str(format!("{key}: not found")));
                        continue;
                    }
                    match get_tool_version(key).as_deref().and_then(first_version) {
                        Some(have) if version_satisfies(&have, op, &want) => {}
                        Some(have) => missing.push(Value::Str(format!(
                            "{key}: need {req}, have {}",
                            have.iter()
                                .map(u64::to_string)
                                .collect::<Vec<_>>()
                                .join(".")
                        ))),
                        // Installed, but it would not say which version. Not
                        // provably satisfied, so not reported as satisfied.
                        None => missing.push(Value::Str(format!(
                            "{key}: need {req}, version could not be determined"
                        ))),
                    }
                }
                other => {
                    return Err(crate::safety::bad_arg(
                        "platform_require",
                        &format!("{key} as true/false or a version requirement"),
                        other.type_name(),
                    ))
                }
            },
        }
    }

    let mut result = std::collections::BTreeMap::new();
    result.insert("satisfied".to_string(), Value::Bool(missing.is_empty()));
    result.insert("missing".to_string(), Value::Array(missing));
    Ok(Value::Record(result))
}

fn bi_platform_check_reqs(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    bi_platform_require(args, input)
}

fn bi_platform_satisfies(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_satisfies", &input)?;
    // A missing answer is an error, not `false`: "not satisfied" and "could not
    // say" are different things to an agent deciding whether to proceed.
    let Value::Record(r) = bi_platform_require(args, None)? else {
        return Err(crate::safety::bad_state(
            "platform_satisfies",
            "platform_require did not answer a record",
            "platform_require",
        ));
    };
    match r.get("satisfied") {
        Some(Value::Bool(sat)) => Ok(Value::Bool(*sat)),
        _ => Err(crate::safety::bad_state(
            "platform_satisfies",
            "platform_require answered no satisfied flag",
            "platform_require",
        )),
    }
}

fn bi_platform_diff(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_diff", &input)?;
    // Compare two snapshots
    let snap1 = match args.first() {
        Some(Value::Record(r)) => r.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "platform_diff",
                "Record",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let snap2 = match args.get(1) {
        Some(Value::Record(r)) => r.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "platform_diff",
                "Record",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    let mut diff = std::collections::BTreeMap::new();
    let mut added = Vec::new();
    let mut removed = Vec::new();
    let mut changed = Vec::new();

    // Find added/changed in snap2
    for (key, val2) in &snap2 {
        match snap1.get(key) {
            None => added.push(Value::Str(key.clone())),
            Some(val1) if val1 != val2 => {
                let mut change = std::collections::BTreeMap::new();
                change.insert("key".to_string(), Value::Str(key.clone()));
                change.insert("old".to_string(), val1.clone());
                change.insert("new".to_string(), val2.clone());
                changed.push(Value::Record(change));
            }
            _ => {}
        }
    }

    // Find removed in snap2
    for key in snap1.keys() {
        if !snap2.contains_key(key) {
            removed.push(Value::Str(key.clone()));
        }
    }

    diff.insert("added".to_string(), Value::Array(added));
    diff.insert("removed".to_string(), Value::Array(removed));
    diff.insert("changed".to_string(), Value::Array(changed));

    Ok(Value::Record(diff))
}

fn bi_platform_compatible(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_compatible", &input)?;
    // Check if two snapshots are compatible (same OS family, arch)
    let snap1 = match args.first() {
        Some(Value::Record(r)) => r,
        other => {
            return Err(crate::safety::bad_arg(
                "platform_compatible",
                "Record",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let snap2 = match args.get(1) {
        Some(Value::Record(r)) => r,
        other => {
            return Err(crate::safety::bad_arg(
                "platform_compatible",
                "Record",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };

    // A key missing from both records compared equal (None == None), so two
    // empty records were "compatible". Each record must carry all three.
    for key in ["os", "arch", "family"] {
        for snap in [snap1, snap2] {
            if !snap.contains_key(key) {
                return Err(crate::safety::bad_arg(
                    "platform_compatible",
                    "records from platform_snapshot(), each with os, arch and family",
                    &format!("a record without {key}"),
                ));
            }
        }
    }

    let os_match = snap1.get("os") == snap2.get("os");
    let arch_match = snap1.get("arch") == snap2.get("arch");
    let family_match = snap1.get("family") == snap2.get("family");

    Ok(Value::Bool(os_match && arch_match && family_match))
}

fn bi_platform_db_init(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_db_init", &input)?;
    let db_path = platform_db_path()?;
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| crate::safety::fs_error("platform_db_init", parent, &e))?;
    }
    if !db_path.exists() {
        std::fs::write(&db_path, "{}")
            .map_err(|e| crate::safety::fs_error("platform_db_init", &db_path, &e))?;
    }
    Ok(Value::Str(db_path.to_string_lossy().to_string()))
}

fn bi_platform_db_store(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_db_store", &input)?;
    let key =
        platform_str_arg("platform_db_store", &args, 0)?.unwrap_or_else(|| "default".to_string());
    let snapshot = match args.get(1) {
        Some(v) => v.clone(),
        None => bi_platform_snapshot(vec![], None)?,
    };

    let db_path = platform_db_path()?;
    bi_platform_db_init(vec![], None)?;

    // An unreadable store used to read as empty and be written back with only
    // the new key: every other entry was destroyed. The read error is now the
    // answer.
    let content = read_text_capped("platform_db_store", &db_path)?;
    let mut db = platform_store_parse("platform_db_store", &db_path, &content)?;

    db.insert(key, value_to_json(snapshot));

    // The store had no size limit and was read whole on every call; a store
    // past the file limit could no longer be read back.
    let text = serde_json::to_string_pretty(&db)?;
    let max = crate::security::max_file_size_bytes()?;
    if text.len() as u64 > max {
        return Err(crate::safety::budget_exceeded(
            "platform_db_store",
            format!(
                "the platform store would be {} bytes, more than the file limit of {max}",
                text.len()
            ),
            "remove entries from the store, or raise max_file_size_mb",
        ));
    }
    std::fs::write(&db_path, text)
        .map_err(|e| crate::safety::fs_error("platform_db_store", &db_path, &e))?;
    Ok(Value::Bool(true))
}

fn bi_platform_db_load(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let key = args
        .first()
        .and_then(|v| v.as_str().ok())
        .unwrap_or("default");

    let db_path = platform_db_path()?;
    if !db_path.exists() {
        return Ok(Value::Null);
    }

    let content = read_text_capped("platform_db_load", &db_path)?;
    // A corrupt store read as empty, so every key answered null.
    let db: serde_json::Map<String, serde_json::Value> =
        serde_json::from_str(&content).map_err(|e| {
            crate::safety::bad_state_with_hint(
                "platform_db_load",
                &format!(
                    "the platform store {} is not valid JSON: {e}",
                    db_path.display()
                ),
                "repair or delete the file; platform_db_store recreates it",
            )
        })?;
    match db.get(key) {
        Some(val) => Ok(json_to_value(val.clone())),
        None => Ok(Value::Null),
    }
}

fn bi_platform_db_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let db_path = platform_db_path()?;
    if !db_path.exists() {
        return Ok(Value::Array(vec![]));
    }

    let content = std::fs::read_to_string(&db_path)
        .map_err(|e| crate::safety::fs_error("platform_db_list", &db_path, &e))?;
    // A corrupt file was listed as empty before. It is now named as bad state.
    let db: serde_json::Map<String, serde_json::Value> =
        serde_json::from_str(&content).map_err(|e| {
            crate::safety::bad_state_with_hint(
                "platform_db_list",
                &format!("{} is not a JSON object: {e}", db_path.display()),
                "a valid platform DB file; repair or remove it",
            )
        })?;

    let keys: Vec<Value> = db.keys().map(|k| Value::Str(k.clone())).collect();
    Ok(Value::Array(keys))
}

fn bi_platform_db_delete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_db_delete", &input)?;
    // The key is required (the declaration says so). Validated before the guard,
    // so a missing key is E_BAD_ARG and never reaches the approval gate.
    let key = platform_str_arg("platform_db_delete", &args, 0)?
        .ok_or_else(|| crate::safety::bad_arg("platform_db_delete", "a key: String", "nothing"))?;

    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "platform_db_delete",
        effect: crate::safety::Effect::Destructive,
        what: "db_delete",
        targets: vec![key.clone()],
        blast_radius: serde_json::json!({ "key": key }),
        reversible: false,
        fs_paths: false,
    })?;

    let db_path = platform_db_path()?;
    if !db_path.exists() {
        return Ok(Value::Bool(false));
    }

    let content = std::fs::read_to_string(&db_path)
        .map_err(|e| crate::safety::fs_error("platform_db_delete", &db_path, &e))?;
    let mut db = platform_store_parse("platform_db_delete", &db_path, &content)?;

    let existed = db.remove(&key).is_some();
    // Written only when something was removed: a miss leaves the file untouched.
    if existed {
        std::fs::write(&db_path, serde_json::to_string_pretty(&db)?)
            .map_err(|e| crate::safety::fs_error("platform_db_delete", &db_path, &e))?;
    }

    Ok(Value::Bool(existed))
}

fn bi_platform_db_compare(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_db_compare", &input)?;
    let key_of = |index: usize| -> Result<String> {
        platform_str_arg("platform_db_compare", &args, index)?.ok_or_else(|| {
            crate::safety::bad_arg("platform_db_compare", "two keys: String, String", "fewer")
        })
    };
    let key1 = key_of(0)?;
    let key2 = key_of(1)?;

    // A key that is not in the store used to load as null, and the diff then
    // refused a null as "expected Record, got Null". Name the miss instead.
    let mut snapshots = Vec::with_capacity(2);
    for key in [key1, key2] {
        match bi_platform_db_load(vec![Value::Str(key.clone())], None)? {
            Value::Null => {
                return Err(crate::safety::not_found(
                    "platform_db_compare",
                    "platform snapshot",
                    &key,
                ))
            }
            snapshot => snapshots.push(snapshot),
        }
    }
    bi_platform_diff(snapshots, None)
}

fn bi_platform_db_export(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let file_path = args.first().and_then(|v| v.as_str().ok());

    let db_path = platform_db_path()?;
    // With no store yet, a requested export file was never written: the
    // call answered "{}" instead of the path.
    let content = if db_path.exists() {
        std::fs::read_to_string(&db_path)
            .map_err(|e| crate::safety::fs_error("platform_db_export", &db_path, &e))?
    } else {
        "{}".to_string()
    };

    if let Some(path) = file_path {
        // The destination was written with no workspace check at all.
        let path = guard_local_write("platform_db_export", path)?;
        crate::tx::snapshot(&path); // record pre-export state if a transaction is active
        write_file_atomically("platform_db_export", &path, content.as_bytes())?;
        Ok(Value::Str(path))
    } else {
        Ok(Value::Str(content))
    }
}

fn bi_platform_db_import(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_db_import", &input)?;
    let source = platform_str_arg("platform_db_import", &args, 0)?.ok_or_else(|| {
        crate::safety::bad_arg(
            "platform_db_import",
            "a JSON object, or the path of a file containing one",
            "nothing",
        )
    })?;

    // Check if it's a file path or JSON string
    let content = if std::path::Path::new(&source).exists() {
        read_text_capped("platform_db_import", &source)?
    } else {
        source.clone()
    };

    // Validate JSON
    let imported: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&content)
        .map_err(|e| {
            crate::safety::bad_arg(
                "platform_db_import",
                "a JSON object, or the path of a file containing one",
                &e.to_string(),
            )
        })?;

    let db_path = platform_db_path()?;
    bi_platform_db_init(vec![], None)?;

    // Merge with existing. A corrupt store used to read as empty here and be
    // overwritten by the import, losing its entries.
    let existing = std::fs::read_to_string(&db_path)
        .map_err(|e| crate::safety::fs_error("platform_db_import", &db_path, &e))?;
    let mut db = platform_store_parse("platform_db_import", &db_path, &existing)?;

    for (k, v) in imported {
        db.insert(k, v);
    }

    std::fs::write(&db_path, serde_json::to_string_pretty(&db)?)
        .map_err(|e| crate::safety::fs_error("platform_db_import", &db_path, &e))?;
    // The number of keys the store holds after the merge, not the number imported.
    Ok(Value::Int(db.len() as i64))
}

fn bi_platform_fingerprint(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_fingerprint", &input)?;
    let snapshot = bi_platform_snapshot(vec![], None)?;
    if let Value::Record(r) = snapshot {
        if let Some(fp @ Value::Str(_)) = r.get("fingerprint") {
            return Ok(fp.clone());
        }
    }
    // The snapshot always carries one, so its absence is a defect, not an
    // answer. It used to be the string "unknown".
    Err(crate::safety::bad_state(
        "platform_fingerprint",
        "the platform snapshot carries no fingerprint",
        "platform_snapshot",
    ))
}

fn bi_platform_hash(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let data = match args.first() {
        Some(v) => format!("{:?}", v),
        None => "".to_string(),
    };
    Ok(Value::Str(format!("{:x}", md5_simple(&data))))
}

// ============================================================================
// Platform Categorized Tool & Library Detection
// ============================================================================

fn bi_platform_compilers(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let compilers = [
        "gcc", "g++", "clang", "clang++", "rustc", "go", "javac", "swift", "kotlinc", "scalac",
        "ghc", "ocaml", "fpc", "gfortran", "nvcc", "hipcc", "dmd", "ldc2", "gdc", "zig", "nim",
        "crystal", "tcc", "pcc", "icc", "icx", "nvc", "nvc++", "emcc", "wasm-ld",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&compilers) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_build_systems(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let build_systems = [
        "make", "cmake", "ninja", "meson", "bazel", "buck2", "scons", "gradle", "maven", "ant",
        "cargo", "cabal", "stack", "mix", "dune", "xmake", "premake5", "waf", "rake", "shake",
        "tup", "gn", "gyp", "qmake", "autoconf", "automake", "libtool",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&build_systems) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_runtimes(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let runtimes = [
        "python", "python3", "node", "deno", "bun", "ruby", "php", "perl", "lua", "luajit",
        "julia", "R", "java", "dotnet", "mono", "erlang", "elixir", "racket", "sbcl", "clisp",
        "guile", "tcl", "tk", "groovy", "scala", "kotlin", "clojure",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&runtimes) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_pkg_lang(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let pkg_lang = [
        "pip", "pip3", "pipx", "poetry", "pdm", "uv", "conda", "mamba", "npm", "yarn", "pnpm",
        "bun", "gem", "bundler", "composer", "cargo", "go", "nuget", "dotnet", "maven", "gradle",
        "cabal", "stack", "opam", "mix", "hex", "rebar3", "cpan", "luarocks", "pub", "swift",
        "spm", "vcpkg", "conan", "hunter", "cpm",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&pkg_lang) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_containers(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let containers = [
        "docker",
        "podman",
        "buildah",
        "skopeo",
        "containerd",
        "runc",
        "nerdctl",
        "crictl",
        "ctr",
        "lxc",
        "lxd",
        "vagrant",
        "packer",
        "qemu-system-x86_64",
        "vboxmanage",
        "multipass",
        "lima",
        "colima",
        "rancher",
        "k3d",
        "kind",
        "minikube",
        "microk8s",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&containers) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_cloud_clis(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let cloud = [
        "aws",
        "az",
        "gcloud",
        "doctl",
        "linode-cli",
        "vultr-cli",
        "oci",
        "ibmcloud",
        "hcloud",
        "exo",
        "scaleway",
        "flyctl",
        "netlify",
        "vercel",
        "heroku",
        "railway",
        "render",
        "cf",
        "wrangler",
        "supabase",
        "firebase",
        "amplify",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&cloud) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_databases(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let databases = [
        "psql",
        "mysql",
        "sqlite3",
        "mongosh",
        "redis-cli",
        "mongod",
        "pg_dump",
        "mysqldump",
        "cqlsh",
        "influx",
        "clickhouse-client",
        "cockroach",
        "tiup",
        "vitess",
        "pgcli",
        "mycli",
        "litecli",
        "duckdb",
        "questdb",
        "timescaledb",
        "surreal",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&databases) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_linters(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let linters = [
        "eslint",
        "prettier",
        "black",
        "ruff",
        "mypy",
        "pylint",
        "flake8",
        "rubocop",
        "clippy",
        "rustfmt",
        "gofmt",
        "golangci-lint",
        "shellcheck",
        "hadolint",
        "yamllint",
        "jsonlint",
        "tflint",
        "stylelint",
        "htmlhint",
        "markdownlint",
        "actionlint",
        "cppcheck",
        "clang-tidy",
        "clang-format",
        "astyle",
        "uncrustify",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&linters) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_vcs(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let vcs = [
        "git",
        "hg",
        "svn",
        "fossil",
        "darcs",
        "bzr",
        "cvs",
        "git-lfs",
        "git-annex",
        "dvc",
        "gh",
        "glab",
        "hub",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&vcs) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_iac_tools(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let iac = [
        "kubectl",
        "helm",
        "kustomize",
        "k3s",
        "k3d",
        "kind",
        "minikube",
        "terraform",
        "terragrunt",
        "pulumi",
        "cdktf",
        "crossplane",
        "ansible",
        "ansible-playbook",
        "chef",
        "puppet",
        "salt",
        "vagrant",
        "packer",
        "nomad",
        "consul",
        "vault",
        "argocd",
        "flux",
        "tekton",
        "skaffold",
        "tilt",
        "devspace",
    ];
    let mut versions = std::collections::BTreeMap::new();
    for (tool, ver) in probe_tool_versions(&iac) {
        let tool = tool.as_str();
        versions.insert(tool.to_string(), Value::Str(ver));
    }
    Ok(Value::Record(versions))
}

fn bi_platform_libs(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut libs = std::collections::BTreeMap::new();

    // Check pkg-config for common libraries
    let check_libs = [
        "openssl",
        "libssl",
        "libcrypto",
        "zlib",
        "libpng",
        "libjpeg",
        "libcurl",
        "sqlite3",
        "libxml-2.0",
        "libffi",
        "glib-2.0",
        "gtk+-3.0",
        "qt5",
        "sdl2",
        "glfw3",
        "vulkan",
        "opencv4",
        "protobuf",
        "grpc",
        "boost",
        "eigen3",
        "fmt",
        "spdlog",
    ];

    for lib in check_libs {
        let mut cmd = crate::safety::child_command("pkg-config");
        cmd.args(["--modversion", lib]);
        if let Ok(out) = bounded_cmd_output("platform_libs", "pkg-config", cmd, PROBE_DEADLINE_SECS)
        {
            if out.status.success() {
                let ver = String::from_utf8_lossy(&out.stdout).trim().to_string();
                libs.insert(lib.to_string(), Value::Str(ver));
            }
        }
    }

    Ok(Value::Record(libs))
}

fn bi_platform_lib_version(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let lib = args.first().and_then(|v| v.as_str().ok()).unwrap_or("");
    crate::safety::reject_option_like("platform_lib_version", &[lib.to_string()])?;
    // A missing pkg-config and an absent library were both null, so "not
    // installed" could not be told from "could not ask". Null now means only
    // the library is unknown to pkg-config.
    let mut cmd = crate::safety::child_command("pkg-config");
    cmd.args(["--modversion", lib]);
    let out = bounded_cmd_output(
        "platform_lib_version",
        "pkg-config",
        cmd,
        PROBE_DEADLINE_SECS,
    )?;
    if out.status.success() {
        return Ok(Value::Str(
            String::from_utf8_lossy(&out.stdout).trim().to_string(),
        ));
    }
    // pkg-config and pkgconf say the module was not found ("Package 'x' was
    // not found", "No package 'x' found"); any other failure, such as a
    // broken .pc file, had also read as an unknown library.
    let stderr = String::from_utf8_lossy(&out.stderr);
    if stderr.contains("not found") || stderr.contains("No package") {
        return Ok(Value::Null);
    }
    Err(crate::safety::tool_failed(
        "platform_lib_version",
        "pkg-config --modversion",
        out.status.code(),
        &stderr,
    ))
}

/// Where a Linux libstdc++ is installed, read in this order. A host with none
/// of them has no libstdc++ to report.
#[cfg(target_os = "linux")]
const LIBSTDCXX_CANDIDATES: [&str; 4] = [
    "/usr/lib/x86_64-linux-gnu/libstdc++.so.6",
    "/usr/lib/aarch64-linux-gnu/libstdc++.so.6",
    "/usr/lib64/libstdc++.so.6",
    "/usr/lib/libstdc++.so.6",
];

/// The glibc line from `ldd --version`. Musl's ldd exits non-zero and names
/// musl: that is the answer "no glibc", `Ok(None)`. Any other non-zero exit, or
/// a clean exit with no line, is `Err` with the text to refuse with. A failed
/// listing must not read as an absent library.
#[cfg(any(target_os = "linux", test))]
fn glibc_from_ldd(success: bool, stdout: &str, stderr: &str) -> Result<Option<String>, String> {
    if success {
        return stdout
            .lines()
            .map(str::trim)
            .find(|l| !l.is_empty())
            .map(|l| Some(l.to_string()))
            .ok_or_else(|| "ldd printed no version line".to_string());
    }
    if format!("{stdout}{stderr}")
        .to_ascii_lowercase()
        .contains("musl")
    {
        return Ok(None);
    }
    Err(stderr.trim().to_string())
}

/// The last `GLIBCXX_` tag in `strings` output. A failed `strings` is `Err`,
/// whatever it printed; a successful one with no tags is `Ok(None)`.
#[cfg(any(target_os = "linux", test))]
fn libstdcxx_from_strings(
    success: bool,
    stdout: &str,
    stderr: &str,
) -> Result<Option<String>, String> {
    if !success {
        return Err(stderr.trim().to_string());
    }
    Ok(stdout
        .lines()
        .rfind(|l| l.starts_with("GLIBCXX_"))
        .map(str::to_string))
}

/// The first line of `xcodebuild -version`. A non-zero exit is `None`: on a
/// Mac with only the Command Line Tools that is the answer "no Xcode".
#[cfg(any(target_os = "macos", test))]
fn xcode_from_xcodebuild(success: bool, stdout: &str) -> Option<String> {
    if !success {
        return None;
    }
    stdout
        .lines()
        .map(str::trim)
        .find(|l| !l.is_empty())
        .map(str::to_string)
}

/// The compiler banner line from `cl` stderr. `cl` with no arguments prints
/// it and exits non-zero, so the banner, not the status, is what is read.
#[cfg(any(target_os = "windows", test))]
fn msvc_from_cl(stderr: &str) -> Option<String> {
    stderr
        .lines()
        .map(str::trim)
        .find(|l| l.contains("Version"))
        .map(str::to_string)
}

/// Whether a failed probe is a program that is not installed (E_TOOL_MISSING).
/// Not gated to Windows: the GPU probes use it on every host.
fn is_tool_missing(err: &anyhow::Error) -> bool {
    err.downcast_ref::<crate::safety::SafetyError>()
        .is_some_and(|se| se.code == crate::safety::ErrorCode::ToolMissing)
}

/// The toolchain facts this host has. A probe that fails is refused, never read
/// as absent. A fact that is optional by design (Xcode, MSVC, the Windows SDK
/// variables) is omitted when its tool says the thing is not there.
fn bi_platform_system_libs(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut info = std::collections::BTreeMap::new();

    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("ldd");
        cmd.arg("--version");
        let out = bounded_cmd_output("platform_system_libs", "ldd", cmd, PROBE_DEADLINE_SECS)?;
        let stdout = String::from_utf8_lossy(&out.stdout);
        let stderr = String::from_utf8_lossy(&out.stderr);
        match glibc_from_ldd(out.status.success(), &stdout, &stderr) {
            Ok(Some(line)) => {
                info.insert("glibc".to_string(), Value::Str(line));
            }
            Ok(None) => {}
            Err(stderr) => {
                return Err(crate::safety::tool_failed(
                    "platform_system_libs",
                    "ldd",
                    out.status.code(),
                    &stderr,
                ));
            }
        }

        // The first candidate that answers wins. A candidate whose `strings`
        // failed hands over to the next, and the last failure is refused only
        // when no candidate answers.
        let mut found: Option<String> = None;
        let mut failure: Option<anyhow::Error> = None;
        for path in LIBSTDCXX_CANDIDATES
            .iter()
            .filter(|p| std::path::Path::new(p).exists())
        {
            let mut cmd = crate::safety::child_command("strings");
            cmd.arg(path);
            match bounded_cmd_output("platform_system_libs", "strings", cmd, PROBE_DEADLINE_SECS) {
                Ok(out) => {
                    let stdout = String::from_utf8_lossy(&out.stdout);
                    let stderr = String::from_utf8_lossy(&out.stderr);
                    match libstdcxx_from_strings(out.status.success(), &stdout, &stderr) {
                        Ok(Some(v)) => {
                            found = Some(v);
                            break;
                        }
                        Ok(None) => {}
                        Err(stderr) => {
                            failure = Some(crate::safety::tool_failed(
                                "platform_system_libs",
                                "strings",
                                out.status.code(),
                                &stderr,
                            ));
                        }
                    }
                }
                Err(e) => failure = Some(e),
            }
        }
        match (found, failure) {
            (Some(v), _) => {
                info.insert("libstdc++".to_string(), Value::Str(v));
            }
            (None, Some(e)) => return Err(e),
            (None, None) => {}
        }
    }

    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("xcrun");
        cmd.args(["--show-sdk-version"]);
        let out = bounded_cmd_output("platform_system_libs", "xcrun", cmd, PROBE_DEADLINE_SECS)?;
        let sdk = probe_stdout("platform_system_libs", "xcrun", out)?;
        info.insert("macos_sdk".to_string(), Value::Str(sdk));

        let mut cmd = crate::safety::child_command("xcodebuild");
        cmd.arg("-version");
        let out = bounded_cmd_output(
            "platform_system_libs",
            "xcodebuild",
            cmd,
            PROBE_DEADLINE_SECS,
        )?;
        if let Some(line) =
            xcode_from_xcodebuild(out.status.success(), &String::from_utf8_lossy(&out.stdout))
        {
            info.insert("xcode".to_string(), Value::Str(line));
        }
    }

    #[cfg(target_os = "windows")]
    {
        // Get Windows SDK version
        if let Ok(sdk_path) = std::env::var("WindowsSdkDir") {
            info.insert("windows_sdk_path".to_string(), Value::Str(sdk_path));
        }
        if let Ok(sdk_ver) = std::env::var("WindowsSDKVersion") {
            info.insert("windows_sdk".to_string(), Value::Str(sdk_ver));
        }
        // Get Visual Studio version
        if let Ok(vs_path) = std::env::var("VSINSTALLDIR") {
            info.insert("vs_path".to_string(), Value::Str(vs_path));
        }
        // `cl` is on PATH only in a Developer prompt, so a missing `cl` is the
        // answer "no MSVC". Any other failure to run it is refused.
        let cmd = crate::safety::child_command("cl");
        match bounded_cmd_output("platform_system_libs", "cl", cmd, PROBE_DEADLINE_SECS) {
            Ok(out) => match msvc_from_cl(&String::from_utf8_lossy(&out.stderr)) {
                Some(line) => {
                    info.insert("msvc".to_string(), Value::Str(line));
                }
                None => {
                    return Err(crate::safety::bad_state_with_hint(
                        "platform_system_libs",
                        "unexpected `cl` output",
                        "a `Microsoft (R) C/C++ Optimizing Compiler Version` banner",
                    ));
                }
            },
            Err(e) if is_tool_missing(&e) => {}
            Err(e) => return Err(e),
        }
    }

    Ok(Value::Record(info))
}

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

    /// platform_snapshot's fingerprint hashes os_version and build, so the
    /// kernel-read strings must be the ones `cmd /c ver` gave. Compared only
    /// where ver prints the English line it can be compared with.
    #[cfg(target_os = "windows")]
    #[test]
    fn the_version_strings_are_the_ones_ver_printed() {
        let mut cmd = crate::safety::child_command("cmd");
        cmd.args(["/c", "ver"]);
        let out = bounded_cmd_output("platform_os_version", "cmd", cmd, PROBE_DEADLINE_SECS)
            .expect("cmd runs");
        let ver = String::from_utf8_lossy(&out.stdout).trim().to_string();
        let Value::Str(line) = bi_platform_os_version(vec![], None).unwrap() else {
            panic!("platform_os_version is not a String");
        };
        if ver.contains("[Version ") {
            assert_eq!(line, ver);
        }
        let inner = line
            .strip_prefix("Microsoft Windows [Version ")
            .and_then(|v| v.strip_suffix(']'))
            .expect("the ver form");
        let parts: Vec<&str> = inner.split('.').collect();
        let str_of = |v: Value| match v {
            Value::Str(s) => s,
            other => panic!("not a String: {other:?}"),
        };
        assert_eq!(
            str_of(bi_platform_kernel(vec![], None).unwrap()),
            parts[..3].join(".")
        );
        assert_eq!(str_of(bi_platform_build(vec![], None).unwrap()), parts[2]);
        assert_eq!(str_of(bi_sys_kernel(vec![], None).unwrap()), inner);
    }

    #[test]
    fn os_release_pretty_name_is_unquoted_and_absent_when_missing() {
        let text = "NAME=\"Debian GNU/Linux\"\nPRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\"\n";
        assert_eq!(
            os_release_pretty_name(text).as_deref(),
            Some("Debian GNU/Linux 12 (bookworm)")
        );
        assert_eq!(os_release_pretty_name("NAME=\"x\"\n"), None);
    }

    #[test]
    fn glibc_from_ldd_reads_the_first_line_on_success() {
        assert_eq!(
            glibc_from_ldd(true, "ldd (GNU libc) 2.39\nCopyright\n", ""),
            Ok(Some("ldd (GNU libc) 2.39".to_string()))
        );
    }

    #[test]
    fn glibc_from_ldd_clean_exit_without_a_line_is_refused() {
        assert!(glibc_from_ldd(true, "\n", "").is_err());
    }

    #[test]
    fn glibc_from_ldd_musl_is_no_glibc_not_a_failure() {
        assert_eq!(
            glibc_from_ldd(false, "", "musl libc (x86_64)\nVersion 1.2.4"),
            Ok(None)
        );
    }

    #[test]
    fn glibc_from_ldd_failed_listing_is_refused_not_read_as_absent() {
        // The old code left glibc out of the record on a non-zero ldd, which
        // read as "no glibc". It is a refusal now.
        assert_eq!(
            glibc_from_ldd(false, "", "ldd: boom"),
            Err("ldd: boom".to_string())
        );
    }

    #[test]
    fn libstdcxx_from_strings_takes_the_last_glibcxx_tag() {
        assert_eq!(
            libstdcxx_from_strings(true, "junk\nGLIBCXX_3.4.29\nGLIBCXX_3.4.32\n", ""),
            Ok(Some("GLIBCXX_3.4.32".to_string()))
        );
    }

    #[test]
    fn libstdcxx_from_failed_strings_is_refused_even_when_it_printed_tags() {
        // The old code parsed the stdout of a failed `strings` as the answer.
        assert!(libstdcxx_from_strings(false, "GLIBCXX_3.4.29\n", "strings: boom").is_err());
    }

    #[test]
    fn libstdcxx_without_glibcxx_tags_is_no_answer() {
        assert_eq!(libstdcxx_from_strings(true, "nothing here\n", ""), Ok(None));
    }

    #[test]
    fn xcode_is_absent_when_xcodebuild_fails_on_a_clt_only_host() {
        assert_eq!(
            xcode_from_xcodebuild(
                false,
                "xcode-select: error: tool 'xcodebuild' requires Xcode"
            ),
            None
        );
    }

    #[test]
    fn xcode_takes_the_first_line_of_version_output() {
        assert_eq!(
            xcode_from_xcodebuild(true, "Xcode 15.4\nBuild version 15F31d\n").as_deref(),
            Some("Xcode 15.4")
        );
    }

    #[test]
    fn msvc_reads_the_banner_line_from_stderr() {
        let stderr = "Microsoft (R) C/C++ Optimizing Compiler Version 19.39.33523 for x64\r\nCopyright (C) Microsoft Corporation.\r\n\r\nusage: cl [ option... ]\r\n";
        assert_eq!(
            msvc_from_cl(stderr).as_deref(),
            Some("Microsoft (R) C/C++ Optimizing Compiler Version 19.39.33523 for x64")
        );
    }

    #[test]
    fn msvc_without_a_banner_is_none() {
        assert_eq!(msvc_from_cl(""), None);
        assert_eq!(msvc_from_cl("error: something else"), None);
    }
}

fn bi_platform_sdk_version(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let sdk = args.first().and_then(|v| v.as_str().ok()).unwrap_or("");

    match sdk {
        "android" => {
            if let Ok(home) =
                std::env::var("ANDROID_HOME").or_else(|_| std::env::var("ANDROID_SDK_ROOT"))
            {
                // Try to read build-tools version. A missing directory is an
                // SDK that is not installed (Null below); an unreadable one is
                // an error, not an empty list.
                let bt_path = std::path::Path::new(&home).join("build-tools");
                match std::fs::read_dir(&bt_path) {
                    Ok(entries) => {
                        let versions: Vec<String> = entries
                            .filter_map(|e| e.ok())
                            .filter_map(|e| e.file_name().into_string().ok())
                            .collect();
                        return Ok(Value::Array(versions.into_iter().map(Value::Str).collect()));
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                    Err(e) => {
                        return Err(crate::safety::fs_error(
                            "platform_sdk_version",
                            &bt_path,
                            &e,
                        ))
                    }
                }
            }
        }
        "ios" | "macos" | "xcode" => {
            // A failing xcrun used to answer "" (or Null when it failed to
            // start). Absent xcrun is still "not installed".
            let mut cmd = crate::safety::child_command("xcrun");
            cmd.args(["--show-sdk-version"]);
            if let Some(version) = probe_text_if_installed("platform_sdk_version", "xcrun", cmd)? {
                return Ok(Value::Str(version));
            }
        }
        "windows" => {
            if let Ok(ver) = std::env::var("WindowsSDKVersion") {
                return Ok(Value::Str(ver));
            }
        }
        "dotnet" => {
            // A probe error used to fall through to Null ("not installed").
            let mut cmd = crate::safety::child_command("dotnet");
            cmd.args(["--list-sdks"]);
            if let Some(text) = probe_text_if_installed("platform_sdk_version", "dotnet", cmd)? {
                let sdks: Vec<Value> = text.lines().map(|l| Value::Str(l.to_string())).collect();
                return Ok(Value::Array(sdks));
            }
        }
        "java" | "jdk" => {
            if let Ok(home) = std::env::var("JAVA_HOME") {
                return Ok(Value::Str(home));
            }
        }
        // An SDK name this does not know answered null, which reads as
        // "not installed".
        other => {
            return Err(crate::safety::bad_arg(
                "platform_sdk_version",
                "sdk android, ios, macos, xcode, windows, dotnet, java or jdk",
                other,
            ))
        }
    }

    // A known SDK that is not installed.
    Ok(Value::Null)
}

fn bi_platform_libc(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("ldd");
        cmd.arg("--version");
        if let Ok(out) = bounded_cmd_output("platform_libc", "ldd", cmd, PROBE_DEADLINE_SECS) {
            let ver = String::from_utf8_lossy(&out.stdout);
            if let Some(line) = ver.lines().next() {
                return Ok(Value::Str(line.to_string()));
            }
        }
        // Alternative: check /lib
        if let Ok(entries) = std::fs::read_dir("/lib/x86_64-linux-gnu") {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();
                if name.starts_with("libc.so") || name.starts_with("libc-") {
                    return Ok(Value::Str(name));
                }
            }
        }
    }
    #[cfg(target_os = "macos")]
    {
        return Ok(Value::Str("libSystem (macOS)".to_string()));
    }
    #[cfg(target_os = "windows")]
    {
        // MSVC runtime
        let mut cmd = crate::safety::child_command("where");
        cmd.arg("ucrtbase.dll");
        if let Ok(out) = bounded_cmd_output("platform_libc", "where", cmd, PROBE_DEADLINE_SECS) {
            if out.status.success() {
                return Ok(Value::Str("ucrt (Universal CRT)".to_string()));
            }
        }
        return Ok(Value::Str("msvcrt".to_string()));
    }
    Ok(Value::Str("unknown".to_string()))
}

/// The highest `<prefix>N.N.N` symbol-version string in a binary, compared
/// numerically: by string order `GLIBCXX_3.4.9` outranks `GLIBCXX_3.4.33`.
#[cfg(target_os = "linux")]
fn highest_symbol_version(bytes: &[u8], prefix: &str) -> Option<String> {
    let p = prefix.as_bytes();
    let mut best: Option<(Vec<u64>, String)> = None;
    let mut i = 0;
    while i + p.len() <= bytes.len() {
        if &bytes[i..i + p.len()] == p {
            let start = i + p.len();
            let end = bytes[start..]
                .iter()
                .position(|b| !(b.is_ascii_digit() || *b == b'.'))
                .map_or(bytes.len(), |n| start + n);
            let ver = std::str::from_utf8(&bytes[start..end]).unwrap_or("");
            let key: Vec<u64> = ver.split('.').filter_map(|x| x.parse().ok()).collect();
            if !key.is_empty() && best.as_ref().is_none_or(|(k, _)| key > *k) {
                best = Some((key, ver.to_string()));
            }
            i = end;
        } else {
            i += 1;
        }
    }
    best.map(|(_, v)| v)
}

#[cfg(all(test, target_os = "linux"))]
mod highest_symbol_version_tests {
    use super::highest_symbol_version;

    #[test]
    fn versions_compare_numerically_not_as_strings() {
        let bin = b"\0GLIBCXX_3.4.9\0GLIBCXX_3.4.33\0GLIBCXX_3.4.4\0CXXABI_1.3.15\0CXXABI_1.3.9\0";
        assert_eq!(
            highest_symbol_version(bin, "GLIBCXX_").as_deref(),
            Some("3.4.33")
        );
        assert_eq!(
            highest_symbol_version(bin, "CXXABI_").as_deref(),
            Some("1.3.15")
        );
        assert_eq!(highest_symbol_version(bin, "NOPE_"), None);
    }
}

/// Largest C++ runtime library read on Linux; a larger file is refused.
#[cfg(target_os = "linux")]
const LIBSTDCXX_READ_LIMIT: u64 = 64 * 1024 * 1024;

/// Most of msvcp140.dll that is read on Windows. The version resource sits
/// well inside this bound; the read stops there rather than failing.
#[cfg(target_os = "windows")]
const MSVCP140_READ_LIMIT: u64 = 16 * 1024 * 1024;

/// Open a candidate runtime library. `Ok(None)` means it does not exist, so the
/// caller moves on to the next path. Any other failure to open is a coded error:
/// a file that exists but cannot be read is never skipped.
#[cfg(any(windows, target_os = "linux"))]
fn open_candidate(path: &std::path::Path) -> Result<Option<std::fs::File>> {
    match std::fs::File::open(path) {
        Ok(file) => Ok(Some(file)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(crate::safety::fs_error("platform_libcpp", path, &e)),
    }
}

/// Read at most `limit` bytes of an opened candidate.
#[cfg(any(windows, target_os = "linux"))]
fn read_up_to(file: std::fs::File, path: &std::path::Path, limit: u64) -> Result<Vec<u8>> {
    use std::io::Read;
    let mut bytes = Vec::new();
    file.take(limit)
        .read_to_end(&mut bytes)
        .map_err(|e| crate::safety::fs_error("platform_libcpp", path, &e))?;
    Ok(bytes)
}

/// The file version of the Visual C++ STL runtime, read from the version
/// resource of `%SystemRoot%\System32\msvcp140.dll`. Nothing is made up: a
/// missing runtime or an unreadable version resource is a coded error.
#[cfg(target_os = "windows")]
fn msvcp140_version() -> Result<String> {
    let system_root = std::env::var_os("SystemRoot")
        .filter(|v| !v.is_empty())
        .map_or_else(
            || std::path::PathBuf::from("C:\\Windows"),
            std::path::PathBuf::from,
        );
    let path = system_root.join("System32").join("msvcp140.dll");
    let Some(file) = open_candidate(&path)? else {
        return Err(crate::safety::bad_state_with_hint(
            "platform_libcpp",
            "no MSVC C++ runtime (msvcp140.dll) was found",
            "install the Visual C++ Redistributable",
        ));
    };
    let bytes = read_up_to(file, &path, MSVCP140_READ_LIMIT)?;
    pe_version::pe_file_version(&bytes).ok_or_else(|| {
        crate::safety::bad_state_with_hint(
            "platform_libcpp",
            "the version resource of msvcp140.dll could not be read",
            "reinstall the Visual C++ Redistributable",
        )
    })
}

/// The version of the system libc++ on macOS: the `current version` in the
/// LC_ID_DYLIB load command of /usr/lib/libc++.1.dylib, as dyld mapped it.
/// The library exists only in the dyld shared cache, so there is no file for
/// `otool -L` to read (it exits 1 on the runner); dlopen maps it from the
/// cache, and its in-memory header carries the same load commands. A library
/// that does not load or a header without LC_ID_DYLIB is a coded error; no
/// version is guessed.
#[cfg(target_os = "macos")]
// libc marks the dyld image accessors deprecated in favour of the mach2
// crate; they are still libSystem's public API.
#[allow(deprecated)]
fn libcxx_version_macos() -> Result<String> {
    const LIBCXX: &str = "/usr/lib/libc++.1.dylib";
    const LC_ID_DYLIB: u32 = 0xd;
    let unreadable = |why: &str| {
        crate::safety::bad_state_with_hint(
            "platform_libcpp",
            &format!("the version of the system libc++ could not be read: {why}"),
            "check that /usr/lib/libc++.1.dylib is present in the dyld shared cache",
        )
    };
    let path = std::ffi::CString::new(LIBCXX).expect("no NUL in a constant");
    // SAFETY: a NUL-terminated path; the handle is kept, so the image stays
    // mapped while its header is read below.
    let handle = unsafe { libc::dlopen(path.as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL) };
    if handle.is_null() {
        return Err(unreadable("dlopen did not load it"));
    }
    // SAFETY: dyld's image list is read with its own accessors; an index below
    // _dyld_image_count names a mapped image, and a mapped image's header is
    // followed by `sizeofcmds` bytes of load commands.
    let current = unsafe {
        let mut found = None;
        for i in 0..libc::_dyld_image_count() {
            let name = libc::_dyld_get_image_name(i);
            if name.is_null() || std::ffi::CStr::from_ptr(name).to_bytes() != LIBCXX.as_bytes() {
                continue;
            }
            let header = libc::_dyld_get_image_header(i);
            if header.is_null() {
                continue;
            }
            let ncmds = (*header).ncmds;
            let sizeofcmds = (*header).sizeofcmds as usize;
            let start = (header as *const u8).add(std::mem::size_of::<libc::mach_header_64>());
            let mut offset = 0usize;
            for _ in 0..ncmds {
                if offset + 24 > sizeofcmds {
                    break;
                }
                let at = start.add(offset);
                let cmd = std::ptr::read_unaligned(at as *const u32);
                let cmdsize = std::ptr::read_unaligned(at.add(4) as *const u32) as usize;
                if cmd == LC_ID_DYLIB {
                    // dylib_command: cmd, cmdsize, name offset, timestamp,
                    // current_version, compatibility_version.
                    found = Some(std::ptr::read_unaligned(at.add(16) as *const u32));
                    break;
                }
                if cmdsize < 8 {
                    break;
                }
                offset += cmdsize;
            }
            break;
        }
        found
    };
    let Some(v) = current else {
        return Err(unreadable("no LC_ID_DYLIB in its mapped header"));
    };
    // X.Y.Z packed as xxxx.yy.zz.
    Ok(format!("{}.{}.{}", v >> 16, (v >> 8) & 0xff, v & 0xff))
}

/// The C++ standard library: {name, version, abi}. The version and abi are
/// null where the platform does not report them.
///
/// On Windows the MSVC STL version comes from msvcp140.dll's version resource.
/// On Linux the libstdc++ symbol versions are read from the library, and an
/// unreadable candidate is a coded error. On macOS the libc++ version is read
/// from dyld's mapping of the library (see `libcxx_version_macos`); the abi
/// stays null.
fn bi_platform_libcpp(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    no_args_or_input("platform_libcpp", &args, &input)?;
    // One shape everywhere: {name, version, abi}. It was a Record of symbol
    // versions on Linux and a bare String elsewhere, so the same call had two
    // types depending on the OS. The Linux side also shelled out to
    // `strings` (absent without binutils), picked the "highest" version by
    // string order, looked only in x86_64 paths, and fell back to the string
    // "unknown".
    let lib = |name: &str, version: Option<String>, abi: Option<String>| {
        let mut rec = std::collections::BTreeMap::new();
        rec.insert("name".to_string(), Value::Str(name.to_string()));
        rec.insert(
            "version".to_string(),
            version.map_or(Value::Null, Value::Str),
        );
        rec.insert("abi".to_string(), abi.map_or(Value::Null, Value::Str));
        Value::Record(rec)
    };
    #[cfg(target_os = "linux")]
    {
        for path in [
            "/usr/lib/x86_64-linux-gnu/libstdc++.so.6",
            "/usr/lib/aarch64-linux-gnu/libstdc++.so.6",
            "/usr/lib64/libstdc++.so.6",
            "/usr/lib/libstdc++.so.6",
            "/lib/x86_64-linux-gnu/libstdc++.so.6",
        ] {
            let path = std::path::Path::new(path);
            let Some(file) = open_candidate(path)? else {
                continue;
            };
            let len = file
                .metadata()
                .map_err(|e| crate::safety::fs_error("platform_libcpp", path, &e))?
                .len();
            if len > LIBSTDCXX_READ_LIMIT {
                return Err(crate::safety::budget_exceeded(
                    "platform_libcpp",
                    format!(
                        "`{}` is {len} bytes, over the {LIBSTDCXX_READ_LIMIT}-byte read limit",
                        path.display()
                    ),
                    "the C++ runtime is read only up to this bound; a larger file is refused",
                ));
            }
            let bytes = read_up_to(file, path, LIBSTDCXX_READ_LIMIT)?;
            return Ok(lib(
                "libstdc++",
                highest_symbol_version(&bytes, "GLIBCXX_"),
                highest_symbol_version(&bytes, "CXXABI_"),
            ));
        }
        for path in [
            "/usr/lib/x86_64-linux-gnu/libc++.so.1",
            "/usr/lib/aarch64-linux-gnu/libc++.so.1",
            "/usr/lib/libc++.so.1",
        ] {
            // libc++ reports no version here, so opening it is the whole check.
            if open_candidate(std::path::Path::new(path))?.is_some() {
                return Ok(lib("libc++", None, None));
            }
        }
        return Err(crate::safety::bad_state_with_hint(
            "platform_libcpp",
            "no C++ standard library (libstdc++ or libc++) was found in the usual locations",
            "install libstdc++6 or libc++1",
        ));
    }
    #[cfg(target_os = "macos")]
    {
        let version = libcxx_version_macos()?;
        return Ok(lib("libc++", Some(version), None));
    }
    #[cfg(target_os = "windows")]
    {
        let version = msvcp140_version()?;
        return Ok(lib("MSVC STL", Some(version), Some("msvcp140".to_string())));
    }
    #[allow(unreachable_code)]
    Err(crate::safety::unimplemented(
        "platform_libcpp",
        "detecting the C++ standard library is implemented for Linux, macOS and Windows only; NOTHING WAS INSPECTED",
        "",
    ))
}

fn bi_platform_ssl_version(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Try openssl first
    let mut cmd = crate::safety::child_command("openssl");
    cmd.arg("version");
    if let Ok(out) = bounded_cmd_output("platform_ssl_version", "openssl", cmd, PROBE_DEADLINE_SECS)
    {
        if out.status.success() {
            return Ok(Value::Str(
                String::from_utf8_lossy(&out.stdout).trim().to_string(),
            ));
        }
    }
    // Try pkg-config
    let mut cmd = crate::safety::child_command("pkg-config");
    cmd.args(["--modversion", "openssl"]);
    if let Ok(out) = bounded_cmd_output(
        "platform_ssl_version",
        "pkg-config",
        cmd,
        PROBE_DEADLINE_SECS,
    ) {
        if out.status.success() {
            return Ok(Value::Str(
                String::from_utf8_lossy(&out.stdout).trim().to_string(),
            ));
        }
    }
    Ok(Value::Null)
}

fn bi_platform_cuda_version(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut info = std::collections::BTreeMap::new();

    // CUDA Toolkit version
    // nvcc's output was recorded without checking its exit status, so a failing
    // nvcc filled in the toolkit line from whatever it printed. A tool that is
    // not installed is still just absent.
    let mut cmd = crate::safety::child_command("nvcc");
    cmd.arg("--version");
    if let Some(output) = probe_text_if_installed("platform_cuda_version", "nvcc", cmd)? {
        for line in output.lines() {
            if line.contains("release") {
                info.insert(
                    "cuda_toolkit".to_string(),
                    Value::Str(line.trim().to_string()),
                );
                break;
            }
        }
    }

    // NVIDIA driver version
    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("nvidia-smi");
        cmd.args(["--query-gpu=driver_version", "--format=csv,noheader"]);
        // A failing nvidia-smi used to be skipped; it is an error now.
        if let Some(ver) = probe_text_if_installed("platform_cuda_version", "nvidia-smi", cmd)? {
            info.insert("nvidia_driver".to_string(), Value::Str(ver));
        }
    }
    #[cfg(target_os = "windows")]
    {
        let cmd = crate::safety::child_command("nvidia-smi");
        // A failing nvidia-smi used to be skipped; it is an error now.
        if let Some(output) = probe_text_if_installed("platform_cuda_version", "nvidia-smi", cmd)? {
            for line in output.lines() {
                if line.contains("Driver Version") {
                    info.insert(
                        "nvidia_driver".to_string(),
                        Value::Str(line.trim().to_string()),
                    );
                    break;
                }
            }
        }
    }

    // cuDNN version
    if let Ok(cudnn_path) = std::env::var("CUDNN_PATH") {
        info.insert("cudnn_path".to_string(), Value::Str(cudnn_path));
    }

    // Check for ROCm/HIP as alternative
    // hipcc's output was recorded without an exit-status check, as nvcc's was.
    let mut cmd = crate::safety::child_command("hipcc");
    cmd.arg("--version");
    if let Some(ver) = probe_text_if_installed("platform_cuda_version", "hipcc", cmd)? {
        if let Some(line) = ver.lines().next() {
            info.insert("hip".to_string(), Value::Str(line.to_string()));
        }
    }

    if info.is_empty() {
        Ok(Value::Null)
    } else {
        Ok(Value::Record(info))
    }
}

// ============================================================================
// Platform Hardware Detection
// ============================================================================

fn bi_platform_cpu(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut info = std::collections::BTreeMap::new();

    #[cfg(target_os = "windows")]
    {
        // Windows: was a PowerShell Get-CimInstance Win32_Processor query (WMI),
        // parsed from its JSON. Now read in process: the name and physical core
        // count through sysinfo; the logical count from available_parallelism
        // (the count sys_cpu_count gives, not WMI's NumberOfLogicalProcessors);
        // and the clock from the registry's ~MHz value (the boot-time reading,
        // not WMI's rated MaxClockSpeed). A value that cannot be read is left out.
        let sys = System::new_with_specifics(
            sysinfo::RefreshKind::nothing().with_cpu(sysinfo::CpuRefreshKind::nothing()),
        );
        if let Some(cpu) = sys.cpus().first() {
            let name = cpu.brand().trim();
            if !name.is_empty() {
                info.insert("name".to_string(), Value::Str(name.to_string()));
            }
        }
        if let Some(cores) = sys.physical_core_count() {
            info.insert("cores".to_string(), Value::Int(cores as i64));
        }
        if let Ok(lp) = std::thread::available_parallelism() {
            info.insert(
                "logical_processors".to_string(),
                Value::Int(lp.get() as i64),
            );
        }
        if let Ok(Some(mhz)) = windows_cpu_mhz("platform_cpu") {
            info.insert("max_clock_mhz".to_string(), Value::Int(mhz as i64));
        }
        // Also get architecture
        if let Ok(arch) = std::env::var("PROCESSOR_ARCHITECTURE") {
            info.insert("arch".to_string(), Value::Str(arch));
        }
    }

    #[cfg(target_os = "linux")]
    {
        if let Ok(cpuinfo) = std::fs::read_to_string("/proc/cpuinfo") {
            for line in cpuinfo.lines() {
                if let Some((key, val)) = line.split_once(':') {
                    let key = key.trim();
                    let val = val.trim();
                    match key {
                        "model name" => {
                            info.insert("name".to_string(), Value::Str(val.to_string()));
                        }
                        "cpu cores" => {
                            if let Ok(n) = val.parse::<i64>() {
                                info.insert("cores".to_string(), Value::Int(n));
                            }
                        }
                        "siblings" => {
                            if let Ok(n) = val.parse::<i64>() {
                                info.insert("logical_processors".to_string(), Value::Int(n));
                            }
                        }
                        "cpu MHz" => {
                            if let Ok(f) = val.parse::<f64>() {
                                info.insert("current_mhz".to_string(), Value::Float(f));
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        info.insert(
            "arch".to_string(),
            Value::Str(std::env::consts::ARCH.to_string()),
        );
    }

    #[cfg(target_os = "macos")]
    {
        // A failed sysctl used to put its empty stdout in as `name` (""), or
        // drop the count silently. Each probe is an error now if it fails.
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "machdep.cpu.brand_string"]);
        let name = probe_text("platform_cpu", "sysctl", cmd)?;
        info.insert("name".to_string(), Value::Str(name));
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "hw.physicalcpu"]);
        let cores = probe_text("platform_cpu", "sysctl", cmd)?;
        let cores = cores.parse::<i64>().map_err(|e| {
            crate::safety::bad_state_with_hint(
                "platform_cpu",
                &format!("hw.physicalcpu is not a number: {e}"),
                "a sysctl that reports the physical CPU count",
            )
        })?;
        info.insert("cores".to_string(), Value::Int(cores));
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "hw.logicalcpu"]);
        let logical = probe_text("platform_cpu", "sysctl", cmd)?;
        let logical = logical.parse::<i64>().map_err(|e| {
            crate::safety::bad_state_with_hint(
                "platform_cpu",
                &format!("hw.logicalcpu is not a number: {e}"),
                "a sysctl that reports the logical CPU count",
            )
        })?;
        info.insert("logical_processors".to_string(), Value::Int(logical));
        info.insert(
            "arch".to_string(),
            Value::Str(std::env::consts::ARCH.to_string()),
        );
    }

    Ok(Value::Record(info))
}

fn bi_platform_cpu_count(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Use std::thread::available_parallelism for logical CPUs. A failure used to
    // answer 1, which is a real count; it is an error now.
    match std::thread::available_parallelism() {
        Ok(count) => Ok(Value::Int(count.get() as i64)),
        Err(e) => Err(crate::safety::bad_state_with_hint(
            "platform_cpu_count",
            &format!("the CPU count could not be read: {e}"),
            "a host that reports its available parallelism",
        )),
    }
}

fn bi_platform_cpu_freq(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // MHz as a Float on every OS. It was an Int on Windows and macOS and a
    // Float on Linux, so the same call had two types. Null where the OS
    // reports no frequency (Apple Silicon, many ARM and virtual CPUs).
    #[cfg(target_os = "windows")]
    {
        // Null on an unreadable value, as Null was the answer to a failed
        // PowerShell query before.
        if let Ok(Some(mhz)) = windows_cpu_mhz("platform_cpu_freq") {
            return Ok(Value::Float(mhz as f64));
        }
    }
    #[cfg(target_os = "linux")]
    {
        if let Ok(cpuinfo) = std::fs::read_to_string("/proc/cpuinfo") {
            for line in cpuinfo.lines() {
                if line.starts_with("cpu MHz") {
                    if let Some((_, val)) = line.split_once(':') {
                        if let Ok(f) = val.trim().parse::<f64>() {
                            return Ok(Value::Float(f));
                        }
                    }
                }
            }
        }
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "hw.cpufrequency"]);
        // A sysctl that exits non-zero has no hw.cpufrequency (Apple Silicon),
        // which is the Null below. probe_text checks the exit status.
        if let Ok(text) = probe_text("platform_cpu_freq", "sysctl", cmd) {
            if let Ok(n) = text.parse::<i64>() {
                return Ok(Value::Float(n as f64 / 1_000_000.0)); // Hz to MHz
            }
        }
    }
    Ok(Value::Null)
}

fn bi_platform_memory(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_memory", &input)?;
    let mut info = std::collections::BTreeMap::new();

    // A probe that fails is a coded error. Each one used to be skipped, so a
    // failed query answered {} -- indistinguishable from "this host has no
    // memory to report".
    // Was WMI Win32_OperatingSystem through PowerShell; now sysinfo, in process.
    // The old "free" was WMI's FreePhysicalMemory, and sysinfo's available_memory
    // counts standby memory too, so free_kb can read higher than the old figure.
    #[cfg(target_os = "windows")]
    {
        let system = memory_snapshot("platform_memory")?;
        let total = system.total_memory();
        info.insert("total_kb".to_string(), Value::Int((total / 1024) as i64));
        info.insert(
            "total_gb".to_string(),
            Value::Float(total as f64 / 1024.0 / 1024.0 / 1024.0),
        );
        let free = system.available_memory();
        info.insert("free_kb".to_string(), Value::Int((free / 1024) as i64));
        info.insert(
            "free_gb".to_string(),
            Value::Float(free as f64 / 1024.0 / 1024.0 / 1024.0),
        );
    }

    #[cfg(target_os = "linux")]
    {
        let meminfo = std::fs::read_to_string("/proc/meminfo")
            .map_err(|e| crate::safety::fs_error("platform_memory", "/proc/meminfo", &e))?;
        {
            for line in meminfo.lines() {
                if let Some((key, val)) = line.split_once(':') {
                    let key = key.trim();
                    let val = val.trim().replace(" kB", "");
                    if let Ok(kb) = val.parse::<i64>() {
                        match key {
                            "MemTotal" => {
                                info.insert("total_kb".to_string(), Value::Int(kb));
                                info.insert(
                                    "total_gb".to_string(),
                                    Value::Float(kb as f64 / 1024.0 / 1024.0),
                                );
                            }
                            "MemFree" => {
                                info.insert("free_kb".to_string(), Value::Int(kb));
                            }
                            "MemAvailable" => {
                                info.insert("available_kb".to_string(), Value::Int(kb));
                                info.insert(
                                    "available_gb".to_string(),
                                    Value::Float(kb as f64 / 1024.0 / 1024.0),
                                );
                            }
                            "Buffers" => {
                                info.insert("buffers_kb".to_string(), Value::Int(kb));
                            }
                            "Cached" => {
                                info.insert("cached_kb".to_string(), Value::Int(kb));
                            }
                            "SwapTotal" => {
                                info.insert("swap_total_kb".to_string(), Value::Int(kb));
                            }
                            "SwapFree" => {
                                info.insert("swap_free_kb".to_string(), Value::Int(kb));
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "hw.memsize"]);
        let out = bounded_cmd_output("platform_memory", "sysctl", cmd, PROBE_DEADLINE_SECS)
            .map_err(|e| {
                crate::safety::tool_missing("platform_memory", "sysctl", &e.to_string())
            })?;
        if !out.status.success() {
            return Err(crate::safety::tool_failed(
                "platform_memory",
                "sysctl -n hw.memsize",
                out.status.code(),
                &String::from_utf8_lossy(&out.stderr),
            ));
        }
        let bytes = String::from_utf8_lossy(&out.stdout)
            .trim()
            .parse::<i64>()
            .map_err(|e| {
                crate::safety::tool_failed(
                    "platform_memory",
                    "sysctl -n hw.memsize",
                    out.status.code(),
                    &format!("it did not print a byte count: {e}"),
                )
            })?;
        info.insert("total_bytes".to_string(), Value::Int(bytes));
        info.insert(
            "total_gb".to_string(),
            Value::Float(bytes as f64 / 1024.0 / 1024.0 / 1024.0),
        );
    }

    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        return Err(crate::safety::unimplemented(
            "platform_memory",
            "memory detection is not implemented for this operating system",
            "read the memory total from the operating system directly",
        ));
    }

    #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
    {
        if !info.contains_key("total_kb") && !info.contains_key("total_bytes") {
            return Err(crate::safety::tool_failed(
                "platform_memory",
                "the platform memory query",
                None,
                "it reported no total memory",
            ));
        }
    }

    Ok(Value::Record(info))
}

fn bi_platform_memory_total(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Was WMI Win32_OperatingSystem through PowerShell; now sysinfo, in process.
    // Returns bytes, as before.
    #[cfg(target_os = "windows")]
    {
        let system = memory_snapshot("platform_memory_total")?;
        return memory_bytes("platform_memory_total", system.total_memory());
    }
    #[cfg(target_os = "linux")]
    {
        if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
            for line in meminfo.lines() {
                if line.starts_with("MemTotal:") {
                    let val = line.replace("MemTotal:", "").replace(" kB", "");
                    if let Ok(kb) = val.trim().parse::<i64>() {
                        return Ok(Value::Int(kb * 1024));
                    }
                }
            }
        }
    }
    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("sysctl");
        cmd.args(["-n", "hw.memsize"]);
        // probe_text refuses a non-zero exit with its code and stderr.
        let text = probe_text("platform_memory_total", "sysctl", cmd)?;
        if let Ok(bytes) = text.parse::<i64>() {
            return Ok(Value::Int(bytes));
        }
    }
    // Every machine has memory; reaching here means detection failed, which a
    // null reported as an answer.
    #[allow(unreachable_code)]
    Err(crate::safety::tool_failed(
        "platform_memory_total",
        "the platform's memory query",
        None,
        "total memory could not be read",
    ))
}

fn bi_platform_memory_free(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // Available memory in bytes, the same quantity on every OS (sysinfo).
    // This read MemAvailable on Linux but only the free-page list on macOS,
    // and assumed 4096-byte pages there -- Apple Silicon's are 16384, so it
    // reported a quarter of the free memory.
    let mut sys = System::new();
    sys.refresh_memory();
    Ok(Value::Int(sys.available_memory() as i64))
}

fn bi_platform_disks(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut disks = Vec::new();

    // This was `Get-CimInstance Win32_LogicalDisk` through PowerShell. It now
    // reads the same volumes from kernel32. WMI listed every logical disk
    // with a root, CD-ROM, network, removable and RAM-disk ones included, so
    // this lists every volume GetDriveTypeW gives a root to. Each field WMI
    // left empty for a drive is left out when its call fails: `size_*` and
    // `free_*` when GetDiskFreeSpaceExW fails, `filesystem` when
    // GetVolumeInformationW fails or the name is empty, and `label` when
    // GetVolumeInformationW fails. An unlabeled volume keeps `label` as "",
    // which is what WMI reported.
    #[cfg(target_os = "windows")]
    {
        for v in windows_volumes("platform_disks")? {
            let mut disk = std::collections::BTreeMap::new();
            disk.insert("mount".to_string(), Value::Str(format!("{}:", v.letter)));
            if let Some(size) = v.total {
                disk.insert("size_bytes".to_string(), Value::Int(size as i64));
                disk.insert(
                    "size_gb".to_string(),
                    Value::Float(size as f64 / 1024.0 / 1024.0 / 1024.0),
                );
            }
            if let Some(free) = v.free {
                disk.insert("free_bytes".to_string(), Value::Int(free as i64));
                disk.insert(
                    "free_gb".to_string(),
                    Value::Float(free as f64 / 1024.0 / 1024.0 / 1024.0),
                );
            }
            if let Some(fs) = v.fs_name.filter(|s| !s.is_empty()) {
                disk.insert("filesystem".to_string(), Value::Str(fs));
            }
            if let Some(label) = v.label {
                disk.insert("label".to_string(), Value::Str(label));
            }
            disks.push(Value::Record(disk));
        }
    }

    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("df");
        cmd.args(["-B1", "--output=source,target,fstype,size,avail"]);
        // A failed df used to list no disks. Its exit status is checked now.
        let output = probe_text("platform_disks", "df", cmd)?;
        for line in output.lines().skip(1) {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 5
                && !parts[0].starts_with("tmpfs")
                && !parts[0].starts_with("devtmpfs")
            {
                let mut disk = std::collections::BTreeMap::new();
                disk.insert("device".to_string(), Value::Str(parts[0].to_string()));
                disk.insert("mount".to_string(), Value::Str(parts[1].to_string()));
                disk.insert("filesystem".to_string(), Value::Str(parts[2].to_string()));
                if let Ok(n) = parts[3].parse::<i64>() {
                    disk.insert("size_bytes".to_string(), Value::Int(n));
                    disk.insert(
                        "size_gb".to_string(),
                        Value::Float(n as f64 / 1024.0 / 1024.0 / 1024.0),
                    );
                }
                if let Ok(n) = parts[4].parse::<i64>() {
                    disk.insert("free_bytes".to_string(), Value::Int(n));
                    disk.insert(
                        "free_gb".to_string(),
                        Value::Float(n as f64 / 1024.0 / 1024.0 / 1024.0),
                    );
                }
                disks.push(Value::Record(disk));
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        let mut cmd = crate::safety::child_command("df");
        cmd.args(["-b"]);
        // A failed df used to list no disks. Its exit status is checked now.
        let output = probe_text("platform_disks", "df", cmd)?;
        for line in output.lines().skip(1) {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 9 && parts[0].starts_with("/dev/") {
                let mut disk = std::collections::BTreeMap::new();
                disk.insert("device".to_string(), Value::Str(parts[0].to_string()));
                disk.insert("mount".to_string(), Value::Str(parts[8].to_string()));
                if let Ok(n) = parts[1].parse::<i64>() {
                    let bytes = n * 512;
                    disk.insert("size_bytes".to_string(), Value::Int(bytes));
                    disk.insert(
                        "size_gb".to_string(),
                        Value::Float(bytes as f64 / 1024.0 / 1024.0 / 1024.0),
                    );
                }
                if let Ok(n) = parts[3].parse::<i64>() {
                    let bytes = n * 512;
                    disk.insert("free_bytes".to_string(), Value::Int(bytes));
                    disk.insert(
                        "free_gb".to_string(),
                        Value::Float(bytes as f64 / 1024.0 / 1024.0 / 1024.0),
                    );
                }
                disks.push(Value::Record(disk));
            }
        }
    }

    Ok(Value::Array(disks))
}

fn bi_platform_disk_usage(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // In-process, from the disk that holds `path`. This ran `df -B1`, which
    // BSD df does not accept, so on macOS it always answered null; on
    // Windows it ignored any path without a drive letter and answered {} for
    // a drive that did not exist.
    let path = args.first().and_then(|v| v.as_str().ok()).unwrap_or(".");
    let resolved = std::fs::canonicalize(path)
        .map_err(|e| crate::safety::fs_error("platform_disk_usage", path, &e))?;
    // Windows canonical paths carry the verbatim prefix, backslash backslash
    // question-mark backslash, which no mount point such as C: is a prefix
    // of. Spelled with escapes, not a raw string, and described in words
    // here: the source scanners in tests/ do not skip comments, and a quote
    // after a backslash reads to them as an escaped quote that never closes.
    let resolved = match resolved.to_str().and_then(|s| s.strip_prefix("\\\\?\\")) {
        Some(rest) if !rest.starts_with("UNC") => std::path::PathBuf::from(rest),
        _ => resolved,
    };
    let disks = Disks::new_with_refreshed_list();
    let disk = disks
        .iter()
        .filter(|d| resolved.starts_with(d.mount_point()))
        .max_by_key(|d| d.mount_point().as_os_str().len())
        .ok_or_else(|| {
            crate::safety::bad_state_with_hint(
                "platform_disk_usage",
                &format!("no mounted disk contains {}", resolved.display()),
                "pass a path on a mounted filesystem",
            )
        })?;
    let total = disk.total_space() as i64;
    let free = disk.available_space() as i64;
    let used = total - free;
    let mut info = BTreeMap::new();
    info.insert(
        "mount_point".to_string(),
        Value::Str(disk.mount_point().to_string_lossy().to_string()),
    );
    info.insert("total_bytes".to_string(), Value::Int(total));
    info.insert("free_bytes".to_string(), Value::Int(free));
    info.insert("used_bytes".to_string(), Value::Int(used));
    info.insert(
        "usage_percent".to_string(),
        Value::Float(if total > 0 {
            used as f64 / total as f64 * 100.0
        } else {
            0.0
        }),
    );
    Ok(Value::Record(info))
}

/// The AMD GPUs in `rocm-smi` text, one record per `GPU[n]` index, with the
/// keys the NVIDIA rows use: vendor, index, name, memory_mb, memory_free_mb,
/// driver, temperature_c, utilization_percent. rocm-smi prints one
/// `GPU[n] : label: value` line per field. A field it does not print is Null
/// (driver is never printed under these flags). Lines that are not GPU fields
/// are skipped.
#[cfg(target_os = "linux")]
fn rocm_smi_records(text: &str) -> Vec<Value> {
    let mut by_index: BTreeMap<i64, BTreeMap<String, String>> = BTreeMap::new();
    for line in text.lines() {
        let Some(rest) = line.trim().strip_prefix("GPU[") else {
            continue;
        };
        let Some((idx, field)) = rest.split_once(']') else {
            continue;
        };
        let Ok(index) = idx.trim().parse::<i64>() else {
            continue;
        };
        let field = field.trim().trim_start_matches(':').trim();
        let Some((label, value)) = field.split_once(':') else {
            continue;
        };
        by_index
            .entry(index)
            .or_default()
            .insert(label.trim().to_string(), value.trim().to_string());
    }
    by_index
        .into_iter()
        .map(|(index, fields)| {
            let int = |label: &str| fields.get(label).and_then(|v| v.parse::<i64>().ok());
            let float = |label: &str| {
                fields
                    .get(label)
                    .and_then(|v| v.parse::<f64>().ok())
                    .map(|f| Value::Int(f.round() as i64))
                    .unwrap_or(Value::Null)
            };
            let total_bytes = int("VRAM Total Memory (B)");
            let used_bytes = int("VRAM Total Used Memory (B)");
            let name = fields
                .get("Card series")
                .filter(|v| !v.is_empty())
                .cloned()
                .map(Value::Str)
                .unwrap_or(Value::Null);
            let memory_free_mb = match (total_bytes, used_bytes) {
                (Some(total), Some(used)) => Value::Int((total - used) / 1024 / 1024),
                _ => Value::Null,
            };
            let mut gpu = BTreeMap::new();
            gpu.insert("vendor".to_string(), Value::Str("AMD".to_string()));
            gpu.insert("index".to_string(), Value::Int(index));
            gpu.insert("name".to_string(), name);
            gpu.insert(
                "memory_mb".to_string(),
                total_bytes
                    .map(|b| Value::Int(b / 1024 / 1024))
                    .unwrap_or(Value::Null),
            );
            gpu.insert("memory_free_mb".to_string(), memory_free_mb);
            gpu.insert("driver".to_string(), Value::Null);
            gpu.insert(
                "temperature_c".to_string(),
                float("Temperature (Sensor edge) (C)"),
            );
            gpu.insert("utilization_percent".to_string(), float("GPU use (%)"));
            Value::Record(gpu)
        })
        .collect()
}

fn bi_platform_gpus(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut gpus = Vec::new();

    // NVIDIA GPUs via nvidia-smi. Not installed means no NVIDIA GPUs. Installed
    // but failing is an error: it used to read as none. A row with too few
    // columns is also an error. A single field that is not a number (nvidia-smi
    // prints [N/A] for some) stays absent, as before.
    let mut cmd = crate::safety::child_command("nvidia-smi");
    cmd.args(["--query-gpu=index,name,memory.total,memory.free,driver_version,temperature.gpu,utilization.gpu", "--format=csv,noheader,nounits"]);
    match bounded_cmd_output("platform_gpus", "nvidia-smi", cmd, PROBE_DEADLINE_SECS) {
        Ok(out) => {
            let output = probe_stdout("platform_gpus", "nvidia-smi", out)?;
            for line in output.lines() {
                let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
                if parts.len() < 7 {
                    return Err(crate::safety::bad_state_with_hint(
                        "platform_gpus",
                        &format!(
                            "nvidia-smi row has {} columns, expected 7: {line}",
                            parts.len()
                        ),
                        "the csv query nvidia-smi was asked for",
                    ));
                }
                let mut gpu = std::collections::BTreeMap::new();
                gpu.insert("vendor".to_string(), Value::Str("NVIDIA".to_string()));
                if let Ok(idx) = parts[0].parse::<i64>() {
                    gpu.insert("index".to_string(), Value::Int(idx));
                }
                gpu.insert("name".to_string(), Value::Str(parts[1].to_string()));
                if let Ok(mem) = parts[2].parse::<i64>() {
                    gpu.insert("memory_mb".to_string(), Value::Int(mem));
                }
                if let Ok(free) = parts[3].parse::<i64>() {
                    gpu.insert("memory_free_mb".to_string(), Value::Int(free));
                }
                gpu.insert("driver".to_string(), Value::Str(parts[4].to_string()));
                if let Ok(temp) = parts[5].parse::<i64>() {
                    gpu.insert("temperature_c".to_string(), Value::Int(temp));
                }
                if let Ok(util) = parts[6].parse::<i64>() {
                    gpu.insert("utilization_percent".to_string(), Value::Int(util));
                }
                gpus.push(Value::Record(gpu));
            }
        }
        Err(e) if is_tool_missing(&e) => {}
        Err(e) => return Err(e),
    }

    // AMD GPUs via rocm-smi (Linux), in the same record shape as the NVIDIA rows.
    #[cfg(target_os = "linux")]
    if gpus.is_empty() {
        let mut cmd = crate::safety::child_command("rocm-smi");
        cmd.args([
            "--showproductname",
            "--showmeminfo",
            "vram",
            "--showtemp",
            "--showuse",
        ]);
        if let Ok(out) = bounded_cmd_output("platform_gpus", "rocm-smi", cmd, PROBE_DEADLINE_SECS) {
            if out.status.success() {
                let output = String::from_utf8_lossy(&out.stdout);
                gpus.extend(rocm_smi_records(&output));
            }
        }
    }

    // Fallback: Windows. wmic is absent on current Windows 11, so this uses the
    // same CIM plus registry probe as hw_gpu. The 64-bit driver size is reported.
    #[cfg(target_os = "windows")]
    if gpus.is_empty() {
        if let Ok(Some(adapters)) = win_gpu_probe("platform_gpus") {
            for g in adapters {
                let mut rec = std::collections::BTreeMap::new();
                if let Some(name) = g.name {
                    rec.insert("name".to_string(), Value::Str(name));
                }
                if let Some(bytes) = g.vram_bytes {
                    rec.insert("memory_bytes".to_string(), Value::Int(bytes));
                    rec.insert("memory_mb".to_string(), Value::Int(bytes / 1024 / 1024));
                }
                if let Some(driver) = g.driver {
                    rec.insert("driver".to_string(), Value::Str(driver));
                }
                gpus.push(Value::Record(rec));
            }
        }
    }

    Ok(Value::Array(gpus))
}

/// Sums the rows nvidia-smi prints for `--query-gpu=memory.total,memory.used,memory.free
/// --format=csv,noheader,nounits` (one row per GPU) into `{total_mb, used_mb, free_mb,
/// devices}`. A row that is not three numbers is refused, not skipped: skipping it would
/// total fewer GPUs than the host has. No rows is refused too.
fn gpu_memory_record(output: &str) -> Result<Value> {
    let mut totals = [0i64; 3];
    let mut devices = 0i64;
    for line in output.lines().map(str::trim).filter(|l| !l.is_empty()) {
        let parts: Vec<&str> = line.split(',').map(str::trim).collect();
        if parts.len() != 3 {
            return Err(crate::safety::bad_state_with_hint(
                "platform_gpu_memory",
                &format!("nvidia-smi memory row is not total,used,free: {line:?}"),
                "the csv query nvidia-smi was asked for",
            ));
        }
        for (i, text) in parts.iter().enumerate() {
            let value = text.parse::<i64>().map_err(|e| {
                crate::safety::bad_state_with_hint(
                    "platform_gpu_memory",
                    &format!("nvidia-smi memory field {i} is not a number: {e}"),
                    "the csv query nvidia-smi was asked for",
                )
            })?;
            totals[i] = totals[i].saturating_add(value);
        }
        devices += 1;
    }
    if devices == 0 {
        return Err(crate::safety::bad_state_with_hint(
            "platform_gpu_memory",
            "nvidia-smi printed no memory rows",
            "the csv query nvidia-smi was asked for",
        ));
    }
    let mut info = BTreeMap::new();
    info.insert("total_mb".to_string(), Value::Int(totals[0]));
    info.insert("used_mb".to_string(), Value::Int(totals[1]));
    info.insert("free_mb".to_string(), Value::Int(totals[2]));
    info.insert("devices".to_string(), Value::Int(devices));
    Ok(Value::Record(info))
}

fn bi_platform_gpu_memory(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("nvidia-smi");
    cmd.args([
        "--query-gpu=memory.total,memory.used,memory.free",
        "--format=csv,noheader,nounits",
    ]);
    // Not installed is no figures (Null). Installed but failing, or output that
    // does not hold three numbers, is an error. Both used to read as Null.
    let out = match bounded_cmd_output(
        "platform_gpu_memory",
        "nvidia-smi",
        cmd,
        PROBE_DEADLINE_SECS,
    ) {
        Ok(out) => out,
        Err(e) if is_tool_missing(&e) => return Ok(Value::Null),
        Err(e) => return Err(e),
    };
    let output = probe_stdout("platform_gpu_memory", "nvidia-smi", out)?;
    gpu_memory_record(&output)
}

fn bi_platform_network_interfaces(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut interfaces = Vec::new();

    #[cfg(target_os = "windows")]
    {
        // The adapter table, in process. This was `wmic nic`, which Windows
        // 11 no longer ships; without it the answer was one record holding
        // ipconfig's raw text instead of a list of interfaces. The records
        // have the Linux branch's fields: name, state, mac and addresses.
        for adapter in windows_adapters("platform_network_interfaces")? {
            let mut nic = std::collections::BTreeMap::new();
            nic.insert("name".to_string(), Value::Str(adapter.name));
            nic.insert(
                "state".to_string(),
                Value::Str(if adapter.up { "UP" } else { "DOWN" }.to_string()),
            );
            if let Some(mac) = adapter.mac {
                nic.insert("mac".to_string(), Value::Str(mac));
            }
            let ips: Vec<Value> = adapter
                .addresses
                .iter()
                .map(|ip| Value::Str(ip.to_string()))
                .collect();
            if !ips.is_empty() {
                nic.insert("addresses".to_string(), Value::Array(ips));
            }
            interfaces.push(Value::Record(nic));
        }
    }

    #[cfg(target_os = "linux")]
    {
        let mut cmd = crate::safety::child_command("ip");
        cmd.args(["--json", "addr"]);
        if let Ok(out) = bounded_cmd_output(
            "platform_network_interfaces",
            "ip",
            cmd,
            PROBE_DEADLINE_SECS,
        ) {
            if out.status.success() {
                if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&out.stdout) {
                    if let Some(arr) = json.as_array() {
                        for iface in arr {
                            let mut nic = std::collections::BTreeMap::new();
                            if let Some(name) = iface.get("ifname").and_then(|v| v.as_str()) {
                                nic.insert("name".to_string(), Value::Str(name.to_string()));
                            }
                            if let Some(state) = iface.get("operstate").and_then(|v| v.as_str()) {
                                nic.insert("state".to_string(), Value::Str(state.to_string()));
                            }
                            if let Some(mac) = iface.get("address").and_then(|v| v.as_str()) {
                                nic.insert("mac".to_string(), Value::Str(mac.to_string()));
                            }
                            if let Some(addrs) = iface.get("addr_info").and_then(|v| v.as_array()) {
                                let ips: Vec<Value> = addrs
                                    .iter()
                                    .filter_map(|a| a.get("local").and_then(|v| v.as_str()))
                                    .map(|s| Value::Str(s.to_string()))
                                    .collect();
                                if !ips.is_empty() {
                                    nic.insert("addresses".to_string(), Value::Array(ips));
                                }
                            }
                            interfaces.push(Value::Record(nic));
                        }
                    }
                }
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        let cmd = crate::safety::child_command("ifconfig");
        if let Ok(out) = bounded_cmd_output(
            "platform_network_interfaces",
            "ifconfig",
            cmd,
            PROBE_DEADLINE_SECS,
        ) {
            let output = String::from_utf8_lossy(&out.stdout);
            let mut current_name = String::new();
            let mut current = std::collections::BTreeMap::new();

            for line in output.lines() {
                if !line.starts_with('\t') && !line.starts_with(' ') && line.contains(':') {
                    if !current_name.is_empty() && !current.is_empty() {
                        current.insert("name".to_string(), Value::Str(current_name.clone()));
                        interfaces.push(Value::Record(current.clone()));
                    }
                    current.clear();
                    current_name = line.split(':').next().unwrap_or("").to_string();
                } else if line.contains("ether ") {
                    let mac = line
                        .split("ether ")
                        .nth(1)
                        .unwrap_or("")
                        .split_whitespace()
                        .next()
                        .unwrap_or("");
                    current.insert("mac".to_string(), Value::Str(mac.to_string()));
                } else if line.contains("inet ") && !line.contains("inet6") {
                    let ip = line
                        .split("inet ")
                        .nth(1)
                        .unwrap_or("")
                        .split_whitespace()
                        .next()
                        .unwrap_or("");
                    current.insert("ipv4".to_string(), Value::Str(ip.to_string()));
                }
            }
            if !current_name.is_empty() && !current.is_empty() {
                current.insert("name".to_string(), Value::Str(current_name));
                interfaces.push(Value::Record(current));
            }
        }
    }

    Ok(Value::Array(interfaces))
}

fn bi_platform_hardware_summary(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    platform_refuse_input("platform_hardware_summary", &input)?;
    let mut summary = std::collections::BTreeMap::new();
    let mut unavailable = Vec::new();

    // A section that cannot be read is listed under `unavailable` with its
    // coded reason. It used to be dropped, so the summary looked complete.
    let sections: [(&str, Result<Value>); 5] = [
        ("cpu", bi_platform_cpu(vec![], None)),
        ("memory", bi_platform_memory(vec![], None)),
        ("disks", bi_platform_disks(vec![], None)),
        ("gpus", bi_platform_gpus(vec![], None)),
        ("network", bi_platform_network_interfaces(vec![], None)),
    ];
    for (name, result) in sections {
        match result {
            // An empty list of GPUs or interfaces is an answer, not a section to show.
            Ok(Value::Array(items)) if items.is_empty() && matches!(name, "gpus" | "network") => {}
            Ok(value) => {
                summary.insert(name.to_string(), value);
            }
            Err(e) => unavailable.push(Value::Str(format!("{name}: {e}"))),
        }
    }
    if !unavailable.is_empty() {
        summary.insert("unavailable".to_string(), Value::Array(unavailable));
    }

    // Add architecture and OS
    summary.insert(
        "arch".to_string(),
        Value::Str(std::env::consts::ARCH.to_string()),
    );
    summary.insert(
        "os".to_string(),
        Value::Str(std::env::consts::OS.to_string()),
    );

    Ok(Value::Record(summary))
}

// ============================================================================
// Container Management Builtins (816-849)
// Docker, Podman, and runtime-agnostic container operations
// ============================================================================

// ---------------------------------------------------------------------------
// Helper: run a container CLI command and parse JSON-per-line output
// ---------------------------------------------------------------------------
// Every container builtin runs its tool with an argv and never through a shell.
// Stdout is capped at CONTAINER_OUTPUT_MAX bytes: an answer that does not fit
// is a budget error, never a truncated value. Stderr is kept as a short tail for
// the failure message, or appended to the answer when `with_stderr` is set,
// because build, pull, push and compose write their progress there and `logs`
// carries the container's own stderr there.
// ---------------------------------------------------------------------------
const CONTAINER_OUTPUT_MAX: usize = 4 * 1024 * 1024;
const CONTAINER_STDERR_TAIL: usize = 4 * 1024;
const CONTAINER_LOG_TAIL_DEFAULT: i64 = 1000;
const CONTAINER_LOG_TAIL_MAX: i64 = 10_000;
const CONTAINER_ARGV_MAX: usize = 256;
/// Deadline for one container CLI call; past it the call's tree is killed.
const CONTAINER_DEADLINE_SECS: u64 = 300;

/// A coded `E_TOOL_FAILED` for a container tool whose output cannot be read.
fn container_error(builtin: &str, message: String, hint: &str, got: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::ToolFailed,
        message: format!("{builtin}: {message}"),
        builtin: builtin.to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: got.to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Run `program` with `args` as an argv, never through a shell, and return its
/// stdout (followed by its stderr when `with_stderr` is set). A nonzero exit is
/// `E_TOOL_FAILED` carrying the stderr tail; a missing program is
/// `E_TOOL_MISSING`; output over the bound is `E_BUDGET_EXCEEDED`.
fn container_cli(builtin: &str, program: &str, args: &[&str], with_stderr: bool) -> Result<String> {
    container_cli_within(builtin, program, args, with_stderr, CONTAINER_DEADLINE_SECS)
}

/// [`container_cli`] with its deadline given, so a test can run a silent child
/// past a short one. The call's tree is killed at `deadline_secs`.
fn container_cli_within(
    builtin: &str,
    program: &str,
    args: &[&str],
    with_stderr: bool,
    deadline_secs: u64,
) -> Result<String> {
    let verb = args.first().copied().unwrap_or("");
    let command = format!("{program} {verb}");
    let stderr_keep = if with_stderr {
        Keep::Head(CONTAINER_OUTPUT_MAX)
    } else {
        Keep::Tail(CONTAINER_STDERR_TAIL)
    };
    let run = run_tree(
        program,
        args,
        |_| {},
        None,
        std::time::Duration::from_secs(deadline_secs),
        Keep::Head(CONTAINER_OUTPUT_MAX),
        stderr_keep,
    )
    .map_err(|e| match e {
        TreeError::Spawn(e) => crate::safety::spawn_error(builtin, program, &e),
        TreeError::Wait(e) => container_error(
            builtin,
            format!("could not wait for `{command}`: {e}"),
            "retry the call",
            "no exit status",
        ),
    })?;
    if run.timed_out {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{command}` did not finish within {deadline_secs} s"),
            "the call was killed and its result discarded; check the state with the matching read builtin before retrying",
        ));
    }
    // A stderr tail is kept short on purpose; only a stream returned whole
    // (stdout, or stderr when it is appended) can be over budget.
    if run.stdout_truncated || (with_stderr && run.stderr_truncated) {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{command}` wrote more than {CONTAINER_OUTPUT_MAX} bytes"),
            "ask for less output: a smaller tail, or one container at a time",
        ));
    }
    if !run.success {
        let stderr = &run.stderr;
        let tail = &stderr[stderr.len().saturating_sub(CONTAINER_STDERR_TAIL)..];
        return Err(crate::safety::tool_failed(
            builtin,
            &command,
            run.code,
            &String::from_utf8_lossy(tail),
        ));
    }
    let stdout = run.stdout;
    let stderr = run.stderr;
    let mut text = String::from_utf8_lossy(&stdout).into_owned();
    if with_stderr && !stderr.is_empty() {
        if !text.is_empty() && !text.ends_with('\n') {
            text.push('\n');
        }
        text.push_str(&String::from_utf8_lossy(&stderr));
    }
    Ok(text)
}

/// Parse a container CLI's listing: a JSON array, or one JSON object per line.
/// A line that does not parse is an error, never a dropped row.
fn container_rows(builtin: &str, tool: &str, text: &str) -> Result<Vec<Value>> {
    let trimmed = text.trim();
    let unparsed = || {
        container_error(
            builtin,
            format!("the output of `{tool}` is not in a form this builtin reads"),
            "the tool ran but printed output this builtin does not parse; check its version",
            "unreadable output",
        )
    };
    if trimmed.starts_with('[') {
        let json: serde_json::Value = serde_json::from_str(trimmed).map_err(|_| unparsed())?;
        return Ok(match json_to_value(json) {
            Value::Array(rows) => rows,
            other => vec![other],
        });
    }
    let mut rows = Vec::new();
    for line in trimmed.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let json: serde_json::Value = serde_json::from_str(line).map_err(|_| unparsed())?;
        rows.push(json_to_value(json));
    }
    Ok(rows)
}

// Helper: run a container CLI command and parse JSON-per-line output
fn container_json_lines(program: &str, args: &[&str]) -> Result<Vec<Value>> {
    let text = container_cli(program, program, args, false)?;
    container_rows(program, program, &text)
}

// Helper: run a container CLI command and return stdout as a string
fn container_run_cmd(program: &str, args: &[&str]) -> Result<String> {
    container_cli(program, program, args, false)
}

// ---------------------------------------------------------------------------
// Argument checks shared by the docker_* and podman_* builtins
// ---------------------------------------------------------------------------

fn refuse_pipeline(builtin: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::arg_err(format!(
            "{builtin} takes no piped input; pass its arguments directly"
        )));
    }
    Ok(())
}

/// A container, image, tag or path operand: non-empty, free of control
/// characters, and never option-like. The CLI would read a leading '-' as a
/// flag, and `--` is placed before operands as well, so this is the second
/// guard, not the only one.
fn container_operand(builtin: &str, what: &str, value: &str) -> Result<()> {
    if value.is_empty() {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: a non-empty String"),
            "an empty string",
        ));
    }
    if value.chars().any(char::is_control) {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: a String without control characters"),
            "a control character",
        ));
    }
    crate::safety::reject_option_like(builtin, &[value.to_string()])
}

fn str_operand<'a>(builtin: &str, what: &str, value: Option<&'a Value>) -> Result<&'a str> {
    match value {
        Some(Value::Str(s)) => Ok(s.as_str()),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: String"),
            other.type_name(),
        )),
        None => Err(crate::safety::arg_err(format!(
            "{builtin} requires {what} as its first argument"
        ))),
    }
}

fn optional_bool(builtin: &str, what: &str, value: Option<&Value>) -> Result<bool> {
    match value {
        None => Ok(false),
        Some(Value::Bool(b)) => Ok(*b),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: Bool"),
            other.type_name(),
        )),
    }
}

/// An argv: an Array of Strings. A shell command line is refused, because it
/// would have to be split and interpreted; each element is one argument.
fn argv_arg(
    builtin: &str,
    what: &str,
    value: Option<&Value>,
    required: bool,
) -> Result<Vec<String>> {
    let items = match value {
        None if required => {
            return Err(crate::safety::bad_arg(
                builtin,
                &format!("{what}: an Array of String (argv, not a shell string)"),
                "nothing",
            ))
        }
        None => return Ok(Vec::new()),
        Some(Value::Array(items)) => items,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                &format!("{what}: an Array of String (argv, not a shell string)"),
                other.type_name(),
            ))
        }
    };
    if required && items.is_empty() {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: at least one element"),
            "an empty array",
        ));
    }
    if items.len() > CONTAINER_ARGV_MAX {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!(
                "{what} has {} elements; the limit is {CONTAINER_ARGV_MAX}",
                items.len()
            ),
            "pass fewer arguments",
        ));
    }
    items
        .iter()
        .map(|item| match item {
            Value::Str(s) if s.contains('\0') => Err(crate::safety::bad_arg(
                builtin,
                &format!("{what}: Strings without NUL bytes"),
                "a NUL byte",
            )),
            Value::Str(s) => Ok(s.clone()),
            other => Err(crate::safety::bad_arg(
                builtin,
                &format!("{what}: an Array of String"),
                other.type_name(),
            )),
        })
        .collect()
}

/// `docker run` flags from a Record. A flag name is lowercase letters, digits
/// and hyphens, so it cannot smuggle a second option. A string value is passed
/// as `--flag=value`, a single token the CLI cannot read as anything else; the
/// few short flags take their value as the next token, which is option-checked.
/// Any value of another type is refused, not ignored.
fn container_run_flags(builtin: &str, flags: &BTreeMap<String, Value>) -> Result<Vec<String>> {
    let mut argv = Vec::new();
    for (key, value) in flags {
        let well_formed = key.len() <= 64
            && key.starts_with(|c: char| c.is_ascii_lowercase())
            && key
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
        if !well_formed {
            return Err(crate::safety::bad_arg(
                builtin,
                "flag names of lowercase letters, digits and '-', starting with a letter",
                key,
            ));
        }
        match (key.as_str(), value) {
            (_, Value::Bool(false)) => {}
            ("detach", Value::Bool(true)) => argv.push("-d".to_string()),
            ("rm", Value::Bool(true)) => argv.push("--rm".to_string()),
            ("name" | "port" | "env" | "volume", Value::Str(s)) => {
                container_operand(builtin, key, s)?;
                let short = match key.as_str() {
                    "name" => "--name",
                    "port" => "-p",
                    "env" => "-e",
                    _ => "-v",
                };
                argv.push(short.to_string());
                argv.push(s.clone());
            }
            (_, Value::Bool(true)) => argv.push(format!("--{key}")),
            (_, Value::Str(s)) => argv.push(format!("--{key}={s}")),
            (_, Value::Int(n)) => argv.push(format!("--{key}={n}")),
            (_, other) => {
                return Err(crate::safety::bad_arg(
                    builtin,
                    &format!("flag {key}: Bool, String or Int"),
                    other.type_name(),
                ))
            }
        }
    }
    Ok(argv)
}

/// A local path the builtin will read: refused if option-like, then resolved
/// against the workspace and guarded as a read, the same as `bat`.
fn guard_local_read(builtin: &str, path: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[path.to_string()])?;
    let path = crate::safety::resolve_path_str(path);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin,
        effect: crate::safety::Effect::ReadLocal,
        what: "read",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({ "path": path }),
        reversible: true,
        fs_paths: true,
    })?;
    Ok(path)
}

/// An optional compose file: validated, then read-guarded and resolved.
fn compose_file_arg(builtin: &str, value: Option<&Value>) -> Result<Option<String>> {
    match value {
        None => Ok(None),
        Some(Value::Str(file)) => {
            container_operand(builtin, "compose file", file)?;
            Ok(Some(guard_local_read(builtin, file)?))
        }
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            "compose file: String",
            other.type_name(),
        )),
    }
}

// ---------------------------------------------------------------------------
// Generic container operations, parameterised by the CLI (docker or podman)
// ---------------------------------------------------------------------------

fn container_run(
    program: &str,
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let image = str_operand(builtin, "image", args.first())?;
    container_operand(builtin, "image", image)?;
    // `run` pulls the image when it is not present, from the registry the
    // reference names (see `image_registry`), so that registry is judged here.
    // A daemon or registries.conf mirror is judged by check_container_mirror_egress.
    crate::safety::check_egress(builtin, &[format!("https://{}", image_registry(image))])?;
    crate::safety::check_container_mirror_egress(builtin)?;
    let argv = argv_arg(builtin, "command", args.get(1), false)?;
    let flags = match args.get(2) {
        None => Vec::new(),
        Some(Value::Record(record)) => container_run_flags(builtin, record)?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "flags: Record",
                other.type_name(),
            ))
        }
    };
    // Flags, then `--`, then the image and its argv: nothing after `--` is read
    // as an option, so an argv element beginning with '-' reaches the container.
    let mut cmd: Vec<&str> = vec!["run"];
    cmd.extend(flags.iter().map(String::as_str));
    cmd.push("--");
    cmd.push(image);
    cmd.extend(argv.iter().map(String::as_str));
    let text = container_cli(builtin, program, &cmd, false)?;
    Ok(Value::Str(text.trim().to_string()))
}

/// The container and argv of an exec call, checked. The caller runs the
/// policy guard and then `exec_run`.
fn exec_request(
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<(String, Vec<String>)> {
    refuse_pipeline(builtin, input)?;
    let container = str_operand(builtin, "container", args.first())?;
    container_operand(builtin, "container", container)?;
    let argv = argv_arg(builtin, "command", args.get(1), true)?;
    Ok((container.to_string(), argv))
}

fn exec_run(program: &str, builtin: &str, container: &str, argv: &[String]) -> Result<Value> {
    let mut cmd: Vec<&str> = vec!["exec", "--", container];
    cmd.extend(argv.iter().map(String::as_str));
    let text = container_cli(builtin, program, &cmd, false)?;
    Ok(Value::Str(text.trim().to_string()))
}

fn container_logs(
    program: &str,
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let container = str_operand(builtin, "container", args.first())?;
    container_operand(builtin, "container", container)?;
    // The tail is bounded so a long-lived container cannot fill the answer.
    let tail = match args.get(1) {
        None => CONTAINER_LOG_TAIL_DEFAULT,
        Some(Value::Int(n)) if (1..=CONTAINER_LOG_TAIL_MAX).contains(n) => *n,
        Some(Value::Int(n)) => {
            return Err(crate::safety::bad_arg(
                builtin,
                &format!("tail: Int in 1..={CONTAINER_LOG_TAIL_MAX}"),
                &n.to_string(),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                &format!("tail: Int in 1..={CONTAINER_LOG_TAIL_MAX}"),
                other.type_name(),
            ))
        }
    };
    let tail = tail.to_string();
    let text = container_cli(
        builtin,
        program,
        &["logs", "--tail", tail.as_str(), "--", container],
        true,
    )?;
    Ok(Value::Str(text))
}

fn container_stop(
    program: &str,
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let container = str_operand(builtin, "container", args.first())?;
    container_operand(builtin, "container", container)?;
    container_cli(builtin, program, &["stop", "--", container], false)?;
    Ok(Value::Str(format!("Stopped container {container}")))
}

/// The container and force flag of a rm call, checked. Its policy guard, which
/// differs between the two CLIs, is the caller's.
fn rm_request(builtin: &str, args: &[Value], input: &Option<Value>) -> Result<(String, bool)> {
    refuse_pipeline(builtin, input)?;
    let container = str_operand(builtin, "container", args.first())?;
    container_operand(builtin, "container", container)?;
    let force = optional_bool(builtin, "force", args.get(1))?;
    Ok((container.to_string(), force))
}

fn rm_run(program: &str, builtin: &str, container: &str, force: bool) -> Result<Value> {
    let mut cmd = vec!["rm"];
    if force {
        cmd.push("-f");
    }
    cmd.push("--");
    cmd.push(container);
    container_cli(builtin, program, &cmd, false)?;
    Ok(Value::Str(format!("Removed container {container}")))
}

fn container_build(
    program: &str,
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let tag = str_operand(builtin, "tag", args.first())?;
    container_operand(builtin, "tag", tag)?;
    let path = match args.get(1) {
        None => ".",
        Some(Value::Str(p)) => {
            container_operand(builtin, "path", p)?;
            p.as_str()
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "path: String",
                other.type_name(),
            ))
        }
    };
    // A build pulls the base images its Dockerfile's FROM lines name, so the
    // registries are in the build context, not in the arguments.
    crate::safety::check_egress_unknown(
        builtin,
        "the base images are named in the build context's Dockerfile, not in the arguments",
    )?;
    // The build context is read, so it is resolved and guarded as a read.
    let context = guard_local_read(builtin, path)?;
    let text = container_cli(
        builtin,
        program,
        &["build", "-t", tag, "--", context.as_str()],
        true,
    )?;
    Ok(Value::Str(text))
}

/// The registry a container image reference names, by the rule the docker and
/// podman CLIs apply: the part before the first `/` is a registry when it holds a
/// `.` or a `:` or is `localhost`; otherwise the reference is on Docker Hub. A
/// digest (`@sha256:…`) is not part of the name. This names the registry the
/// reference asks for; a daemon configured with a mirror sends the request to the
/// mirror, which this does not see.
fn image_registry(image: &str) -> &str {
    let name = image.split('@').next().unwrap_or(image);
    match name.split_once('/') {
        Some((first, _)) if first.contains('.') || first.contains(':') || first == "localhost" => {
            first
        }
        _ => "docker.io",
    }
}

/// `pull` and `push`: one image, one CLI verb. Both report progress on stderr.
fn container_image_op(
    program: &str,
    builtin: &str,
    verb: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let image = str_operand(builtin, "image", args.first())?;
    container_operand(builtin, "image", image)?;
    // The registry is the one the reference names; see `image_registry`. A mirror
    // in the daemon or registries.conf is judged by check_container_mirror_egress.
    crate::safety::check_egress(builtin, &[format!("https://{}", image_registry(image))])?;
    crate::safety::check_container_mirror_egress(builtin)?;
    let text = container_cli(builtin, program, &[verb, "--", image], true)?;
    Ok(Value::Str(text))
}

fn container_tag(
    program: &str,
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let source = str_operand(builtin, "source image", args.first())?;
    container_operand(builtin, "source image", source)?;
    let target = str_operand(builtin, "target tag", args.get(1))?;
    container_operand(builtin, "target tag", target)?;
    container_cli(builtin, program, &["tag", "--", source, target], false)?;
    Ok(Value::Str(format!("Tagged {source} as {target}")))
}

fn container_inspect(
    program: &str,
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let name = str_operand(builtin, "container or image name", args.first())?;
    container_operand(builtin, "container or image name", name)?;
    let text = container_cli(builtin, program, &["inspect", "--", name], false)?;
    let json: serde_json::Value = serde_json::from_str(text.trim()).map_err(|_| {
        container_error(
            builtin,
            format!("the output of `{program} inspect` is not JSON"),
            "the tool ran but printed output this builtin does not parse; check its version",
            "unreadable output",
        )
    })?;
    Ok(json_to_value(json))
}

fn container_top(
    program: &str,
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let container = str_operand(builtin, "container", args.first())?;
    container_operand(builtin, "container", container)?;
    let text = container_cli(builtin, program, &["top", "--", container], false)?;
    // The first line is the header; each following line is one process.
    let mut lines = text.lines();
    let Some(header) = lines.next() else {
        return Ok(Value::Array(vec![]));
    };
    let headers: Vec<String> = header
        .split_whitespace()
        .map(|h| h.to_lowercase())
        .collect();
    let mut processes = Vec::new();
    for line in lines {
        let fields: Vec<&str> = line.split_whitespace().collect();
        if fields.is_empty() {
            continue;
        }
        let mut record = BTreeMap::new();
        for (i, header) in headers.iter().enumerate() {
            let val = fields.get(i).copied().unwrap_or("");
            record.insert(header.clone(), Value::Str(val.to_string()));
        }
        processes.push(Value::Record(record));
    }
    Ok(Value::Array(processes))
}

/// `docker cp` between the host and a container. Exactly one operand is
/// `container:path`; the other is a host path, guarded as a write when the
/// container's files are copied out to it and as a read when they are copied in.
fn container_cp(
    program: &str,
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let src = str_operand(builtin, "source path", args.first())?;
    let dest = str_operand(builtin, "destination path", args.get(1))?;
    let src_in_container = cp_is_container_operand(src);
    if src_in_container == cp_is_container_operand(dest) {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: exactly one of source and destination must be container:path; \
             the other is a host path"
        )));
    }
    let (container_side, host_side) = if src_in_container {
        (src, dest)
    } else {
        (dest, src)
    };
    let in_container = container_side.split_once(':').map_or("", |(_, p)| p);
    if in_container.is_empty() || in_container.chars().any(char::is_control) {
        return Err(crate::safety::bad_arg(
            builtin,
            "container:path with a non-empty path",
            container_side,
        ));
    }
    let (src_arg, dest_arg) = if src_in_container {
        (src.to_string(), guard_local_write(builtin, host_side)?)
    } else {
        (guard_local_read(builtin, host_side)?, dest.to_string())
    };
    container_cli(
        builtin,
        program,
        &["cp", "--", src_arg.as_str(), dest_arg.as_str()],
        false,
    )?;
    Ok(Value::Str(format!("Copied {src} -> {dest}")))
}

/// Whether a `docker cp` operand names a container. Like the CLI, the text
/// before the first colon is the name; a name cannot contain a separator and is
/// at least two characters, so `C:\x` and `./a:b` are host paths.
fn cp_is_container_operand(operand: &str) -> bool {
    let Some((name, _)) = operand.split_once(':') else {
        return false;
    };
    name.len() >= 2
        && name.starts_with(|c: char| c.is_ascii_alphanumeric())
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
}

fn compose_up(builtin: &str, args: &[Value], input: &Option<Value>) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    crate::safety::check_egress_unknown(
        builtin,
        "the images a compose file names are pulled, and the file is read from the project directory, not the arguments",
    )?;
    // Detached by default. A foreground `compose up` runs until it is stopped,
    // which no call can bound, so only `true` is accepted.
    let detach = match args.first() {
        None => true,
        Some(Value::Bool(b)) => *b,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                builtin,
                "detach: Bool",
                other.type_name(),
            ))
        }
    };
    if !detach {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: detach must be true; a foreground compose up runs until it is \
             stopped, which no call can bound"
        )));
    }
    let file = compose_file_arg(builtin, args.get(1))?;
    let mut cmd = vec!["compose"];
    if let Some(file) = file.as_deref() {
        cmd.extend(["-f", file]);
    }
    cmd.extend(["up", "-d"]);
    let text = container_cli(builtin, "docker", &cmd, true)?;
    Ok(Value::Str(text))
}

fn compose_down_run(file: Option<&str>) -> Result<Value> {
    let mut cmd = vec!["compose"];
    if let Some(file) = file {
        cmd.extend(["-f", file]);
    }
    cmd.push("down");
    let text = container_cli("docker_compose_down", "docker", &cmd, true)?;
    Ok(Value::Str(text))
}

fn compose_ps(builtin: &str, args: &[Value], input: &Option<Value>) -> Result<Value> {
    refuse_pipeline(builtin, input)?;
    let file = compose_file_arg(builtin, args.first())?;
    let mut cmd = vec!["compose"];
    if let Some(file) = file.as_deref() {
        cmd.extend(["-f", file]);
    }
    cmd.extend(["ps", "--format", "json"]);
    let text = container_cli(builtin, "docker", &cmd, false)?;
    Ok(Value::Array(container_rows(builtin, "docker", &text)?))
}

// ---------------------------------------------------------------------------
// 816: bi_docker_ps – List containers
// ---------------------------------------------------------------------------
fn bi_docker_ps(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let all = args
        .first()
        .map(|v| matches!(v, Value::Bool(true)))
        .unwrap_or(false);
    let mut cmd_args = vec!["ps", "--format", "{{json .}}"];
    if all {
        cmd_args.push("-a");
    }
    let containers = container_json_lines("docker", &cmd_args)?;
    Ok(Value::Array(containers))
}

// ---------------------------------------------------------------------------
// 817: bi_docker_images – List images
// ---------------------------------------------------------------------------
fn bi_docker_images(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let images = container_json_lines("docker", &["images", "--format", "{{json .}}"])?;
    Ok(Value::Array(images))
}

// ---------------------------------------------------------------------------
// 818: bi_docker_run – Run a container
// ---------------------------------------------------------------------------
fn bi_docker_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_run("docker", "docker_run", &args, &input)
}

// ---------------------------------------------------------------------------
// 819: bi_docker_exec – Execute an argv in a container
// ---------------------------------------------------------------------------
fn bi_docker_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (container, argv) = exec_request("docker_exec", &args, &input)?;
    crate::safety::guard_exec(
        "docker_exec",
        format!("docker exec {container} {}", argv.join(" ")),
    )?;
    exec_run("docker", "docker_exec", &container, &argv)
}

// ---------------------------------------------------------------------------
// 820: bi_docker_logs – Get container logs (bounded tail, stdout then stderr)
// ---------------------------------------------------------------------------
fn bi_docker_logs(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_logs("docker", "docker_logs", &args, &input)
}

// ---------------------------------------------------------------------------
// 821: bi_docker_stop – Stop a container
// ---------------------------------------------------------------------------
fn bi_docker_stop(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_stop("docker", "docker_stop", &args, &input)
}

// ---------------------------------------------------------------------------
// 822: bi_docker_rm – Remove a container
// ---------------------------------------------------------------------------
fn bi_docker_rm(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (container, force) = rm_request("docker_rm", &args, &input)?;
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "docker_rm",
        effect: crate::safety::Effect::Destructive,
        what: "container_remove",
        targets: vec![container.clone()],
        blast_radius: serde_json::json!({ "container": container, "force": force }),
        reversible: false,
        fs_paths: false,
    })?;
    rm_run("docker", "docker_rm", &container, force)
}

// ---------------------------------------------------------------------------
// 823: bi_docker_build – Build an image from a local context
// ---------------------------------------------------------------------------
fn bi_docker_build(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_build("docker", "docker_build", &args, &input)
}

// ---------------------------------------------------------------------------
// 824: bi_docker_pull – Pull an image
// ---------------------------------------------------------------------------
fn bi_docker_pull(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_image_op("docker", "docker_pull", "pull", &args, &input)
}

// ---------------------------------------------------------------------------
// 825: bi_docker_push – Push an image
// ---------------------------------------------------------------------------
fn bi_docker_push(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_image_op("docker", "docker_push", "push", &args, &input)
}

// ---------------------------------------------------------------------------
// 826: bi_docker_inspect – Inspect a container or image (JSON array)
// ---------------------------------------------------------------------------
fn bi_docker_inspect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_inspect("docker", "docker_inspect", &args, &input)
}

// ---------------------------------------------------------------------------
// 827: bi_docker_volumes – List volumes
// ---------------------------------------------------------------------------
fn bi_docker_volumes(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let volumes = container_json_lines("docker", &["volume", "ls", "--format", "{{json .}}"])?;
    Ok(Value::Array(volumes))
}

// ---------------------------------------------------------------------------
// 828: bi_docker_networks – List networks
// ---------------------------------------------------------------------------
fn bi_docker_networks(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let networks = container_json_lines("docker", &["network", "ls", "--format", "{{json .}}"])?;
    Ok(Value::Array(networks))
}

// ---------------------------------------------------------------------------
// 829: bi_docker_compose_up – Start a compose project detached
// ---------------------------------------------------------------------------
fn bi_docker_compose_up(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    compose_up("docker_compose_up", &args, &input)
}

// ---------------------------------------------------------------------------
// 830: bi_docker_compose_down – Stop and remove a compose project
// ---------------------------------------------------------------------------
fn bi_docker_compose_down(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_pipeline("docker_compose_down", &input)?;
    let file = compose_file_arg("docker_compose_down", args.first())?;
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "docker_compose_down",
        effect: crate::safety::Effect::Destructive,
        what: "compose_down",
        targets: vec![file
            .clone()
            .unwrap_or_else(|| "<default compose>".to_string())],
        blast_radius: serde_json::json!({}),
        reversible: false,
        fs_paths: false,
    })?;
    compose_down_run(file.as_deref())
}

// ---------------------------------------------------------------------------
// 831: bi_docker_compose_ps – List a compose project's containers
// ---------------------------------------------------------------------------
fn bi_docker_compose_ps(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    compose_ps("docker_compose_ps", &args, &input)
}

// ---------------------------------------------------------------------------
// 832: bi_docker_stats – Container stats (no-stream)
// ---------------------------------------------------------------------------
fn bi_docker_stats(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let stats = container_json_lines(
        "docker",
        &["stats", "--no-stream", "--format", "{{json .}}"],
    )?;
    Ok(Value::Array(stats))
}

// ---------------------------------------------------------------------------
// 833: bi_docker_top – Container processes, one record per process
// ---------------------------------------------------------------------------
fn bi_docker_top(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_top("docker", "docker_top", &args, &input)
}

// ---------------------------------------------------------------------------
// 834: bi_docker_cp – Copy files between the host and a container
// ---------------------------------------------------------------------------
fn bi_docker_cp(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_cp("docker", "docker_cp", &args, &input)
}

// ---------------------------------------------------------------------------
// 835: bi_docker_tag – Tag an image
// ---------------------------------------------------------------------------
fn bi_docker_tag(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_tag("docker", "docker_tag", &args, &input)
}

// ===========================================================================
// Podman Builtins (836-844) – the same operations through the "podman" CLI
// ===========================================================================

// ---------------------------------------------------------------------------
// 836: bi_podman_ps – List containers (podman)
// ---------------------------------------------------------------------------
fn bi_podman_ps(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "podman_ps";
    refuse_pipeline(B, &input)?;
    let all = optional_bool(B, "all", args.first())?;
    let mut cmd = vec!["ps", "--format", "json"];
    if all {
        cmd.push("-a");
    }
    let text = container_cli(B, "podman", &cmd, false)?;
    Ok(Value::Array(container_rows(B, "podman", &text)?))
}

// ---------------------------------------------------------------------------
// 837: bi_podman_images – List images (podman)
// ---------------------------------------------------------------------------
fn bi_podman_images(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "podman_images";
    refuse_pipeline(B, &input)?;
    let _ = args;
    let text = container_cli(B, "podman", &["images", "--format", "json"], false)?;
    Ok(Value::Array(container_rows(B, "podman", &text)?))
}

// ---------------------------------------------------------------------------
// 838: bi_podman_run – Run a container (podman)
// ---------------------------------------------------------------------------
fn bi_podman_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_run("podman", "podman_run", &args, &input)
}

// ---------------------------------------------------------------------------
// 839: bi_podman_exec – Execute an argv in a container (podman)
// ---------------------------------------------------------------------------
fn bi_podman_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let (container, argv) = exec_request("podman_exec", &args, &input)?;
    crate::safety::guard_exec(
        "podman_exec",
        format!("podman exec {container} {}", argv.join(" ")),
    )?;
    exec_run("podman", "podman_exec", &container, &argv)
}

// ---------------------------------------------------------------------------
// 840: bi_podman_logs – Get container logs (podman)
// ---------------------------------------------------------------------------
fn bi_podman_logs(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_logs("podman", "podman_logs", &args, &input)
}

// ---------------------------------------------------------------------------
// 841: bi_podman_stop – Stop a container (podman)
// ---------------------------------------------------------------------------
fn bi_podman_stop(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_stop("podman", "podman_stop", &args, &input)
}

// ---------------------------------------------------------------------------
// 842: bi_podman_rm – Remove a container (podman)
// ---------------------------------------------------------------------------
fn bi_podman_rm(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // podman_rm is Destructive and listed in SELF_GUARDED, so the dispatcher
    // leaves the policy check to this body, as it does for bi_docker_rm.
    let (container, force) = rm_request("podman_rm", &args, &input)?;
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "podman_rm",
        effect: crate::safety::Effect::Destructive,
        what: "container_remove",
        targets: vec![container.clone()],
        blast_radius: serde_json::json!({ "container": container, "force": force }),
        reversible: false,
        fs_paths: false,
    })?;
    rm_run("podman", "podman_rm", &container, force)
}

// ---------------------------------------------------------------------------
// 843: bi_podman_build – Build an image from a local context (podman)
// ---------------------------------------------------------------------------
fn bi_podman_build(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_build("podman", "podman_build", &args, &input)
}

// ---------------------------------------------------------------------------
// 844: bi_podman_pull – Pull an image (podman)
// ---------------------------------------------------------------------------
fn bi_podman_pull(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    container_image_op("podman", "podman_pull", "pull", &args, &input)
}

// ============================================================================
// Kubernetes & Helm Builtins (850-879)
// kubectl, helm operations with structured output
// ============================================================================

// ---------------------------------------------------------------------------
// kubectl runner shared by every k8s_* builtin.
//
// argv only, never a shell. A hard deadline ends a call that hangs (a rollout
// that never finishes, an API server that does not answer). Output is bounded:
// stdout is held up to `max_bytes` and refused beyond that, and stderr keeps
// only its tail. A nonzero exit is a coded E_TOOL_FAILED carrying that tail; a
// kubectl that is not installed is E_TOOL_MISSING.
// ---------------------------------------------------------------------------

/// How long one kubectl call may run before it is killed.
const K8S_DEADLINE_SECS: u64 = 30;
/// Largest text output: describe, logs, apply, exec, cluster-info, top.
const K8S_MAX_TEXT: usize = 4 * 1024 * 1024;
/// Largest JSON output: get and the list builtins.
const K8S_MAX_JSON: usize = 16 * 1024 * 1024;
/// The last bytes of stderr kept for a failure message.
const K8S_STDERR_TAIL: usize = 2048;
/// Log lines k8s_logs returns when no tail is given, and the most it will return.
const K8S_LOG_DEFAULT_TAIL: i64 = 200;
const K8S_LOG_MAX_TAIL: i64 = 10_000;
/// Largest replica count k8s_scale will request.
const K8S_MAX_REPLICAS: i64 = 1_000;
/// Most argv elements k8s_exec will pass to a container.
const K8S_MAX_EXEC_ARGV: usize = 256;

/// A check that turns one caller string into a value kubectl may be given.
type K8sCheck = fn(&str, &str, &str) -> Result<String>;

/// Run `kubectl` with `args` and return its stdout.
fn kubectl_run(builtin: &str, args: &[&str], max_bytes: usize) -> Result<String> {
    kubectl_run_program(builtin, "kubectl", args, max_bytes, K8S_DEADLINE_SECS)
}

/// [`kubectl_run`] with the program and the deadline given, so a test can aim
/// it at a stand-in. Through the shared bounded runner: past `deadline_secs`
/// the whole process tree is killed and the call is a coded budget error, and
/// a grandchild that keeps the pipes open cannot hold the call.
fn kubectl_run_program(
    builtin: &str,
    program: &str,
    args: &[&str],
    max_bytes: usize,
    deadline_secs: u64,
) -> Result<String> {
    let command = format!("{program} {}", args.join(" "));
    let run = run_tree(
        program,
        args,
        |_| {},
        None,
        std::time::Duration::from_secs(deadline_secs),
        Keep::Head(max_bytes),
        Keep::Tail(K8S_STDERR_TAIL),
    )
    .map_err(|e| match e {
        TreeError::Spawn(e) => crate::safety::spawn_error(builtin, program, &e),
        TreeError::Wait(e) => crate::safety::tool_failed(builtin, &command, None, &e.to_string()),
    })?;
    if run.timed_out {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{command}` did not finish within {deadline_secs} s"),
            "check that the cluster answers, or narrow the call",
        ));
    }
    if !run.success {
        return Err(crate::safety::tool_failed(
            builtin,
            &command,
            run.code,
            &String::from_utf8_lossy(&run.stderr),
        ));
    }
    if run.stdout_truncated {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{command}` printed more than {max_bytes} bytes"),
            "narrow the call: give a namespace or a name, or ask for fewer lines",
        ));
    }
    Ok(String::from_utf8_lossy(&run.stdout).into_owned())
}

/// Test hook: [`kubectl_run`] against `program` with a chosen deadline. Not
/// part of the public API.
#[doc(hidden)]
pub fn __test_kubectl_run(
    program: &str,
    args: &[&str],
    max_bytes: usize,
    deadline_secs: u64,
) -> Result<String> {
    kubectl_run_program("test", program, args, max_bytes, deadline_secs)
}

/// Run `kubectl` with JSON output and parse it.
fn kubectl_json(builtin: &str, args: &[&str], max_bytes: usize) -> Result<Value> {
    let text = kubectl_run(builtin, args, max_bytes)?;
    match serde_json::from_str::<serde_json::Value>(&text) {
        Ok(json) => Ok(json_to_value(json)),
        Err(e) => Err(crate::safety::tool_failed(
            builtin,
            &format!("kubectl {}", args.join(" ")),
            Some(0),
            &format!("printed output that is not JSON ({e})"),
        )),
    }
}

/// A resource type, object name, context or namespace as kubectl will read it:
/// 1-253 letters, digits or `-._/:@,`, and never a leading `-`, which kubectl
/// would take for a flag. The leading-`-` refusal is the option-injection
/// guard; the character set keeps everything else inside what names can be.
fn k8s_token(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    let well_formed = !value.is_empty()
        && value.len() <= 253
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "-._/:@,".contains(c));
    if !well_formed {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be 1-253 characters of letters, digits or -._/:@, (got {value:?})"
        )));
    }
    Ok(value.to_string())
}

/// A Kubernetes object name or namespace: the token rule, narrowed to letters,
/// digits, `-` and `.`, so no resource path or list separator can be smuggled
/// into a `type/name` argument.
fn k8s_object_name(builtin: &str, what: &str, value: &str) -> Result<String> {
    let name = k8s_token(builtin, what, value)?;
    if name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
    {
        Ok(name)
    } else {
        Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is a Kubernetes object name (letters, digits, '-' and '.'), got {value:?}"
        )))
    }
}

/// The string argument at `index`, checked, when it is present.
fn k8s_arg(
    builtin: &str,
    what: &str,
    args: &[Value],
    index: usize,
    check: K8sCheck,
) -> Result<Option<String>> {
    match args.get(index) {
        None => Ok(None),
        Some(Value::Str(s)) => check(builtin, what, s).map(Some),
        Some(other) => Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be a String, got {}",
            other.type_name()
        ))),
    }
}

/// The string argument at `index`, checked, and required.
fn k8s_need(
    builtin: &str,
    what: &str,
    args: &[Value],
    index: usize,
    check: K8sCheck,
) -> Result<String> {
    k8s_arg(builtin, what, args, index, check)?
        .ok_or_else(|| crate::safety::arg_err(format!("{builtin} requires {what}")))
}

/// Refuse a pipeline subject. None of the k8s_* builtins takes one, and an
/// ignored subject would look like a filtered result.
fn k8s_no_input(builtin: &str, input: &Option<Value>) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::arg_err(format!(
            "{builtin} takes no pipeline input"
        )));
    }
    Ok(())
}

/// Refuse more arguments than the builtin takes; none is silently dropped.
fn k8s_max_args(builtin: &str, args: &[Value], max: usize) -> Result<()> {
    if args.len() > max {
        return Err(crate::safety::arg_err(format!(
            "{builtin} takes at most {max} argument(s), got {}",
            args.len()
        )));
    }
    Ok(())
}

/// Append `-n <namespace>` when a namespace was given.
fn k8s_push_ns<'a>(cmd: &mut Vec<&'a str>, ns: Option<&'a str>) {
    if let Some(ns) = ns {
        cmd.extend(["-n", ns]);
    }
}

/// `kubectl get <resource> -o json`, for the list builtins. A namespaced list
/// takes an optional namespace; a cluster-scoped one takes no arguments.
fn k8s_list(
    builtin: &str,
    resource: &str,
    namespaced: bool,
    args: &[Value],
    input: Option<Value>,
) -> Result<Value> {
    k8s_no_input(builtin, &input)?;
    k8s_max_args(builtin, args, usize::from(namespaced))?;
    let ns = if namespaced {
        k8s_arg(builtin, "namespace", args, 0, k8s_object_name)?
    } else {
        None
    };
    let mut cmd: Vec<&str> = vec!["get", "-o", "json"];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", resource]);
    kubectl_json(builtin, &cmd, K8S_MAX_JSON)
}

// ---------------------------------------------------------------------------
// Helm and Terraform: one bounded runner, and the argument checks both share
// ---------------------------------------------------------------------------

/// Deadline for the quick calls: reads of local or cluster state.
const TOOL_DEADLINE_SECS: u64 = 120;
/// Deadline for calls that can run for minutes: provider downloads, plans that
/// refresh, applies, destroys, and helm installs and upgrades.
const TOOL_LONG_DEADLINE_SECS: u64 = 900;
/// The most output a call that prints JSON may produce.
const TOOL_MAX_JSON: usize = 16 * 1024 * 1024;
/// The most output a read-only text call may produce.
const TOOL_MAX_TEXT: usize = 4 * 1024 * 1024;
/// Output kept from a call that changes state. Its work is finished by the time
/// its report is read, so an oversized report keeps its end and says so.
const TOOL_KEEP_TAIL: usize = 256 * 1024;
/// Stderr kept for a failure message.
const TOOL_STDERR_TAIL: usize = 2048;
/// The most `--set` overrides one helm call passes.
const HELM_MAX_SET: usize = 256;
/// The longest Terraform workspace name.
const TF_MAX_WORKSPACE: usize = 90;

/// How much of a call's output is kept.
#[derive(Clone, Copy)]
pub(crate) enum Keep {
    /// The first `n` bytes. More is an error: a read cut short would look whole.
    Head(usize),
    /// The last `n` bytes, with a note when earlier output was dropped.
    Tail(usize),
}

/// One finished call: how it ended and what it printed.
pub(crate) struct ToolRun {
    pub(crate) command: String,
    pub(crate) keep: Keep,
    pub(crate) success: bool,
    pub(crate) code: Option<i32>,
    pub(crate) stdout: String,
    pub(crate) stdout_truncated: bool,
    pub(crate) stderr: String,
    /// Whether earlier stderr was dropped to fit `stderr_keep` (the tail is kept).
    pub(crate) stderr_truncated: bool,
}

/// Read a pipe to its end, keeping its last `keep` bytes, and report whether
/// more than that was printed.
fn tool_read_tail(mut pipe: impl std::io::Read, keep: usize) -> (Vec<u8>, bool) {
    let mut buf: Vec<u8> = Vec::new();
    let mut total: usize = 0;
    let mut chunk = [0u8; 8192];
    loop {
        match pipe.read(&mut chunk) {
            Ok(0) | Err(_) => break,
            Ok(n) => {
                total = total.saturating_add(n);
                buf.extend_from_slice(&chunk[..n]);
                if buf.len() > 2 * keep {
                    let cut = buf.len() - keep;
                    buf.drain(..cut);
                }
            }
        }
    }
    let truncated = total > keep;
    if buf.len() > keep {
        let cut = buf.len() - keep;
        buf.drain(..cut);
    }
    (buf, truncated)
}

/// Run `program` with `args` in `dir` (the process's directory when `None`),
/// directly and never through a shell, with stdin closed. Past `deadline_secs`
/// the child is killed and the call is refused. Nothing is judged here: the
/// caller decides what a finished call means.
fn tool_run(
    builtin: &str,
    program: &str,
    dir: Option<&std::path::Path>,
    args: &[&str],
    keep: Keep,
    deadline_secs: u64,
) -> Result<ToolRun> {
    tool_run_stderr(
        builtin,
        program,
        dir,
        args,
        keep,
        TOOL_STDERR_TAIL,
        deadline_secs,
    )
}

/// [`tool_run`] that keeps `stderr_keep` bytes of stderr instead of the usual
/// failure-message tail. A tool whose report is written to stderr (valgrind)
/// needs more than the tail; its failure message is cut again by the caller.
fn tool_run_stderr(
    builtin: &str,
    program: &str,
    dir: Option<&std::path::Path>,
    args: &[&str],
    keep: Keep,
    stderr_keep: usize,
    deadline_secs: u64,
) -> Result<ToolRun> {
    let mut run = run_bounded(
        builtin,
        program,
        dir,
        args,
        keep,
        stderr_keep,
        deadline_secs,
    )?;
    run.stderr = strip_ansi(&run.stderr).trim().to_string();
    Ok(run)
}

/// The bounded runner behind [`tool_run_stderr`], with stderr left as the
/// program wrote it. Stdout keeps `keep` and stderr its last `stderr_keep`
/// bytes. Past `deadline_secs` the whole process tree is killed and the call is
/// refused. Never through a shell, with stdin closed.
pub(crate) fn run_bounded(
    builtin: &str,
    program: &str,
    dir: Option<&std::path::Path>,
    args: &[&str],
    keep: Keep,
    stderr_keep: usize,
    deadline_secs: u64,
) -> Result<ToolRun> {
    let command = format!("{program} {}", args.join(" "));
    let run = run_tree(
        program,
        args,
        |cmd| {
            if let Some(dir) = dir {
                cmd.current_dir(dir);
            }
            if program == "terraform" {
                // Automation mode drops the interactive "run terraform apply" hints.
                cmd.env("TF_IN_AUTOMATION", "1");
            }
        },
        None,
        std::time::Duration::from_secs(deadline_secs),
        keep,
        Keep::Tail(stderr_keep),
    )
    .map_err(|e| match e {
        TreeError::Spawn(e) => crate::safety::spawn_error(builtin, program, &e),
        TreeError::Wait(e) => crate::safety::tool_failed(builtin, &command, None, &e.to_string()),
    })?;
    if run.timed_out {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{command}` did not finish within {deadline_secs} s"),
            "a killed call can leave work half done; check the state with the matching read builtin before retrying",
        ));
    }
    Ok(ToolRun {
        command,
        keep,
        success: run.success,
        code: run.code,
        stdout: String::from_utf8_lossy(&run.stdout).into_owned(),
        stdout_truncated: run.stdout_truncated,
        stderr: String::from_utf8_lossy(&run.stderr).into_owned(),
        stderr_truncated: run.stderr_truncated,
    })
}

/// How one bounded run ended. A pipe that a descendant of the child kept open
/// past the grace is abandoned: what it had produced is kept, and
/// `pipes_abandoned` says so. The `_truncated` flags mean only that output went
/// past its bound, so a child that finished while a helper it started still
/// held the pipe is not reported as having printed too much.
pub(crate) struct TreeRun {
    /// The child exited on its own with status 0.
    pub(crate) success: bool,
    /// The exit code; `None` when killed by a signal or at the deadline.
    pub(crate) code: Option<i32>,
    /// The deadline passed and the child's tree was killed.
    pub(crate) timed_out: bool,
    pub(crate) stdout: Vec<u8>,
    pub(crate) stdout_truncated: bool,
    pub(crate) stderr: Vec<u8>,
    pub(crate) stderr_truncated: bool,
    /// A descendant still held stdout or stderr after the grace, so whatever
    /// it would have printed after that was not read.
    pub(crate) pipes_abandoned: bool,
    /// The child's exit status; `None` only when the deadline killed it.
    pub(crate) status: Option<std::process::ExitStatus>,
}

/// Why a bounded run could not be completed.
pub(crate) enum TreeError {
    /// The program did not start.
    Spawn(std::io::Error),
    /// Waiting on the child failed; the child's tree was killed.
    Wait(std::io::Error),
}

/// How long a run's pipes may stay open after its child has exited or been
/// killed. Only a descendant that outlived the child can keep them open.
const PIPE_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
/// How long the pipes may take to close once a leftover group was killed.
const AFTER_KILL_GRACE: std::time::Duration = std::time::Duration::from_millis(500);
/// Bound on one `taskkill` at a deadline, so the kill itself cannot hang a call.
#[cfg(windows)]
const TASKKILL_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);

/// The one bounded runner that the builtins, the diagnostics runner and the
/// tool-run runner share. `program` runs with `args` directly (never through a
/// shell); `configure` may set the directory and environment; `stdin` is a
/// fixed payload, or the child gets a null stdin when `None`.
///
/// The child leads its own process group (unix), and on Windows it is put in a
/// job object at once (see [`TreeJob`]). At `limit` the child's tree is killed
/// (the group on unix; the job, then `taskkill /T`, on Windows) and the child is
/// reaped. After a normal exit, a pipe still open after [`PIPE_GRACE`] means a
/// leftover descendant holds it, so the group is killed (the job on Windows). A
/// pipe still open after the grace that follows a kill is abandoned, not joined.
/// The call therefore takes at most `limit` plus a few seconds, whatever the
/// descendants do.
///
/// On Windows the job reaches descendants whose parent has already exited, which
/// `taskkill /T` cannot walk. A descendant started before the child joined the
/// job escapes every kill here; that window is short but not zero.
pub(crate) fn run_tree(
    program: &str,
    args: &[&str],
    configure: impl FnOnce(&mut std::process::Command),
    stdin: Option<Vec<u8>>,
    limit: std::time::Duration,
    stdout_keep: Keep,
    stderr_keep: Keep,
) -> std::result::Result<TreeRun, TreeError> {
    let mut command = crate::safety::child_command(program);
    command.args(args);
    configure(&mut command);
    run_tree_cmd(command, stdin, limit, stdout_keep, stderr_keep)
}

/// [`run_tree`] for a `Command` the caller has already built (its program,
/// arguments, environment and directory are kept). Its stdio is set here, so
/// the caller's stdin, stdout and stderr settings are replaced.
pub(crate) fn run_tree_cmd(
    command: std::process::Command,
    stdin: Option<Vec<u8>>,
    limit: std::time::Duration,
    stdout_keep: Keep,
    stderr_keep: Keep,
) -> std::result::Result<TreeRun, TreeError> {
    run_tree_cmd_observed(command, stdin, limit, stdout_keep, stderr_keep, |_, _| {})
}

/// [`run_tree_cmd`] that also hands `observe` the child once the runner is done
/// with it (it exited, or was killed at the limit and reaped), before the
/// child's handle is closed. The second argument is the time from the start of
/// the wait to that point. Only a caller that reads the child's handle needs
/// this: perf stat reads process times and memory from it on Windows.
pub(crate) fn run_tree_cmd_observed(
    mut command: std::process::Command,
    stdin: Option<Vec<u8>>,
    limit: std::time::Duration,
    stdout_keep: Keep,
    stderr_keep: Keep,
    observe: impl FnOnce(&std::process::Child, std::time::Duration),
) -> std::result::Result<TreeRun, TreeError> {
    use std::process::Stdio;
    crate::safety::strip_ironshell_env(&mut command);
    command
        .stdin(if stdin.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }
    let mut child = command.spawn().map_err(TreeError::Spawn)?;
    #[cfg(windows)]
    let job = TreeJob::for_child(&child);
    if let (Some(payload), Some(mut pipe)) = (stdin, child.stdin.take()) {
        // Detached: a child that never reads its stdin blocks this write until
        // the kill closes the pipe, which then fails the write.
        std::thread::spawn(move || {
            use std::io::Write;
            let _ = pipe.write_all(&payload);
        });
    }
    let out = PipeReader::start(child.stdout.take(), stdout_keep);
    let err = PipeReader::start(child.stderr.take(), stderr_keep);

    let started = std::time::Instant::now();
    let exited = loop {
        match child.try_wait() {
            Ok(Some(status)) => break Some(status),
            Ok(None) => {}
            Err(e) => {
                #[cfg(windows)]
                kill_job(job.as_ref());
                kill_tree(&mut child);
                return Err(TreeError::Wait(e));
            }
        }
        if started.elapsed() >= limit {
            break None;
        }
        std::thread::sleep(std::time::Duration::from_millis(5));
    };
    let waited = started.elapsed();
    let (success, code, status, timed_out, out_closed, err_closed) = match exited {
        Some(status) => {
            let (mut out_closed, mut err_closed) = wait_pipes(&out, &err, PIPE_GRACE);
            if !(out_closed && err_closed) {
                // A descendant that outlived the child holds a pipe: kill its
                // group rather than wait for it.
                #[cfg(windows)]
                kill_job(job.as_ref());
                kill_group(child.id());
                (out_closed, err_closed) = wait_pipes(&out, &err, AFTER_KILL_GRACE);
            }
            (
                status.success(),
                status.code(),
                Some(status),
                false,
                out_closed,
                err_closed,
            )
        }
        None => {
            #[cfg(windows)]
            kill_job(job.as_ref());
            kill_tree(&mut child);
            let (out_closed, err_closed) = wait_pipes(&out, &err, PIPE_GRACE);
            (false, None, None, true, out_closed, err_closed)
        }
    };
    observe(&child, waited);
    let (stdout, stdout_truncated) = out.finish();
    let (stderr, stderr_truncated) = err.finish();
    Ok(TreeRun {
        success,
        code,
        timed_out,
        stdout,
        stdout_truncated,
        stderr,
        stderr_truncated,
        pipes_abandoned: !out_closed || !err_closed,
        status,
    })
}

/// Deadline for a probe that only asks a tool about itself or the host
/// (`--version`, `uname`, `which`, a status read). It bounds a hung probe, not
/// a slow one: 10 s was measured too short, because a cold `powershell` start
/// under a parallel test run took longer than that on Windows.
pub(crate) const PROBE_DEADLINE_SECS: u64 = 30;

/// `cmd.output()` with a deadline: the whole process tree is killed past
/// `deadline_secs`, and output over 64 MiB is refused (see
/// [`crate::safety::output_with_timeout`]). A tool that is absent is
/// E_TOOL_MISSING, a deadline is E_BUDGET_EXCEEDED, and a nonzero exit is left
/// in the returned status for the caller to judge, as `output()` left it.
pub(crate) fn bounded_cmd_output(
    builtin: &str,
    tool: &str,
    cmd: std::process::Command,
    deadline_secs: u64,
) -> Result<std::process::Output> {
    crate::safety::output_with_timeout(cmd, deadline_secs)
        .map_err(|e| crate::safety::spawn_error(builtin, tool, &e))
}

/// Run `tool` (executed as `program`) through [`run_tree`] and return the
/// `Output` its callers read. Stdin is written on run_tree's own thread, so a
/// payload larger than the pipe buffer cannot deadlock against a child that is
/// still writing. Past `deadline_secs` the child's tree is killed and the call
/// is a coded budget error. Output over `max_output` in either stream is also a
/// budget error: a report cut short would look whole. Nothing is judged here.
pub(crate) fn run_output(
    builtin: &str,
    tool: &str,
    program: &str,
    args: &[&str],
    configure: impl FnOnce(&mut std::process::Command),
    stdin: Option<Vec<u8>>,
    deadline_secs: u64,
    max_output: usize,
) -> Result<std::process::Output> {
    let run = run_tree(
        program,
        args,
        configure,
        stdin,
        std::time::Duration::from_secs(deadline_secs),
        Keep::Head(max_output),
        Keep::Head(max_output),
    )
    .map_err(|e| match e {
        TreeError::Spawn(e) | TreeError::Wait(e) => crate::safety::spawn_error(builtin, tool, &e),
    })?;
    match run.status {
        Some(status) if !run.timed_out => {
            if run.stdout_truncated || run.stderr_truncated {
                return Err(crate::safety::budget_exceeded(
                    builtin,
                    format!("`{tool}` printed more than {max_output} 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,
            })
        }
        _ => Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{tool}` did not finish within {deadline_secs} s"),
            "the call was killed and its result discarded; check the state with the matching read builtin before retrying",
        )),
    }
}

/// Test hook: the scheduler's tool runner, so a test can feed it a payload
/// larger than the pipe buffer. Not part of the public API.
#[doc(hidden)]
pub fn __test_scheduler_run_tool(
    tool: &str,
    args: &[&str],
    stdin: Option<&[u8]>,
) -> Result<std::process::Output> {
    scheduler::run_tool("test", tool, args, stdin)
}

/// Test hook: the container CLI runner with its deadline given in seconds.
/// Not part of the public API.
#[doc(hidden)]
pub fn __test_container_cli(program: &str, args: &[&str], deadline_secs: u64) -> Result<String> {
    container_cli_within("test", program, args, false, deadline_secs)
}

/// Test hook: the checked tool runner (`run_checked`, behind `run_tool`) with
/// its deadline given in seconds. Not part of the public API.
#[doc(hidden)]
pub fn __test_run_checked(tool: &str, args: &[&str], deadline_secs: u64) -> Result<String> {
    let mut cmd = crate::safety::child_command(tool);
    cmd.args(args);
    run_checked("test", tool, cmd, deadline_secs).map(|(out, _)| out)
}

/// Test hook: the package manager's exec helper (Linux only) with its deadline
/// given in seconds. Not part of the public API.
#[cfg(target_os = "linux")]
#[doc(hidden)]
pub fn __test_pkg_exec(
    tool: &str,
    args: &[&str],
    deadline_secs: u64,
) -> Result<std::process::Output> {
    let argv: Vec<String> = args.iter().map(|arg| arg.to_string()).collect();
    pkg_admin::exec_for("test", tool, &argv, deadline_secs)
}

/// Test hook: the account tools' spawn helper (Linux; elsewhere a refusal).
/// Not part of the public API.
#[doc(hidden)]
pub fn __test_accounts_spawn(
    tool: &str,
    args: &[&str],
    stdin: Option<&str>,
) -> Result<std::process::Output> {
    accounts::spawn("test", tool, args, stdin)
}

/// What one pipe has produced, kept to its `Keep` bound while it is read.
struct PipeBuf {
    keep: Keep,
    kept: Vec<u8>,
    total: usize,
}

impl PipeBuf {
    fn limit(&self) -> usize {
        match self.keep {
            Keep::Head(n) | Keep::Tail(n) => n,
        }
    }

    fn push(&mut self, bytes: &[u8]) {
        self.total = self.total.saturating_add(bytes.len());
        match self.keep {
            Keep::Head(max) => {
                let room = max.saturating_sub(self.kept.len());
                self.kept.extend_from_slice(&bytes[..bytes.len().min(room)]);
            }
            Keep::Tail(max) => {
                self.kept.extend_from_slice(bytes);
                if self.kept.len() > max.saturating_mul(2) {
                    let cut = self.kept.len() - max;
                    self.kept.drain(..cut);
                }
            }
        }
    }
}

/// A pipe read to its end on its own thread. The thread signals `done` when
/// the pipe reaches end-of-file; the waiter never joins the thread.
struct PipeReader {
    buf: std::sync::Arc<std::sync::Mutex<PipeBuf>>,
    done: std::sync::mpsc::Receiver<()>,
}

impl PipeReader {
    fn start<R: std::io::Read + Send + 'static>(pipe: Option<R>, keep: Keep) -> Self {
        let buf = std::sync::Arc::new(std::sync::Mutex::new(PipeBuf {
            keep,
            kept: Vec::new(),
            total: 0,
        }));
        let (tx, done) = std::sync::mpsc::channel();
        match pipe {
            Some(mut pipe) => {
                let shared = std::sync::Arc::clone(&buf);
                std::thread::spawn(move || {
                    let mut chunk = [0u8; 8192];
                    loop {
                        match pipe.read(&mut chunk) {
                            Ok(0) => break,
                            Ok(n) => shared
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)
                                .push(&chunk[..n]),
                            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                            Err(_) => break,
                        }
                    }
                    let _ = tx.send(());
                });
            }
            None => {
                let _ = tx.send(());
            }
        }
        PipeReader { buf, done }
    }

    /// Whether the pipe reached end-of-file by `until`. A reader that has
    /// finished (its sender is gone) counts as closed on every later call.
    fn wait_until(&self, until: std::time::Instant) -> bool {
        let wait = until.saturating_duration_since(std::time::Instant::now());
        !matches!(
            self.done.recv_timeout(wait),
            Err(std::sync::mpsc::RecvTimeoutError::Timeout)
        )
    }

    /// The kept bytes and whether output went past the bound and was dropped.
    fn finish(self) -> (Vec<u8>, bool) {
        let mut buf = self
            .buf
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let max = buf.limit();
        let truncated = buf.total > max;
        if let Keep::Tail(_) = buf.keep {
            if buf.kept.len() > max {
                let cut = buf.kept.len() - max;
                buf.kept.drain(..cut);
            }
        }
        (std::mem::take(&mut buf.kept), truncated)
    }
}

/// Wait for both pipes to close within one shared grace.
fn wait_pipes(out: &PipeReader, err: &PipeReader, grace: std::time::Duration) -> (bool, bool) {
    let until = std::time::Instant::now() + grace;
    (out.wait_until(until), err.wait_until(until))
}

/// Kill the child's tree, then reap the child. Unix: the child leads its own
/// process group, so the whole group is signalled. Windows: `taskkill /T` walks
/// the tree, which only works while the child is alive, so it runs first. Callers
/// on Windows terminate the run's job ([`kill_job`]) before this.
fn kill_tree(child: &mut std::process::Child) {
    kill_group(child.id());
    #[cfg(windows)]
    {
        taskkill_tree(child.id());
    }
    let _ = child.kill();
    let _ = child.wait();
}

/// Windows: a job object that holds one bounded run's child and what it starts.
/// A process started by a job member joins the job (Windows 8 and later), so the
/// job reaches descendants whose parent has already exited, which `taskkill /T`
/// cannot walk. The job does not kill on close: a descendant that closed its
/// pipes and was left running survives, as on unix. A descendant the child starts
/// before it is assigned to the job escapes the job.
#[cfg(windows)]
struct TreeJob(*mut std::ffi::c_void);

#[cfg(windows)]
#[link(name = "kernel32")]
extern "system" {
    fn CreateJobObjectW(attrs: *mut std::ffi::c_void, name: *const u16) -> *mut std::ffi::c_void;
    fn AssignProcessToJobObject(job: *mut std::ffi::c_void, process: *mut std::ffi::c_void) -> i32;
    fn TerminateJobObject(job: *mut std::ffi::c_void, exit_code: u32) -> i32;
    fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
}

#[cfg(windows)]
impl TreeJob {
    /// A job holding `child`, or `None` when no job can be made or the child
    /// cannot join one (for example a process already in a job that forbids
    /// nesting). Without a job the run falls back to `taskkill /T`.
    fn for_child(child: &std::process::Child) -> Option<TreeJob> {
        use std::os::windows::io::AsRawHandle;
        // SAFETY: null attributes and a null name ask for an unnamed job with the
        // default security descriptor; the call has no other effects.
        let job = TreeJob(unsafe { CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()) });
        if job.0.is_null() {
            return None;
        }
        // SAFETY: `job.0` is the live job handle made above, and the child's
        // process handle stays valid while `child` is borrowed. On failure `job`
        // is dropped, which closes the job.
        let assigned = unsafe { AssignProcessToJobObject(job.0, child.as_raw_handle()) };
        (assigned != 0).then_some(job)
    }

    /// Kill every process in the job, the child's descendants included, whether
    /// or not their parent is still alive.
    fn terminate(&self) {
        // SAFETY: `self.0` is a live job handle owned by `self`.
        unsafe {
            TerminateJobObject(self.0, 1);
        }
    }
}

#[cfg(windows)]
impl Drop for TreeJob {
    fn drop(&mut self) {
        // SAFETY: the handle came from CreateJobObjectW and is closed only here.
        // Closing it ends nothing: kill-on-close is not set.
        unsafe {
            CloseHandle(self.0);
        }
    }
}

/// Windows: terminate a run's job, if it has one. Called before `taskkill /T` at
/// a deadline, and after a normal exit when a pipe is held open.
#[cfg(windows)]
fn kill_job(job: Option<&TreeJob>) {
    if let Some(job) = job {
        job.terminate();
    }
}

/// Signal the process group whose id is `pid` (the child's own group on unix).
fn kill_group(pid: u32) {
    #[cfg(unix)]
    {
        // SAFETY: a negative pid addresses the process group that
        // `process_group(0)` made the child's own; kill has no memory effects.
        unsafe {
            libc::kill(-(pid as i32), libc::SIGKILL);
        }
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
    }
}

/// `taskkill /T /F` on the tree rooted at `pid`, given at most
/// [`TASKKILL_LIMIT`]. It runs with argv (no shell) and its output is discarded.
#[cfg(windows)]
pub(crate) fn taskkill_tree(pid: u32) {
    use std::process::Stdio;
    let pid_text = pid.to_string();
    let mut cmd = crate::safety::child_command("taskkill");
    crate::safety::strip_ironshell_env(&mut cmd);
    let Ok(mut killer) = cmd
        .args(["/T", "/F", "/PID", pid_text.as_str()])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return;
    };
    let until = std::time::Instant::now() + TASKKILL_LIMIT;
    loop {
        match killer.try_wait() {
            Ok(Some(_)) => return,
            Ok(None) if std::time::Instant::now() < until => {
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
            _ => {
                let _ = killer.kill();
                let _ = killer.wait();
                return;
            }
        }
    }
}

/// Text with terminal colour sequences removed. Terraform colours some errors on
/// stderr even under -no-color, and a failure message should not carry them.
fn strip_ansi(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\u{1b}' {
            if chars.peek() == Some(&'[') {
                chars.next();
                for d in chars.by_ref() {
                    if d.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// The text of a finished call, or the coded failure it reports.
fn tool_text(builtin: &str, run: ToolRun) -> Result<String> {
    if !run.success {
        return Err(crate::safety::tool_failed(
            builtin,
            &run.command,
            run.code,
            &run.stderr,
        ));
    }
    match run.keep {
        Keep::Head(max) if run.stdout_truncated => Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{}` printed more than {max} bytes", run.command),
            "narrow the call so that it prints less",
        )),
        Keep::Tail(max) if run.stdout_truncated => Ok(format!(
            "[earlier output dropped; the last {max} bytes follow]\n{}",
            run.stdout
        )),
        _ => Ok(run.stdout),
    }
}

/// The JSON a finished call printed. Output that is not JSON is a coded
/// failure, never a string handed back in place of the answer.
fn tool_json(builtin: &str, run: ToolRun) -> Result<Value> {
    let command = run.command.clone();
    let text = tool_text(builtin, run)?;
    match serde_json::from_str::<serde_json::Value>(&text) {
        Ok(json) => Ok(json_to_value(json)),
        Err(e) => Err(crate::safety::tool_failed(
            builtin,
            &command,
            Some(0),
            &format!("printed output that is not JSON ({e})"),
        )),
    }
}

/// A helm call, run in the process's directory.
fn helm_call(builtin: &str, args: &[String], keep: Keep, deadline_secs: u64) -> Result<ToolRun> {
    let refs: Vec<&str> = args.iter().map(String::as_str).collect();
    tool_run(builtin, "helm", None, &refs, keep, deadline_secs)
}

/// A terraform call, run in `dir`.
fn tf_call(
    builtin: &str,
    dir: &std::path::Path,
    args: &[&str],
    keep: Keep,
    deadline_secs: u64,
) -> Result<ToolRun> {
    tool_run(builtin, "terraform", Some(dir), args, keep, deadline_secs)
}

/// The workspace root as an absolute path. `IRONSHELL_WORKSPACE`, or the process's
/// directory when it is unset.
fn workspace_root_abs() -> std::path::PathBuf {
    let root = crate::safety::workspace_root();
    if root.is_absolute() {
        root
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(&root))
            .unwrap_or(root)
    }
}

/// `value` resolved against `base` and required to lie inside the workspace.
/// Every path a helm or terraform call is given passes here first.
fn workspace_path(
    builtin: &str,
    value: &str,
    base: &std::path::Path,
) -> Result<std::path::PathBuf> {
    let given = std::path::Path::new(value);
    let path = if given.is_absolute() {
        given.to_path_buf()
    } else {
        base.join(given)
    };
    if !crate::safety::within_workspace(&path.to_string_lossy()) {
        return Err(crate::safety::outside_workspace(builtin, value));
    }
    Ok(path)
}

/// A plain text argument: not empty and never option-like. Used where the
/// value goes to a tool as an argument, so a leading `-` would be a flag.
fn tf_plain(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    if value.trim().is_empty() || value.contains('\0') {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must not be empty"
        )));
    }
    Ok(value.to_string())
}

/// A Terraform directory: the workspace root, or `value` inside it. Refused
/// when it is outside the workspace, or when it is not a directory. Without
/// that second check a missing directory would surface as E_TOOL_MISSING.
fn tf_dir(builtin: &str, value: Option<&str>) -> Result<std::path::PathBuf> {
    let root = workspace_root_abs();
    let dir = match value {
        None => root,
        Some(v) => workspace_path(builtin, v, &root)?,
    };
    if !dir.is_dir() {
        return Err(crate::safety::not_found(
            builtin,
            "directory",
            &dir.display().to_string(),
        ));
    }
    Ok(dir)
}

/// `-var-file=<path>` for a variable file inside the workspace, when one is given.
fn tf_var_file(builtin: &str, args: &[Value], index: usize) -> Result<Option<String>> {
    let Some(name) = k8s_arg(builtin, "variable file", args, index, tf_plain)? else {
        return Ok(None);
    };
    let path = workspace_path(builtin, &name, &workspace_root_abs())?;
    if !path.is_file() {
        return Err(crate::safety::not_found(builtin, "variable file", &name));
    }
    Ok(Some(format!("-var-file={}", path.display())))
}

/// A Terraform workspace name: letters, digits, `-` and `_`.
fn tf_workspace_name(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    let well_formed = !value.is_empty()
        && value.chars().count() <= TF_MAX_WORKSPACE
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if !well_formed {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is 1-{TF_MAX_WORKSPACE} letters, digits, '-' or '_' (got {value:?})"
        )));
    }
    Ok(value.to_string())
}

/// A helm chart: a repository chart name, an OCI or URL reference, or a local
/// path. A local path that exists must lie inside the workspace.
fn helm_chart(builtin: &str, what: &str, value: &str) -> Result<String> {
    let chart = k8s_token(builtin, what, value)?;
    if std::path::Path::new(&chart).exists() {
        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
        workspace_path(builtin, &chart, &cwd)?;
    }
    Ok(chart)
}

/// A helm values key: letters, digits, and `._-[]`, not starting with `-`.
fn helm_set_key(builtin: &str, key: &str) -> Result<String> {
    let well_formed = !key.is_empty()
        && key.len() <= 253
        && !key.starts_with('-')
        && key
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "._-[]".contains(c));
    if !well_formed {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: a values key is letters, digits and ._-[] and does not start with '-' (got {key:?})"
        )));
    }
    Ok(key.to_string())
}

/// `--set=key=value` for each override in a values Record. Each override is one
/// argv element, so a value cannot become a flag. A comma in a string value is
/// escaped, because helm splits `--set` on commas.
fn helm_set_flags(builtin: &str, values: Option<&Value>) -> Result<Vec<String>> {
    let overrides = match values {
        None => return Ok(Vec::new()),
        Some(Value::Record(map)) => map,
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: values must be a Record, got {}",
                other.type_name()
            )))
        }
    };
    if overrides.len() > HELM_MAX_SET {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: at most {HELM_MAX_SET} values, got {}",
            overrides.len()
        )));
    }
    let mut flags = Vec::with_capacity(overrides.len());
    for (key, value) in overrides {
        let key = helm_set_key(builtin, key)?;
        let text = match value {
            Value::Str(s) if s.chars().any(char::is_control) => {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: the value for {key} contains a control character"
                )))
            }
            Value::Str(s) => s.replace(',', "\\,"),
            Value::Int(n) => n.to_string(),
            Value::Bool(b) => b.to_string(),
            Value::Float(f) if f.is_finite() => f.to_string(),
            other => {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: the value for {key} must be a String, Int, Float or Bool, got {}",
                    other.type_name()
                )))
            }
        };
        flags.push(format!("--set={key}={text}"));
    }
    Ok(flags)
}

/// `--namespace=<ns>` when a namespace was given.
fn helm_ns_flag(ns: Option<String>) -> Option<String> {
    ns.map(|n| format!("--namespace={n}"))
}

// Helper: parse tabular kubectl output (e.g. `kubectl top`) into Records
fn parse_kubectl_table(text: &str) -> Vec<Value> {
    let mut lines = text.lines();
    let header_line = match lines.next() {
        Some(h) => h,
        None => return Vec::new(),
    };
    let headers: Vec<String> = header_line
        .split_whitespace()
        .map(|h| {
            h.to_lowercase()
                .replace('(', "_")
                .replace(')', "")
                .replace('%', "pct")
        })
        .collect();
    let mut rows = Vec::new();
    for line in lines {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let cols: Vec<&str> = trimmed.split_whitespace().collect();
        let mut record = std::collections::BTreeMap::new();
        for (i, hdr) in headers.iter().enumerate() {
            let val = cols.get(i).unwrap_or(&"").to_string();
            record.insert(hdr.clone(), Value::Str(val));
        }
        rows.push(Value::Record(record));
    }
    rows
}

// ---------------------------------------------------------------------------
// 850: bi_k8s_get - kubectl get <resource> [-n namespace] -o json
// ---------------------------------------------------------------------------
fn bi_k8s_get(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("k8s_get", &input)?;
    k8s_max_args("k8s_get", &args, 2)?;
    let resource = k8s_need("k8s_get", "a resource type", &args, 0, k8s_token)?;
    let ns = k8s_arg("k8s_get", "namespace", &args, 1, k8s_object_name)?;
    let mut cmd: Vec<&str> = vec!["get", "-o", "json"];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", resource.as_str()]);
    kubectl_json("k8s_get", &cmd, K8S_MAX_JSON)
}

// ---------------------------------------------------------------------------
// 851: bi_k8s_apply - kubectl apply -f <local manifest> [-n namespace]
//
// The manifest is a local file inside the workspace, read through the same
// guard as the file builtins before kubectl is given its resolved path. A URL
// is refused: kubectl would fetch it outside that guard.
// ---------------------------------------------------------------------------
fn bi_k8s_apply(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_apply";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let Some(Value::Str(file)) = args.first() else {
        return Err(crate::safety::arg_err(
            "k8s_apply requires a manifest file path as first argument",
        ));
    };
    crate::safety::reject_option_like(B, std::slice::from_ref(file))?;
    if file.contains("://") {
        return Err(crate::safety::arg_err(
            "k8s_apply reads a local manifest; a URL is not fetched, because kubectl would read it outside the workspace guard",
        ));
    }
    let ns = k8s_arg(B, "namespace", &args, 1, k8s_object_name)?;
    let resolved = crate::safety::resolve_path_str(file);
    // No guard call here: listing k8s_apply as self-guarded would skip the
    // dispatcher's Network guard (metering, allowlist, audit) for the cluster
    // call. The manifest read is checked by validate_read_path.
    let path = crate::security::validate_read_path(&resolved)?;
    let meta = std::fs::metadata(&path).map_err(|e| crate::safety::fs_error(B, &path, &e))?;
    if !meta.is_file() {
        return Err(crate::safety::arg_err(format!(
            "{B} requires a regular file, got {resolved:?}"
        )));
    }
    let path_text = path.display().to_string();
    let mut cmd: Vec<&str> = vec!["apply", "-f", path_text.as_str()];
    k8s_push_ns(&mut cmd, ns.as_deref());
    let text = kubectl_run(B, &cmd, K8S_MAX_TEXT)?;
    Ok(Value::Str(text.trim().to_string()))
}

// ---------------------------------------------------------------------------
// 852: bi_k8s_delete - kubectl delete <resource> <name> [-n namespace]
// ---------------------------------------------------------------------------
fn bi_k8s_delete(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_delete";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    let resource = k8s_need(B, "a resource type", &args, 0, k8s_token)?;
    let name = k8s_need(B, "a resource name", &args, 1, k8s_object_name)?;
    let ns = k8s_arg(B, "namespace", &args, 2, k8s_object_name)?;
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: B,
        effect: crate::safety::Effect::Destructive,
        what: "k8s_delete",
        targets: vec![format!("{}/{}", resource, name)],
        blast_radius: serde_json::json!({ "resource": resource, "name": name, "namespace": ns }),
        reversible: false,
        fs_paths: false,
    })?;
    let mut cmd: Vec<&str> = vec!["delete"];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", resource.as_str(), name.as_str()]);
    let text = kubectl_run(B, &cmd, K8S_MAX_TEXT)?;
    Ok(Value::Str(text.trim().to_string()))
}

// ---------------------------------------------------------------------------
// 853: bi_k8s_describe - kubectl describe <resource> <name> [-n namespace]
// ---------------------------------------------------------------------------
fn bi_k8s_describe(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_describe";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    let resource = k8s_need(B, "a resource type", &args, 0, k8s_token)?;
    let name = k8s_need(B, "a resource name", &args, 1, k8s_object_name)?;
    let ns = k8s_arg(B, "namespace", &args, 2, k8s_object_name)?;
    let mut cmd: Vec<&str> = vec!["describe"];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", resource.as_str(), name.as_str()]);
    let text = kubectl_run(B, &cmd, K8S_MAX_TEXT)?;
    Ok(Value::Str(text.trim().to_string()))
}

// ---------------------------------------------------------------------------
// 854: bi_k8s_logs - kubectl logs <pod> [-n namespace] --tail=N
//
// Always bounded: the tail defaults to K8S_LOG_DEFAULT_TAIL lines and cannot
// exceed K8S_LOG_MAX_TAIL.
// ---------------------------------------------------------------------------
fn bi_k8s_logs(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_logs";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    let pod = k8s_need(B, "a pod name", &args, 0, k8s_object_name)?;
    let ns = k8s_arg(B, "namespace", &args, 1, k8s_object_name)?;
    let tail = match args.get(2) {
        None => K8S_LOG_DEFAULT_TAIL,
        Some(Value::Int(n)) if (1..=K8S_LOG_MAX_TAIL).contains(n) => *n,
        Some(Value::Int(n)) => {
            return Err(crate::safety::arg_err(format!(
                "k8s_logs tail must be in 1..={K8S_LOG_MAX_TAIL} lines, got {n}"
            )))
        }
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "k8s_logs tail must be an Int, got {}",
                other.type_name()
            )))
        }
    };
    let tail_flag = format!("--tail={tail}");
    let mut cmd: Vec<&str> = vec!["logs", tail_flag.as_str()];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", pod.as_str()]);
    Ok(Value::Str(kubectl_run(B, &cmd, K8S_MAX_TEXT)?))
}

// ---------------------------------------------------------------------------
// 855: bi_k8s_exec - kubectl exec <pod> [-n namespace] -- <argv...>
//
// The command is an Array of Strings, the argv the container runs. A string is
// refused rather than split on spaces, and nothing is run through a shell.
// ---------------------------------------------------------------------------
fn bi_k8s_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_exec";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    let pod = k8s_need(B, "a pod name", &args, 0, k8s_object_name)?;
    let Some(Value::Array(items)) = args.get(1) else {
        return Err(crate::safety::arg_err(
            "k8s_exec command must be an Array of Strings (the argv); a shell string is not run",
        ));
    };
    if items.is_empty() || items.len() > K8S_MAX_EXEC_ARGV {
        return Err(crate::safety::arg_err(format!(
            "k8s_exec command must have 1..={K8S_MAX_EXEC_ARGV} elements, got {}",
            items.len()
        )));
    }
    let mut argv: Vec<String> = Vec::with_capacity(items.len());
    for item in items {
        match item {
            Value::Str(s) if !s.contains('\0') => argv.push(s.clone()),
            _ => {
                return Err(crate::safety::arg_err(
                    "k8s_exec command elements must be Strings without NUL bytes",
                ))
            }
        }
    }
    let ns = k8s_arg(B, "namespace", &args, 2, k8s_object_name)?;
    crate::safety::guard_exec(B, format!("kubectl exec {pod} -- {}", argv.join(" ")))?;
    let mut cmd: Vec<&str> = vec!["exec", pod.as_str()];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.push("--");
    cmd.extend(argv.iter().map(String::as_str));
    Ok(Value::Str(kubectl_run(B, &cmd, K8S_MAX_TEXT)?))
}

// ---------------------------------------------------------------------------
// 856-866: list builtins (kubectl get <resource> -o json)
// ---------------------------------------------------------------------------
fn bi_k8s_pods(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_list("k8s_pods", "pods", true, &args, input)
}

fn bi_k8s_services(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_list("k8s_services", "services", true, &args, input)
}

fn bi_k8s_deployments(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_list("k8s_deployments", "deployments", true, &args, input)
}

fn bi_k8s_namespaces(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_list("k8s_namespaces", "namespaces", false, &args, input)
}

fn bi_k8s_nodes(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_list("k8s_nodes", "nodes", false, &args, input)
}

fn bi_k8s_events(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_list("k8s_events", "events", true, &args, input)
}

fn bi_k8s_configmaps(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_list("k8s_configmaps", "configmaps", true, &args, input)
}

fn bi_k8s_ingresses(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_list("k8s_ingresses", "ingresses", true, &args, input)
}

// ---------------------------------------------------------------------------
// 863: bi_k8s_secrets - secret names only
//
// The jsonpath selects metadata.name and nothing else, so no secret value is
// read into the shell.
// ---------------------------------------------------------------------------
fn bi_k8s_secrets(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_secrets";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let ns = k8s_arg(B, "namespace", &args, 0, k8s_object_name)?;
    let mut cmd: Vec<&str> = vec!["get", "-o", "jsonpath={.items[*].metadata.name}"];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", "secrets"]);
    let text = kubectl_run(B, &cmd, K8S_MAX_JSON)?;
    let names: Vec<Value> = text
        .split_whitespace()
        .map(|s| Value::Str(s.to_string()))
        .collect();
    Ok(Value::Array(names))
}

// ---------------------------------------------------------------------------
// 865-866: bi_k8s_rollout_status / bi_k8s_rollout_restart
//
// `rollout status` is given its own deadline, so kubectl ends a rollout that
// never completes with a coded failure before the call's deadline kills it.
// ---------------------------------------------------------------------------
fn bi_k8s_rollout_status(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_rollout_status";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let name = k8s_need(B, "a deployment name", &args, 0, k8s_object_name)?;
    let ns = k8s_arg(B, "namespace", &args, 1, k8s_object_name)?;
    let target = format!("deployment/{name}");
    let mut cmd: Vec<&str> = vec!["rollout", "status", "--timeout=25s"];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", target.as_str()]);
    let text = kubectl_run(B, &cmd, K8S_MAX_TEXT)?;
    Ok(Value::Str(text.trim().to_string()))
}

fn bi_k8s_rollout_restart(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_rollout_restart";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let name = k8s_need(B, "a deployment name", &args, 0, k8s_object_name)?;
    let ns = k8s_arg(B, "namespace", &args, 1, k8s_object_name)?;
    let target = format!("deployment/{name}");
    let mut cmd: Vec<&str> = vec!["rollout", "restart"];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", target.as_str()]);
    let text = kubectl_run(B, &cmd, K8S_MAX_TEXT)?;
    Ok(Value::Str(text.trim().to_string()))
}

// ---------------------------------------------------------------------------
// 867: bi_k8s_scale - kubectl scale deployment/<name> --replicas=N [-n ns]
// ---------------------------------------------------------------------------
fn bi_k8s_scale(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_scale";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    let name = k8s_need(B, "a deployment name", &args, 0, k8s_object_name)?;
    let replicas = match args.get(1) {
        Some(Value::Int(n)) if (0..=K8S_MAX_REPLICAS).contains(n) => *n,
        Some(Value::Int(n)) => {
            return Err(crate::safety::arg_err(format!(
                "k8s_scale replicas must be in 0..={K8S_MAX_REPLICAS}, got {n}"
            )))
        }
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "k8s_scale replicas must be an Int, got {}",
                other.type_name()
            )))
        }
        None => {
            return Err(crate::safety::arg_err(
                "k8s_scale requires a replica count as second argument",
            ))
        }
    };
    let ns = k8s_arg(B, "namespace", &args, 2, k8s_object_name)?;
    let target = format!("deployment/{name}");
    let replicas_flag = format!("--replicas={replicas}");
    let mut cmd: Vec<&str> = vec!["scale", replicas_flag.as_str()];
    k8s_push_ns(&mut cmd, ns.as_deref());
    cmd.extend(["--", target.as_str()]);
    let text = kubectl_run(B, &cmd, K8S_MAX_TEXT)?;
    Ok(Value::Str(text.trim().to_string()))
}

// ---------------------------------------------------------------------------
// 868: bi_k8s_top_pods - kubectl top pods [-n namespace] (parsed table)
// ---------------------------------------------------------------------------
fn bi_k8s_top_pods(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_top_pods";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let ns = k8s_arg(B, "namespace", &args, 0, k8s_object_name)?;
    let mut cmd: Vec<&str> = vec!["top", "pods"];
    k8s_push_ns(&mut cmd, ns.as_deref());
    let text = kubectl_run(B, &cmd, K8S_MAX_TEXT)?;
    Ok(Value::Array(parse_kubectl_table(&text)))
}

// ---------------------------------------------------------------------------
// 869: bi_k8s_top_nodes - kubectl top nodes (parsed table)
// ---------------------------------------------------------------------------
fn bi_k8s_top_nodes(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("k8s_top_nodes", &input)?;
    k8s_max_args("k8s_top_nodes", &args, 0)?;
    let text = kubectl_run("k8s_top_nodes", &["top", "nodes"], K8S_MAX_TEXT)?;
    Ok(Value::Array(parse_kubectl_table(&text)))
}

// ---------------------------------------------------------------------------
// 870: bi_k8s_context - current-context (no argument) or use-context (a name)
// ---------------------------------------------------------------------------
fn bi_k8s_context(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "k8s_context";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let text = match k8s_arg(B, "a context name", &args, 0, k8s_token)? {
        Some(ctx) => kubectl_run(
            B,
            &["config", "use-context", "--", ctx.as_str()],
            K8S_MAX_TEXT,
        )?,
        None => kubectl_run(B, &["config", "current-context"], K8S_MAX_TEXT)?,
    };
    Ok(Value::Str(text.trim().to_string()))
}

// ---------------------------------------------------------------------------
// 871: bi_k8s_contexts - kubectl config get-contexts -o name
// ---------------------------------------------------------------------------
fn bi_k8s_contexts(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("k8s_contexts", &input)?;
    k8s_max_args("k8s_contexts", &args, 0)?;
    let text = kubectl_run(
        "k8s_contexts",
        &["config", "get-contexts", "-o", "name"],
        K8S_MAX_TEXT,
    )?;
    let contexts: Vec<Value> = text
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(contexts))
}

// ---------------------------------------------------------------------------
// 872: bi_k8s_cluster_info - kubectl cluster-info
// ---------------------------------------------------------------------------
fn bi_k8s_cluster_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("k8s_cluster_info", &input)?;
    k8s_max_args("k8s_cluster_info", &args, 0)?;
    let text = kubectl_run("k8s_cluster_info", &["cluster-info"], K8S_MAX_TEXT)?;
    Ok(Value::Str(text.trim().to_string()))
}

// ---------------------------------------------------------------------------
// 873: bi_helm_list - helm list [namespace] -o json
// ---------------------------------------------------------------------------
fn bi_helm_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "helm_list";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let ns = k8s_arg(B, "namespace", &args, 0, k8s_object_name)?;
    let mut cmd: Vec<String> = vec!["list".into(), "-o".into(), "json".into()];
    cmd.extend(helm_ns_flag(ns));
    let run = helm_call(B, &cmd, Keep::Head(TOOL_MAX_JSON), TOOL_DEADLINE_SECS)?;
    tool_json(B, run)
}

// ---------------------------------------------------------------------------
// 874 and 875: bi_helm_install / bi_helm_upgrade - helm <verb> [flags] -- release chart
// ---------------------------------------------------------------------------
fn helm_deploy(builtin: &str, verb: &str, args: &[Value], input: &Option<Value>) -> Result<Value> {
    k8s_no_input(builtin, input)?;
    k8s_max_args(builtin, args, 4)?;
    crate::safety::check_egress_unknown(
        builtin,
        "the chart's repository is named by helm's repo configuration, not the arguments",
    )?;
    let release = k8s_need(builtin, "a release name", args, 0, k8s_object_name)?;
    let chart = k8s_need(builtin, "a chart", args, 1, helm_chart)?;
    let ns = k8s_arg(builtin, "namespace", args, 2, k8s_object_name)?;
    let sets = helm_set_flags(builtin, args.get(3))?;
    let mut cmd: Vec<String> = vec![verb.into()];
    cmd.extend(helm_ns_flag(ns));
    cmd.extend(sets);
    cmd.extend(["--".into(), release, chart]);
    let run = helm_call(
        builtin,
        &cmd,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(builtin, run)?.trim().to_string()))
}

/// 874 – bi_helm_install: helm install <release> <chart> [namespace] [values]
fn bi_helm_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    helm_deploy("helm_install", "install", &args, &input)
}

/// 875 – bi_helm_upgrade: helm upgrade <release> <chart> [namespace] [values]
fn bi_helm_upgrade(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    helm_deploy("helm_upgrade", "upgrade", &args, &input)
}

// ---------------------------------------------------------------------------
// 876: bi_helm_uninstall - helm uninstall [namespace] -- release
// ---------------------------------------------------------------------------
fn bi_helm_uninstall(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "helm_uninstall";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let release = k8s_need(B, "a release name", &args, 0, k8s_object_name)?;
    let ns = k8s_arg(B, "namespace", &args, 1, k8s_object_name)?;
    let mut cmd: Vec<String> = vec!["uninstall".into()];
    cmd.extend(helm_ns_flag(ns));
    cmd.extend(["--".into(), release]);
    let run = helm_call(B, &cmd, Keep::Tail(TOOL_KEEP_TAIL), TOOL_LONG_DEADLINE_SECS)?;
    Ok(Value::Str(tool_text(B, run)?.trim().to_string()))
}

// ---------------------------------------------------------------------------
// 877: bi_helm_repos - helm repo list -o json
// ---------------------------------------------------------------------------
fn bi_helm_repos(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "helm_repos";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 0)?;
    let cmd: Vec<String> = vec!["repo".into(), "list".into(), "-o".into(), "json".into()];
    let run = helm_call(B, &cmd, Keep::Head(TOOL_MAX_JSON), TOOL_DEADLINE_SECS)?;
    // With no repository file helm exits 1 to say there is nothing to list.
    // That is an empty answer, not a failure.
    if !run.success && run.stderr.contains("no repositories to show") {
        return Ok(Value::Array(Vec::new()));
    }
    tool_json(B, run)
}

// ---------------------------------------------------------------------------
// 878: bi_helm_search - helm search repo <keyword> -o json
// ---------------------------------------------------------------------------
fn bi_helm_search(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "helm_search";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let keyword = k8s_need(B, "a keyword", &args, 0, k8s_token)?;
    // `search repo` reads the index of the repositories already added. It does
    // not contact the Artifact Hub; that search is deliberately not offered.
    let cmd: Vec<String> = vec![
        "search".into(),
        "repo".into(),
        "-o".into(),
        "json".into(),
        "--".into(),
        keyword,
    ];
    let run = helm_call(B, &cmd, Keep::Head(TOOL_MAX_JSON), TOOL_DEADLINE_SECS)?;
    tool_json(B, run)
}

// ---------------------------------------------------------------------------
// 879: bi_helm_status - helm status [namespace] -o json -- release
// ---------------------------------------------------------------------------
fn bi_helm_status(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "helm_status";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let release = k8s_need(B, "a release name", &args, 0, k8s_object_name)?;
    let ns = k8s_arg(B, "namespace", &args, 1, k8s_object_name)?;
    let mut cmd: Vec<String> = vec!["status".into(), "-o".into(), "json".into()];
    cmd.extend(helm_ns_flag(ns));
    cmd.extend(["--".into(), release]);
    let run = helm_call(B, &cmd, Keep::Head(TOOL_MAX_JSON), TOOL_DEADLINE_SECS)?;
    tool_json(B, run)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Run a command, return stdout on success or an error with stderr.
fn vm_run_cmd(program: &str, args: &[&str]) -> Result<String> {
    let mut cmd = crate::safety::child_command(program);
    cmd.args(args);
    // A deadline is a budget, not a missing tool, so it keeps its own code.
    let output = crate::safety::output_with_timeout(cmd, TOOL_DEADLINE_SECS).map_err(|e| {
        match crate::safety::io_budget_error(&e) {
            Some(coded) => coded,
            None if e.kind() == std::io::ErrorKind::TimedOut => {
                crate::safety::spawn_error(program, program, &e)
            }
            None => crate::safety::tool_missing(program, program, &e.to_string()),
        }
    })?;
    if !output.status.success() {
        return Err(crate::safety::tool_failed(
            program,
            &format!("{} {}", program, args.join(" ")),
            output.status.code(),
            &String::from_utf8_lossy(&output.stderr),
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Run a command, parse stdout as JSON, and convert to Value.
fn vm_run_cmd_json(program: &str, args: &[&str]) -> Result<Value> {
    let text = vm_run_cmd(program, args)?;
    if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
        Ok(json_to_value(json))
    } else {
        Ok(Value::Str(text.trim().to_string()))
    }
}

/// Run a PowerShell command and return stdout.
fn vm_run_powershell(script: &str) -> Result<String> {
    vm_run_cmd("powershell", &["-NoProfile", "-Command", script])
}

/// Run a PowerShell command that produces JSON and parse it.
fn vm_run_powershell_json(script: &str) -> Result<Value> {
    let text = vm_run_powershell(script)?;
    if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
        Ok(json_to_value(json))
    } else {
        Ok(Value::Str(text.trim().to_string()))
    }
}

/// Parse virsh / tabular output into Vec<Value::Record>.
fn parse_virsh_table(text: &str) -> Vec<Value> {
    let mut lines: Vec<&str> = text.lines().collect();
    // virsh usually has a header line, then a separator "---...", then data
    if lines.len() < 2 {
        return Vec::new();
    }
    // Find header
    let header_line = lines.remove(0).trim();
    let headers: Vec<String> = header_line
        .split_whitespace()
        .map(|h| h.to_lowercase())
        .collect();
    // Skip separator line(s) that start with dashes
    while !lines.is_empty() && lines[0].trim().starts_with('-') {
        lines.remove(0);
    }
    let mut rows = Vec::new();
    for line in &lines {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let cols: Vec<&str> = trimmed
            .splitn(headers.len(), char::is_whitespace)
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect();
        let mut record = std::collections::BTreeMap::new();
        for (i, hdr) in headers.iter().enumerate() {
            let val = cols.get(i).unwrap_or(&"").to_string();
            record.insert(hdr.clone(), Value::Str(val));
        }
        rows.push(Value::Record(record));
    }
    rows
}

/// Parse WSL --list --verbose tabular output into Vec<Value::Record>.
fn parse_wsl_list(text: &str) -> Vec<Value> {
    let mut lines: Vec<&str> = text.lines().collect();
    if lines.is_empty() {
        return Vec::new();
    }
    // First line is header: "  NAME   STATE   VERSION"
    lines.remove(0); // skip header
    let mut rows = Vec::new();
    for line in &lines {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        // Default distro has a leading '*'
        let cleaned = trimmed.trim_start_matches('*').trim();
        let cols: Vec<&str> = cleaned.split_whitespace().collect();
        if cols.len() >= 3 {
            let mut record = std::collections::BTreeMap::new();
            record.insert("name".to_string(), Value::Str(cols[0].to_string()));
            record.insert("state".to_string(), Value::Str(cols[1].to_string()));
            record.insert("version".to_string(), Value::Str(cols[2].to_string()));
            record.insert("default".to_string(), Value::Bool(trimmed.starts_with('*')));
            rows.push(Value::Record(record));
        }
    }
    rows
}

/// Require a string argument at the given position.
fn require_str(args: &[Value], idx: usize, name: &str) -> Result<String> {
    match args.get(idx) {
        Some(Value::Str(s)) => Ok(s.clone()),
        _ => Err(crate::safety::arg_err(format!(
            "{} requires a string argument",
            name
        ))),
    }
}

/// Whether a detection probe's tool ran and exited 0. A tool that is not
/// installed is `false`. A probe that could not run (a spawn failure, or no
/// answer before the deadline) is an error: it used to fall through to "none",
/// which is a claim that no hypervisor exists.
fn hypervisor_probe_ok(tool: &str, cmd: std::process::Command) -> Result<bool> {
    match bounded_cmd_output("detect_hypervisor", tool, cmd, PROBE_DEADLINE_SECS) {
        Ok(o) => Ok(o.status.success()),
        Err(e) if is_tool_missing(&e) => Ok(false),
        Err(e) => Err(e),
    }
}

/// Detect available hypervisor on the current platform.
/// Returns one of: "hyperv", "virsh", "vboxmanage", "none"
fn detect_hypervisor() -> Result<&'static str> {
    #[cfg(target_os = "windows")]
    {
        // On Windows, prefer Hyper-V
        let mut cmd = crate::safety::child_command("powershell");
        cmd.args([
            "-NoProfile",
            "-Command",
            "Get-Command Get-VM -ErrorAction SilentlyContinue",
        ]);
        if hypervisor_probe_ok("powershell", cmd)? {
            return Ok("hyperv");
        }
    }
    // Try virsh (Linux / macOS with libvirt)
    let mut cmd = crate::safety::child_command("virsh");
    cmd.arg("version");
    if hypervisor_probe_ok("virsh", cmd)? {
        return Ok("virsh");
    }
    // Try VBoxManage
    let mut cmd = crate::safety::child_command("VBoxManage");
    cmd.arg("--version");
    if hypervisor_probe_ok("VBoxManage", cmd)? {
        return Ok("vboxmanage");
    }
    Ok("none")
}

// ============================================================================
// Cloud & Infrastructure-as-Code Builtins (920-949)
// Terraform, Ansible, Pulumi, Vagrant, Packer, AWS, Azure, GCloud
// ============================================================================

// [removed duplicate] use std::collections::BTreeMap;
// [removed duplicate] use std::process::Command;
// [removed duplicate] use anyhow::{anyhow, Result};

// [removed duplicate] use crate::value::Value;
// [removed duplicate] use crate::builtins::json_to_value;

// ---------------------------------------------------------------------------
// Ansible, cloud, container-scan, forge (gh, glab), rsync and package helpers.
// Every value a tool receives as an argument passes one of these first, and a
// call that does not match is refused before any process starts.
// ---------------------------------------------------------------------------

/// The longest image, transport or remote reference a builtin passes on.
const OPS_MAX_REF: usize = 512;
/// The longest event or subcommand name.
const OPS_MAX_NAME: usize = 64;
/// The longest command string a remote node would be sent.
const OPS_MAX_COMMAND: usize = 8192;
/// The transports skopeo may copy from or inspect. Each names a registry or a
/// local store; none runs a program.
const OPS_TRANSPORTS: &[&str] = &[
    "docker://",
    "docker-daemon:",
    "containers-storage:",
    "docker-archive:",
    "oci-archive:",
    "oci:",
    "dir:",
];
/// The transports whose reference is a local path, which must lie in the workspace.
const OPS_LOCAL_TRANSPORTS: &[&str] = &["docker-archive:", "oci-archive:", "oci:", "dir:"];
/// Forge flags that open an editor or a browser. A call here must not open either.
const OPS_FORGE_REFUSED_FLAGS: &[&str] = &["--editor", "-e", "--web", "-w", "--browser"];
/// Forge subcommands that change a remote.
const OPS_FORGE_WRITE_VERBS: &[&str] = &[
    "close", "comment", "create", "edit", "note", "ready", "reopen", "update",
];
/// The subcommands `gh pr` accepts. Merge, review and checkout are not offered.
const GH_PR_VERBS: &[&str] = &[
    "checks", "close", "comment", "create", "diff", "edit", "list", "ready", "reopen", "status",
    "view",
];
/// The subcommands `gh issue` accepts. Delete, transfer, pin and lock are not offered.
const GH_ISSUE_VERBS: &[&str] = &[
    "close", "comment", "create", "edit", "list", "reopen", "status", "view",
];
/// The subcommands `gh repo` accepts. Every one that changes a repository is refused.
const GH_REPO_VERBS: &[&str] = &["list", "view"];
/// The subcommands `glab mr` accepts. Merge and approve are not offered.
const GLAB_MR_VERBS: &[&str] = &[
    "close", "create", "diff", "list", "note", "reopen", "update", "view",
];
/// The subcommands `glab issue` accepts. Delete is not offered.
const GLAB_ISSUE_VERBS: &[&str] = &[
    "close", "create", "list", "note", "reopen", "update", "view",
];

/// A cloud call's error for an operation no provider client backs.
fn cloud_unimplemented(builtin: &str) -> anyhow::Error {
    crate::safety::unimplemented(
        builtin,
        "no cloud provider is wired into IronShell, so nothing was created, changed or read",
        "use the provider's own CLI or API",
    )
}

/// The Record a cloud builtin takes as options: each key one it names, each
/// value a String. Anything else is refused rather than dropped.
fn cloud_options(builtin: &str, value: Option<&Value>, keys: &[&str]) -> Result<()> {
    let opts = match value {
        None => return Ok(()),
        Some(Value::Record(map)) => map,
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: options must be a Record, got {}",
                other.type_name()
            )))
        }
    };
    for (key, value) in opts {
        if !keys.contains(&key.as_str()) {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: unknown option {key:?}; the options are {}",
                keys.join(", ")
            )));
        }
        match value {
            Value::Str(s) if !s.contains('\0') => {}
            other => {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: option {key} must be a String, got {}",
                    other.type_name()
                )))
            }
        }
    }
    Ok(())
}

/// A container image reference: letters, digits and `._-/:@+`, never a leading
/// `-`. The set has no spaces, quotes or separators a tool would split on.
fn ops_image_ref(builtin: &str, what: &str, value: &str) -> Result<String> {
    let reference = pkg_plain(builtin, what, value)?;
    let well_formed = reference.len() <= OPS_MAX_REF
        && reference
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "._-/:@+".contains(c));
    if !well_formed {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is letters, digits and ._-/:@+, at most {OPS_MAX_REF} characters (got {reference:?})"
        )));
    }
    Ok(reference)
}

/// A skopeo reference that begins with a transport. A local transport's path
/// must lie inside the workspace; a registry or daemon reference is checked as
/// an image reference.
fn ops_transport(builtin: &str, what: &str, value: &str) -> Result<String> {
    let text = pkg_plain(builtin, what, value)?;
    if text.len() > OPS_MAX_REF {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is longer than {OPS_MAX_REF} characters"
        )));
    }
    let Some(&prefix) = OPS_TRANSPORTS.iter().find(|p| text.starts_with(**p)) else {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} {text:?} must name a transport: docker://, docker-daemon:, containers-storage:, docker-archive:, oci-archive:, oci: or dir:"
        )));
    };
    let rest = &text[prefix.len()..];
    if OPS_LOCAL_TRANSPORTS.contains(&prefix) {
        // `oci:path:tag`: a colon past a drive letter (index 1) starts the tag.
        let path = match rest.rfind(':') {
            Some(at) if at > 1 => &rest[..at],
            _ => rest,
        };
        if path.is_empty() {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: {what} {text:?} names no path"
            )));
        }
        pkg_inside(builtin, path)?;
    } else {
        ops_image_ref(builtin, what, rest)?;
    }
    Ok(text)
}

/// A local path an ops tool reads or writes: a plain value, never a URL, and
/// inside the workspace.
fn ops_local_path(builtin: &str, what: &str, value: &str) -> Result<String> {
    let path = pkg_plain(builtin, what, value)?;
    if path.contains("://") {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} {path:?} is a URL; name a local path inside the workspace"
        )));
    }
    pkg_inside(builtin, &path)?;
    Ok(path)
}

/// A local path that must exist: a file, or a directory when `file` is false.
fn ops_existing_local(builtin: &str, what: &str, value: &str, file: bool) -> Result<String> {
    let path = ops_local_path(builtin, what, value)?;
    let base = std::env::current_dir().unwrap_or_else(|_| workspace_root_abs());
    let full = workspace_path(builtin, &path, &base)?;
    let present = if file { full.is_file() } else { full.exists() };
    if !present {
        return Err(crate::safety::not_found(builtin, what, &path));
    }
    Ok(path)
}

/// A playbook: an existing file inside the workspace.
fn ops_playbook(builtin: &str, what: &str, value: &str) -> Result<String> {
    ops_existing_local(builtin, what, value, true)
}

/// An inventory: an existing file or directory inside the workspace. An inline
/// host list such as `host1,` is not a path and does not exist, so it is refused.
fn ops_inventory(builtin: &str, what: &str, value: &str) -> Result<String> {
    ops_existing_local(builtin, what, value, false)
}

/// A vault file: an existing file inside the workspace.
fn ops_vault_file(builtin: &str, what: &str, value: &str) -> Result<String> {
    ops_existing_local(builtin, what, value, true)
}

/// A directory to scan: an existing path inside the workspace.
fn ops_scan_dir(builtin: &str, what: &str, value: &str) -> Result<String> {
    ops_existing_local(builtin, what, value, false)
}

/// The action `ansible-vault` runs. Only the three named actions are passed on.
fn ops_vault_action(builtin: &str, what: &str, value: &str) -> Result<String> {
    match value {
        "view" | "encrypt" | "decrypt" => Ok(value.to_string()),
        other => Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be view, encrypt or decrypt (got {other:?})"
        ))),
    }
}

/// An event or workflow name: letters, digits, `_` and `-`.
fn ops_event(builtin: &str, what: &str, value: &str) -> Result<String> {
    let event = pkg_plain(builtin, what, value)?;
    if event.len() > OPS_MAX_NAME
        || !event
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is letters, digits, '_' and '-', at most {OPS_MAX_NAME} characters (got {event:?})"
        )));
    }
    Ok(event)
}

/// Whether an rsync operand names a remote host: a colon before any separator,
/// other than a drive letter's colon at index 1.
fn ops_is_remote(value: &str) -> bool {
    let cut = value.find(['/', '\\']).unwrap_or(value.len());
    value[..cut].find(':').is_some_and(|at| at > 1)
}

/// An rsync operand: a local path inside the workspace, or `[user@]host:path` /
/// `host::module` with a plain host name. A URL is refused, and so is any host
/// that begins with `-`, which ssh would read as an option.
fn ops_sync_path(builtin: &str, what: &str, value: &str) -> Result<String> {
    let text = pkg_plain(builtin, what, value)?;
    if text.contains("://") {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} {text:?} is a URL; rsync reaches a host as [user@]host:path"
        )));
    }
    if !ops_is_remote(&text) {
        return ops_local_path(builtin, what, &text);
    }
    let colon = text.find(':').unwrap_or(0);
    let host = text[..colon].rsplit('@').next().unwrap_or("");
    let well_formed = !host.is_empty()
        && !host.starts_with('-')
        && host
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "._-".contains(c));
    if !well_formed {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} names host {host:?}, which must be a plain host name"
        )));
    }
    Ok(text)
}

/// The rsync options Record as flags. No Record means `-az`. A key that is not
/// named, or a value of the wrong type, is refused rather than dropped.
fn rsync_flags(builtin: &str, value: Option<&Value>) -> Result<Vec<String>> {
    let Some(value) = value else {
        return Ok(vec!["-az".to_string()]);
    };
    let Value::Record(opts) = value else {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: options must be a Record, got {}",
            value.type_name()
        )));
    };
    const FLAGS: [(&str, &str); 5] = [
        ("archive", "-a"),
        ("compress", "-z"),
        ("delete", "--delete"),
        ("verbose", "-v"),
        ("progress", "--progress"),
    ];
    for key in opts.keys() {
        if key != "exclude" && !FLAGS.iter().any(|(name, _)| key == name) {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: unknown option {key:?}; the options are archive, compress, delete, verbose, progress and exclude"
            )));
        }
    }
    let mut flags = Vec::new();
    for (key, flag) in FLAGS {
        match opts.get(key) {
            None | Some(Value::Bool(false)) => {}
            Some(Value::Bool(true)) => flags.push(flag.to_string()),
            Some(other) => {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: option {key} must be a Bool, got {}",
                    other.type_name()
                )))
            }
        }
    }
    match opts.get("exclude") {
        None => {}
        Some(Value::Str(pattern)) => {
            let pattern = pkg_plain(builtin, "exclude pattern", pattern)?;
            flags.push("--exclude".to_string());
            flags.push(pattern);
        }
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: option exclude must be a String, got {}",
                other.type_name()
            )))
        }
    }
    Ok(flags)
}

/// `--extra-vars` JSON from a Record of scalars. A key must be an identifier.
/// A nested value is refused rather than turned into its display text.
fn ops_extra_vars(builtin: &str, value: Option<&Value>) -> Result<Option<String>> {
    let map = match value {
        None => return Ok(None),
        Some(Value::Record(map)) => map,
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: extra_vars must be a Record, got {}",
                other.type_name()
            )))
        }
    };
    if map.len() > PKG_MAX_ITEMS {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: at most {PKG_MAX_ITEMS} extra variables, got {}",
            map.len()
        )));
    }
    let mut object = serde_json::Map::new();
    for (key, value) in map {
        let well_formed = key.len() <= OPS_MAX_NAME
            && key
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
            && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
        if !well_formed {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: a variable name is an identifier of letters, digits and '_' (got {key:?})"
            )));
        }
        let json = match value {
            Value::Str(s) if !s.contains('\0') => serde_json::Value::String(s.clone()),
            Value::Int(n) => serde_json::Value::from(*n),
            Value::Float(f) if f.is_finite() => serde_json::json!(*f),
            Value::Bool(b) => serde_json::Value::Bool(*b),
            other => {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: the value for {key} must be a String, Int, Float or Bool, got {}",
                    other.type_name()
                )))
            }
        };
        object.insert(key.clone(), json);
    }
    serde_json::to_string(&serde_json::Value::Object(object))
        .map(Some)
        .map_err(|e| crate::safety::arg_err(format!("{builtin}: extra_vars: {e}")))
}

/// Whether a forge flag is one this builtin refuses (an editor or browser flag,
/// bare or with a value).
fn ops_forge_flag_refused(flag: &str) -> bool {
    OPS_FORGE_REFUSED_FLAGS
        .iter()
        .any(|refused| flag == *refused || flag.starts_with(&format!("{refused}=")))
}

/// A forge call (gh or glab): one of `verbs` under `group`, then the flags and
/// values that follow it. A read verb is bounded and deadline'd. A write verb
/// changes a remote; the central Network gate asks for approval in agent mode, and it
/// gets the longer deadline.
fn ops_forge(
    builtin: &str,
    program: &str,
    group: &str,
    verbs: &[&str],
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    k8s_no_input(builtin, input)?;
    let verb =
        k8s_arg(builtin, "subcommand", args, 0, pkg_plain)?.unwrap_or_else(|| "list".to_string());
    if !verbs.contains(&verb.as_str()) {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: subcommand must be one of {}, got {verb:?}",
            verbs.join(", ")
        )));
    }
    let extra = pkg_trailing(builtin, args.get(1..).unwrap_or(&[]))?;
    if let Some(flag) = extra.iter().find(|a| ops_forge_flag_refused(a.as_str())) {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {flag:?} opens an editor or a browser, which this builtin does not run"
        )));
    }
    let writes = OPS_FORGE_WRITE_VERBS.contains(&verb.as_str());
    let mut argv: Vec<&str> = vec![group, verb.as_str()];
    argv.extend(extra.iter().map(String::as_str));
    let run = if writes {
        tool_run(
            builtin,
            program,
            None,
            &argv,
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?
    } else {
        tool_run(
            builtin,
            program,
            None,
            &argv,
            Keep::Head(TOOL_MAX_TEXT),
            TOOL_DEADLINE_SECS,
        )?
    };
    pkg_done(builtin, run, vec![("subcmd", Value::Str(verb))])
}

// ===========================================================================
// Terraform (951-958)
// ===========================================================================

/// Why the terraform builtins that reach a provider or backend fail closed under an
/// egress allowlist: the endpoints come from the configuration, not the arguments.
const TF_EGRESS_REASON: &str =
    "providers and backends are named by the configuration in the directory, not the arguments";

/// Why the package-manager builtins that fetch from the network fail closed under
/// an egress allowlist: the sources are the system's configured repositories
/// (apt sources, winget sources), not the arguments.
const PKG_EGRESS_REASON: &str =
    "the package manager fetches from its configured sources, which the arguments do not name";

/// 951 – terraform_init([dir]): terraform init -input=false -no-color in dir.
/// Downloads the providers the configuration names.
fn bi_terraform_init(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "terraform_init";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    crate::safety::check_egress_unknown(B, TF_EGRESS_REASON)?;
    let dir = tf_dir(B, k8s_arg(B, "directory", &args, 0, tf_plain)?.as_deref())?;
    let run = tf_call(
        B,
        &dir,
        &["init", "-input=false", "-no-color"],
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(B, run)?.trim().to_string()))
}

/// 952 – terraform_plan([var_file]): terraform plan in the workspace root.
fn bi_terraform_plan(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "terraform_plan";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    crate::safety::check_egress_unknown(B, TF_EGRESS_REASON)?;
    let var = tf_var_file(B, &args, 0)?;
    let root = tf_dir(B, None)?;
    let mut cmd: Vec<&str> = vec!["plan", "-input=false", "-no-color"];
    if let Some(flag) = var.as_deref() {
        cmd.push(flag);
    }
    let run = tf_call(
        B,
        &root,
        &cmd,
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(B, run)?.trim().to_string()))
}

/// 953 – terraform_apply([var_file]): terraform apply -auto-approve in the
/// workspace root. Changes infrastructure; agent mode needs approval first
/// (the call is Exec under the central guard).
fn bi_terraform_apply(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "terraform_apply";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    crate::safety::check_egress_unknown(B, TF_EGRESS_REASON)?;
    let var = tf_var_file(B, &args, 0)?;
    let root = tf_dir(B, None)?;
    let mut cmd: Vec<&str> = vec!["apply", "-input=false", "-no-color", "-auto-approve"];
    if let Some(flag) = var.as_deref() {
        cmd.push(flag);
    }
    let run = tf_call(
        B,
        &root,
        &cmd,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(B, run)?.trim().to_string()))
}

/// 923 – terraform_destroy([dir]): terraform destroy -auto-approve in dir.
/// `-auto-approve` means Terraform never asks, so the approval has to happen
/// here. The directory is resolved and checked against the workspace first, so
/// the approval names the directory that will actually be destroyed.
fn bi_terraform_destroy(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "terraform_destroy";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let dir = tf_dir(B, k8s_arg(B, "directory", &args, 0, tf_plain)?.as_deref())?;
    let shown = dir.display().to_string();
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: B,
        effect: crate::safety::Effect::Destructive,
        what: B,
        targets: vec![shown.clone()],
        blast_radius: serde_json::json!({ "dir": shown, "auto_approve": true }),
        reversible: false,
        fs_paths: false,
    })?;
    let run = tf_call(
        B,
        &dir,
        &["destroy", "-input=false", "-no-color", "-auto-approve"],
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(B, run)?.trim().to_string()))
}

/// 924 – terraform_state([dir]): terraform state list, one Array element per resource.
fn bi_terraform_state(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "terraform_state";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    crate::safety::check_egress_unknown(B, TF_EGRESS_REASON)?;
    let dir = tf_dir(B, k8s_arg(B, "directory", &args, 0, tf_plain)?.as_deref())?;
    let run = tf_call(
        B,
        &dir,
        &["state", "list"],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let text = tool_text(B, run)?;
    let items: Vec<Value> = text
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(|l| Value::Str(l.to_string()))
        .collect();
    Ok(Value::Array(items))
}

/// 925 – terraform_output([dir]): terraform output -json as a Record.
fn bi_terraform_output(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "terraform_output";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    crate::safety::check_egress_unknown(B, TF_EGRESS_REASON)?;
    let dir = tf_dir(B, k8s_arg(B, "directory", &args, 0, tf_plain)?.as_deref())?;
    let run = tf_call(
        B,
        &dir,
        &["output", "-json"],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    tool_json(B, run)
}

/// 926 – terraform_workspace([name]): no name shows the current workspace;
/// a name selects it.
fn bi_terraform_workspace(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "terraform_workspace";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let root = tf_dir(B, None)?;
    let run = match k8s_arg(B, "workspace name", &args, 0, tf_workspace_name)? {
        Some(name) => {
            // `workspace select` checks the name against the backend's workspaces.
            // `workspace show` reads .terraform/environment and stays local.
            crate::safety::check_egress_unknown(B, TF_EGRESS_REASON)?;
            tf_call(
                B,
                &root,
                &["workspace", "select", name.as_str()],
                Keep::Head(TOOL_MAX_TEXT),
                TOOL_DEADLINE_SECS,
            )?
        }
        None => tf_call(
            B,
            &root,
            &["workspace", "show"],
            Keep::Head(TOOL_MAX_TEXT),
            TOOL_DEADLINE_SECS,
        )?,
    };
    Ok(Value::Str(tool_text(B, run)?.trim().to_string()))
}

/// 927 – terraform_validate([dir]): terraform validate -json as a Record. An
/// invalid configuration is an answer: its diagnostics come back with
/// `valid: false`, not as a failure.
fn bi_terraform_validate(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "terraform_validate";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let dir = tf_dir(B, k8s_arg(B, "directory", &args, 0, tf_plain)?.as_deref())?;
    let run = tf_call(
        B,
        &dir,
        &["validate", "-json"],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    if !run.success {
        if let Ok(json) = serde_json::from_str::<serde_json::Value>(&run.stdout) {
            if json.get("valid").is_some() {
                return Ok(json_to_value(json));
            }
        }
    }
    tool_json(B, run)
}

// ===========================================================================
// Ansible (928-931)
// ===========================================================================

/// 928 – ansible_playbook(playbook, [inventory], [extra_vars]): ansible-playbook
/// on a playbook inside the workspace, returning the tail of its output. The
/// playbook and inventory must exist inside the workspace, so an inline host
/// list is refused. extra_vars travel on the command line, where other local
/// users can read them in a process listing: keep secrets in a vault file.
/// Runs with a 15 minute deadline; a nonzero exit is E_TOOL_FAILED.
fn bi_ansible_playbook(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ansible_playbook";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    crate::safety::check_egress_unknown(
        B,
        "the hosts it connects to are named by the inventory and playbook, not the arguments",
    )?;
    let playbook = k8s_need(B, "a playbook path", &args, 0, ops_playbook)?;
    let mut argv: Vec<String> = vec![playbook];
    if let Some(inventory) = k8s_arg(B, "inventory", &args, 1, ops_inventory)? {
        argv.push("-i".to_string());
        argv.push(inventory);
    }
    if let Some(vars) = ops_extra_vars(B, args.get(2))? {
        argv.push("--extra-vars".to_string());
        argv.push(vars);
    }
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = tool_run(
        B,
        "ansible-playbook",
        None,
        &refs,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(B, run)?.trim().to_string()))
}

/// 929 – ansible_inventory(inventory): ansible-inventory --list for an inventory
/// inside the workspace, as JSON.
fn bi_ansible_inventory(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ansible_inventory";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let inventory = k8s_need(B, "an inventory path", &args, 0, ops_inventory)?;
    let run = tool_run(
        B,
        "ansible-inventory",
        None,
        &["--list", "-i", inventory.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    tool_json(B, run)
}

/// 930 – ansible_galaxy(role): ansible-galaxy install for a role name, a
/// registry spec or a path inside the workspace. A registry or URL spec is
/// fetched from the network. A `file:` or `link:` spec is refused.
fn bi_ansible_galaxy(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ansible_galaxy";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    crate::safety::check_egress_unknown(
        B,
        "a registry role is fetched from the galaxy server ansible is configured with, not the argument",
    )?;
    let role = k8s_need(B, "a role name", &args, 0, pkg_spec)?;
    let run = tool_run(
        B,
        "ansible-galaxy",
        None,
        &["install", role.as_str()],
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(B, run)?.trim().to_string()))
}

/// 931 – ansible_vault(action, file): ansible-vault view, encrypt or decrypt on
/// a file inside the workspace. `view` returns the decrypted text as the
/// answer, so a secret reaches the caller; `decrypt` leaves the file in plain
/// text. No vault password is accepted or placed on the command line. Where no
/// password source is configured, ansible-vault prompts on the terminal, and
/// the deadline bounds that wait.
fn bi_ansible_vault(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ansible_vault";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let action = k8s_need(
        B,
        "an action (view, encrypt or decrypt)",
        &args,
        0,
        ops_vault_action,
    )?;
    let file = k8s_need(B, "a vault file path", &args, 1, ops_vault_file)?;
    let run = tool_run(
        B,
        "ansible-vault",
        None,
        &[action.as_str(), file.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    Ok(Value::Str(tool_text(B, run)?))
}

// ============================================================================
// Core OS Builtins (950-979)
// File ops, block devices, kernel, system monitoring, diagnostics
// ============================================================================

// [removed duplicate] use std::collections::BTreeMap;
// [removed duplicate] use std::process::Command;
// [removed duplicate] use anyhow::{anyhow, Result};

// Assumes these are defined elsewhere in the crate:
// pub enum Value { Str(String), Int(i64), Float(f64), Bool(bool), Array(Vec<Value>), Record(BTreeMap<String,Value>), Null }
// fn json_to_value(json: serde_json::Value) -> Value;

/// cd(path) - Change the process working directory.
///
/// The catalog has advertised this with a full signature and an example --
/// `cd(path: String) -> String`, category FileSystem -- and there was no
/// implementation anywhere. `pwd()` worked, so the shell could report its
/// directory and not change it, and `shell.cd(...)` dispatched to a builtin
/// that did not exist.
///
/// Guarded with `fs_paths: true` deliberately. The working directory decides
/// what every later relative path means, so an unguarded `cd` is a way out of
/// the workspace jail: `cd("..")` then `write("secrets")` would otherwise land
/// outside a root the agent was confined to.
///
/// `WriteLocal` rather than `Pure`: it modifies process state, and `pwd()`
/// returns a different answer afterwards. Classifying it `Pure` would tell an
/// agent the call is referentially transparent and safe to reorder, which is
/// the one thing it certainly is not.
fn bi_cd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("cd", &input)?;
    k8s_max_args("cd", &args, 1)?;
    let raw = match args.first() {
        Some(Value::Str(s)) if !s.is_empty() => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "cd",
                "path: a non-empty String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let path = crate::safety::resolve_path_str(&raw);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "cd",
        effect: crate::safety::Effect::WriteLocal,
        what: "change directory",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({ "cwd": true }),
        reversible: true,
        fs_paths: true,
    })?;
    std::env::set_current_dir(&path).map_err(|e| crate::safety::fs_error("cd", &path, &e))?;
    let now = std::env::current_dir()
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or(path);
    Ok(Value::Str(now))
}

/// An optional Bool flag argument. A value of any other type used to read as
/// false, so `rm(p, "yes")` was a plain `rm` that said nothing about it.
fn fs_flag(builtin: &str, what: &str, value: Option<&Value>) -> Result<bool> {
    match value {
        None => Ok(false),
        Some(Value::Bool(b)) => Ok(*b),
        Some(other) => Err(crate::safety::bad_arg(
            builtin,
            &format!("{what}: Bool"),
            other.type_name(),
        )),
    }
}

/// 950: bi_rm - Remove one file. Args: path (string), optional force bool.
pub fn bi_rm(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("rm", &input)?;
    k8s_max_args("rm", &args, 2)?;
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "rm",
                "path: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let force = fs_flag("rm", "force", args.get(1))?;
    let written = path.clone();
    // Jailed: relative paths are workspace-relative; resolve before the jail check
    // so the guard validates the path that is actually deleted.
    let path = crate::safety::resolve_path_str(&path);
    // In agent mode, a plain removal of a path that is not there is answered
    // E_NOT_FOUND before the approval gate. The gate asked for a token to
    // delete something that does not exist, and approving it changed nothing.
    // Only inside the workspace (the jail still answers for anything outside
    // it), and only when nothing is at the path: a path that exists goes
    // through the gate as before. `force` keeps its meaning and still goes
    // through the gate, since it is a success for an absent file.
    if !force
        && matches!(crate::safety::current_mode(), crate::safety::Mode::Agent)
        && crate::safety::within_workspace(&path)
        && std::fs::symlink_metadata(&path).is_err()
    {
        // The attempt is still a decision the audit log should record.
        let _ = crate::safety::audit(
            "rm",
            crate::safety::Effect::Destructive,
            "not_found",
            &path,
            serde_json::json!({}),
        );
        return Err(crate::safety::not_found("rm", "file", &path));
    }
    // Reversible exactly when the journal keeps this file's bytes for undo: the
    // journal is on (agent mode) and the file is one it can capture.
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "rm",
        effect: crate::safety::Effect::Destructive,
        what: "delete",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({ "files": 1 }),
        reversible: crate::journal::would_capture(&path),
        fs_paths: true,
    })?;
    // A directory is not a file: remove_file on one answered E_OS_DENIED with a
    // permissions hint. Refused after the gate, which is unchanged, and before
    // the OS call. A symlink is not followed here, so a link still removes itself.
    if !crate::safety::names_a_remote_share(&path)
        && std::fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir())
    {
        return Err(crate::safety::bad_arg_with_hint(
            "rm",
            "a file path",
            "a directory",
            &format!("'{written}' is a directory; remove it with rmdir(\"{written}\", true)"),
        ));
    }
    crate::tx::snapshot(&path); // record pre-delete state if a transaction is active
                                // `force` excuses a file that is already gone, as `rm -f` does, and nothing
                                // else. It used to turn every failure -- a directory, a locked file, a
                                // permission refusal -- into a success string, so a delete that did not
                                // happen read as one that had.
    match std::fs::remove_file(&path) {
        Ok(()) => Ok(Value::Str(format!("removed: {}", path))),
        Err(e) if force && e.kind() == std::io::ErrorKind::NotFound => {
            Ok(Value::Str(format!("already absent: {}", path)))
        }
        Err(e) => Err(crate::safety::fs_error("rm", &path, &e)),
    }
}

/// 951: bi_rmdir - Remove directory. Args: path, optional recursive bool.
pub fn bi_rmdir(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("rmdir", &input)?;
    k8s_max_args("rmdir", &args, 2)?;
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "rmdir",
                "path: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let recursive = fs_flag("rmdir", "recursive", args.get(1))?;
    // Jailed: relative paths are workspace-relative (resolve before the jail check).
    let path = crate::safety::resolve_path_str(&path);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "rmdir",
        effect: crate::safety::Effect::Destructive,
        what: "delete",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({ "recursive": recursive }),
        reversible: false,
        fs_paths: true,
    })?;
    // An empty directory is recorded as one that undo recreates. A directory
    // with anything in it is recorded as irreversible, so that undo reports it
    // as not reversed and never reaches past it to an earlier step. A failed
    // removal leaves no step.
    crate::journal::record_removed_directory(
        "rmdir",
        crate::safety::Effect::Destructive,
        &path,
        &format!(
            "a directory removal is not journaled: {path} and what it held cannot be restored by undo"
        ),
    );
    crate::tx::snapshot(&path); // back up the directory tree if a transaction is active
                                // `remove_dir_all` removes a symbolic link rather than following it, so a
                                // link inside the workspace to a directory outside it is not a way out.
    if recursive {
        std::fs::remove_dir_all(&path).map_err(|e| crate::safety::fs_error("rmdir", &path, &e))?;
    } else {
        std::fs::remove_dir(&path).map_err(|e| crate::safety::fs_error("rmdir", &path, &e))?;
    }
    Ok(Value::Str(format!("removed directory: {}", path)))
}

/// 952: bi_touch - Create empty file or update timestamp. Args: path.
fn bi_touch(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("touch: expected path string")),
    };
    // Opening with create+write and writing nothing does not change an
    // existing file's modification time, so this did not touch anything
    // that already existed; errors were uncoded. It also skipped the
    // workspace jail the other writers go through.
    let path = guard_local_write("touch", &path)?;
    crate::safety::refuse_hard_linked_write("touch", &path)?;
    // An existing file gets only its timestamp changed, so its metadata is what
    // is recorded; a file this call creates is recorded as absent so rollback
    // removes it.
    if std::path::Path::new(&path).exists() {
        crate::tx::snapshot_metadata(&path);
    } else {
        crate::tx::snapshot(&path);
    }
    // A directory is touched like a file is: its time changes. Opening it to
    // append failed with "is a directory".
    let file = if std::path::Path::new(&path).is_dir() {
        crate::tx::open_for_times(std::path::Path::new(&path))
            .map_err(|e| crate::safety::fs_error("touch", &path, &e))
    } else {
        crate::safety::open_in_place("touch", std::path::Path::new(&path), true)
            .map_err(|e| crate::safety::in_place_error("touch", &path, e))
    }?;
    file.set_modified(std::time::SystemTime::now())
        .map_err(|e| crate::safety::fs_error("touch", &path, &e))?;
    Ok(Value::Str(path))
}

/// 953: bi_file_type - Detect file MIME type (cross-platform, no shell-out).
fn bi_file_type(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("file_type: expected path string")),
    };
    let ext = std::path::Path::new(&path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();
    let mime = match ext.as_str() {
        "txt" | "text" | "log" => "text/plain",
        "html" | "htm" => "text/html",
        "css" => "text/css",
        "js" | "mjs" | "cjs" => "text/javascript",
        "json" => "application/json",
        "xml" => "application/xml",
        "csv" => "text/csv",
        "md" | "markdown" => "text/markdown",
        "yaml" | "yml" => "application/yaml",
        "toml" => "application/toml",
        "rs" => "text/x-rust",
        "py" => "text/x-python",
        "rb" => "text/x-ruby",
        "java" => "text/x-java",
        "c" | "h" => "text/x-c",
        "cpp" | "cxx" | "cc" | "hpp" => "text/x-c++",
        "go" => "text/x-go",
        "ts" | "tsx" => "text/typescript",
        "sh" | "bash" | "zsh" => "text/x-shellscript",
        "ps1" => "text/x-powershell",
        "bat" | "cmd" => "text/x-batch",
        "sql" => "text/x-sql",
        "jpg" | "jpeg" => "image/jpeg",
        "png" => "image/png",
        "gif" => "image/gif",
        "bmp" => "image/bmp",
        "svg" => "image/svg+xml",
        "webp" => "image/webp",
        "mp3" => "audio/mpeg",
        "wav" => "audio/wav",
        "mp4" | "m4v" => "video/mp4",
        "webm" => "video/webm",
        "avi" => "video/x-msvideo",
        "mkv" => "video/x-matroska",
        "pdf" => "application/pdf",
        "zip" => "application/zip",
        "gz" | "gzip" => "application/gzip",
        "tar" => "application/x-tar",
        "exe" => "application/x-executable",
        "dll" | "so" | "dylib" => "application/x-sharedlib",
        "wasm" => "application/wasm",
        _ => "application/octet-stream",
    };
    Ok(Value::Str(mime.to_string()))
}

/// 957: bi_lsblk - List block devices (cross-platform via sysinfo::Disks).
fn bi_lsblk(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let disks = Disks::new_with_refreshed_list();
    let entries: Vec<Value> = disks
        .iter()
        .map(|d| {
            let mut rec = BTreeMap::new();
            rec.insert(
                "name".to_string(),
                Value::Str(d.name().to_string_lossy().to_string()),
            );
            rec.insert(
                "mount_point".to_string(),
                Value::Str(d.mount_point().to_string_lossy().to_string()),
            );
            rec.insert(
                "total_space".to_string(),
                Value::Int(d.total_space() as i64),
            );
            rec.insert(
                "available_space".to_string(),
                Value::Int(d.available_space() as i64),
            );
            rec.insert(
                "file_system".to_string(),
                Value::Str(String::from_utf8_lossy(d.file_system().as_encoded_bytes()).to_string()),
            );
            rec.insert("is_removable".to_string(), Value::Bool(d.is_removable()));
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(entries))
}

#[path = "linux_diagnostics.rs"]
mod linux_diagnostics;

#[path = "monitor_parse.rs"]
mod monitor_parse;

#[path = "stdin_lines.rs"]
mod stdin_lines;

#[cfg(feature = "native")]
#[path = "image_match.rs"]
mod image_match;

#[path = "pkg_query.rs"]
mod pkg_query;

#[path = "macos_plist.rs"]
mod macos_plist;

/// Windows: the drive a `C:`, `C:\` or `c:/` argument names, as its upper-case
/// letter. Anything else is refused: blkid on Windows takes a drive, not a path.
#[cfg(windows)]
fn blkid_drive(device: &str) -> Result<char> {
    let b = device.as_bytes();
    let plain = (b.len() == 2 || b.len() == 3)
        && b[0].is_ascii_alphabetic()
        && b[1] == b':'
        && (b.len() == 2 || b[2] == b'\\' || b[2] == b'/');
    if plain {
        Ok(char::from(b[0].to_ascii_uppercase()))
    } else if device.starts_with("/dev/") {
        // A well-formed Unix device names nothing here, as a missing device
        // does on Linux, so a script written for both gets the same code. It
        // is checked as on Linux first: `/dev/../x` is still a bad argument.
        linux_diagnostics::device_path("blkid", device)?;
        Err(crate::safety::not_found(
            "blkid",
            "block device",
            &format!("{device} (Windows names drives, such as C:)"),
        ))
    } else {
        Err(crate::safety::bad_arg(
            "blkid",
            "a drive such as C: or C:\\",
            device,
        ))
    }
}

/// Windows: one drive's volume and partition, from Get-Volume and Get-Partition.
/// The volume's UniqueId is uuid and the partition's Guid is partuuid, the way
/// blkid reports them on Linux; type is the file system lower-cased. A field the
/// drive does not report is left out, not made up.
#[cfg(windows)]
fn blkid_windows(device: &str) -> Result<Value> {
    const NAME: &str = "blkid";
    let letter = blkid_drive(device)?.to_string();
    // A drive with no volume prints nothing, which the parse below reads as
    // absent. Get-Volume exits 1 for it even under SilentlyContinue, so only
    // ObjectNotFound is taken as absence; any other error still fails.
    let script = crate::ps_script!(
        "try {{ $v = Get-Volume -DriveLetter {} -ErrorAction Stop }} catch {{ if ($_.CategoryInfo.Category -eq 'ObjectNotFound') {{ exit 0 }} else {{ throw }} }}; $p = Get-Partition -DriveLetter {} -ErrorAction SilentlyContinue | Select-Object -First 1; [pscustomobject]@{{ UniqueId=$v.UniqueId; FileSystemType=$v.FileSystemType; FileSystemLabel=$v.FileSystemLabel; PartitionGuid=$p.Guid }} | ConvertTo-Json",
        crate::safety::ps_quote(&letter),
        crate::safety::ps_quote(&letter)
    );
    let out = net_run(
        NAME,
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script.as_str()],
        NET_TOOL_SECS,
    )?;
    net_checked(NAME, "powershell", &out)?;
    let Some(item) = net_ps_items(NAME, &out.stdout)?.into_iter().next() else {
        return Err(crate::safety::not_found(
            NAME,
            "identifiable device",
            device,
        ));
    };
    let Some(o) = item.as_object() else {
        return Err(net_unparsed(NAME, "powershell"));
    };
    let text = |key: &str| {
        o.get(key)
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
    };
    let mut rec = BTreeMap::new();
    rec.insert("devname".to_string(), Value::Str(format!("{letter}:")));
    if let Some(s) = text("UniqueId") {
        rec.insert("uuid".to_string(), Value::Str(s));
    }
    if let Some(s) = text("PartitionGuid") {
        rec.insert("partuuid".to_string(), Value::Str(s));
    }
    if let Some(s) = text("FileSystemType") {
        rec.insert("type".to_string(), Value::Str(s.to_lowercase()));
    }
    if let Some(s) = text("FileSystemLabel") {
        rec.insert("label".to_string(), Value::Str(s));
    }
    // Only the drive name is left: nothing identifies a volume, as on Linux.
    if rec.len() == 1 {
        return Err(crate::safety::not_found(
            NAME,
            "identifiable device",
            device,
        ));
    }
    Ok(Value::Record(rec))
}

/// macOS: one device's attributes from `diskutil info -plist`, which changes
/// nothing. devname is DeviceNode, uuid is VolumeUUID (DiskUUID when the device
/// has no volume), type is FilesystemType lower-cased, and label is VolumeName.
/// A key the device does not report is left out, as on Linux and Windows. No
/// partuuid is given: DiskUUID is not the GPT partition GUID blkid reports.
#[cfg(target_os = "macos")]
fn blkid_macos(device: &str) -> Result<Value> {
    const NAME: &str = "blkid";
    let limit = std::time::Duration::from_secs(20);
    let argv = ["info".to_string(), "-plist".to_string(), device.to_string()];
    let run = linux_diagnostics::run_bounded(NAME, "diskutil", "diskutil", &argv, limit)?;
    linux_diagnostics::require_success(NAME, "diskutil", &run, limit)?;
    let plist = macos_plist::parse_top_dict(&run.stdout)
        .map_err(|e| crate::safety::tool_failed(NAME, "diskutil info -plist", Some(0), &e))?;
    let text = |key: &str| match plist.get(key) {
        Some(macos_plist::PlistValue::Str(s)) if !s.trim().is_empty() => Some(s.trim().to_string()),
        _ => None,
    };
    let mut rec = BTreeMap::new();
    if let Some(s) = text("DeviceNode") {
        rec.insert("devname".to_string(), Value::Str(s));
    }
    if let Some(s) = text("VolumeUUID").or_else(|| text("DiskUUID")) {
        rec.insert("uuid".to_string(), Value::Str(s));
    }
    if let Some(s) = text("FilesystemType") {
        rec.insert("type".to_string(), Value::Str(s.to_lowercase()));
    }
    if let Some(s) = text("VolumeName") {
        rec.insert("label".to_string(), Value::Str(s));
    }
    if rec.is_empty() {
        return Err(crate::safety::not_found(
            NAME,
            "identifiable device",
            device,
        ));
    }
    Ok(Value::Record(rec))
}

/// 958: bi_blkid - Block device attributes (Linux and macOS; Windows reads a drive).
fn bi_blkid(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    linux_diagnostics::no_pipeline_input("blkid", &input)?;
    let device = match args.as_slice() {
        [Value::Str(s)] => s.clone(),
        [other] => {
            return Err(crate::safety::bad_arg(
                "blkid",
                "a device path String such as /dev/sda1",
                other.type_name(),
            ))
        }
        _ => {
            return Err(crate::safety::arg_err(
                "blkid: expected exactly one device path",
            ))
        }
    };
    #[cfg(not(windows))]
    linux_diagnostics::device_path("blkid", &device)?;
    #[cfg(target_os = "linux")]
    {
        let limit = std::time::Duration::from_secs(20);
        let run = linux_diagnostics::run_bounded(
            "blkid",
            "blkid",
            "blkid",
            &["-o".to_string(), "export".to_string(), device.clone()],
            limit,
        )?;
        // blkid exits 2 for a device it cannot identify.
        if !run.timed_out && !run.truncated && run.code == Some(2) {
            return Err(crate::safety::not_found(
                "blkid",
                "identifiable device",
                &device,
            ));
        }
        linux_diagnostics::require_success("blkid", "blkid", &run, limit)?;
        let mut rec = BTreeMap::new();
        for line in run.stdout.lines() {
            if let Some((k, v)) = line.split_once('=') {
                let k = k.trim().to_lowercase();
                if !k.is_empty() {
                    rec.insert(k, Value::Str(v.to_string()));
                }
            }
        }
        if rec.is_empty() {
            return Err(crate::safety::not_found(
                "blkid",
                "identifiable device",
                &device,
            ));
        }
        Ok(Value::Record(rec))
    }
    #[cfg(windows)]
    {
        blkid_windows(&device)
    }
    #[cfg(target_os = "macos")]
    {
        blkid_macos(&device)
    }
    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
    {
        Err(crate::safety::unimplemented(
            "blkid",
            "blkid is Linux, macOS and Windows only; NOTHING WAS DONE on this operating system",
            "lsblk() lists block devices on every OS",
        ))
    }
}

/// Longest host name a network tool accepts.
const NET_HOST_MAX: usize = 253;
/// Most words a command line may hold once split into argv.
const NET_ARGV_MAX: usize = 256;
/// Stderr kept from a network or debug tool, for a failure message or a report.
const NET_ERR_MAX: usize = 4096;
/// Most items one xargs_exec call may run.
const XARGS_MAX_ITEMS: usize = 256;
/// Output kept from one run of xargs_exec, on each stream.
const XARGS_ITEM_OUT: usize = 16 * 1024;
/// Wall-clock limit on one xargs_exec call, all of its items together.
const XARGS_TOTAL_SECS: u64 = 600;
/// Redirects http_get follows, each one checked before it is taken.
const HTTP_MAX_REDIRECTS: usize = 5;
/// Largest response body http_get reads.
const HTTP_BODY_MAX: u64 = 16 * 1024 * 1024;
/// Largest file wget_download writes.
const WGET_FILE_MAX: u64 = 1024 * 1024 * 1024;
/// Largest logrotate configuration that is read.
const LOGROTATE_CONFIG_MAX: u64 = 1024 * 1024;
/// Most log files multitail_open opens at once.
const MULTITAIL_MAX_FILES: usize = 16;
/// The port iperf3 listens on when none is given.
const IPERF3_PORT: i64 = 5201;
/// The nmap flags nmap_scan passes through. Every other nmap option is refused:
/// --script runs scripts, -oN/-oG/--log-file write files, and the rest change
/// what nmap reads or runs.
const NMAP_FLAGS: &[&str] = &[
    "-sT", "-sS", "-sU", "-sV", "-Pn", "-n", "-T0", "-T1", "-T2", "-T3", "-T4", "-T5",
];
/// logrotate directives that run a program or send mail. A configuration that
/// names one is refused, because the command it would run is out of sight here.
const LOGROTATE_REFUSED: &[&str] = &[
    "prerotate",
    "postrotate",
    "firstaction",
    "lastaction",
    "preremove",
    "mail",
    "mailfirst",
    "maillast",
];

/// A host name or IP literal given to a network tool as an argument: letters,
/// digits, '.', '-' and ':', at most NET_HOST_MAX bytes. A leading '-' is
/// refused as an option, and every other character is refused by the rule.
fn net_target_host(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    let well_formed = !value.is_empty()
        && value.len() <= NET_HOST_MAX
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':'));
    if well_formed {
        Ok(value.to_string())
    } else {
        Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be a host name or IP literal of letters, digits, '.', '-' and ':' (at most {NET_HOST_MAX} bytes), got {value:?}"
        )))
    }
}

/// A TCP or UDP port: an Int in 1..=65535.
fn net_port(builtin: &str, n: i64) -> Result<i64> {
    if (1..=65535).contains(&n) {
        Ok(n)
    } else {
        Err(crate::safety::arg_err(format!(
            "{builtin}: port must be 1..=65535, got {n}"
        )))
    }
}

/// A systemd unit name for journalctl: letters, digits, and '-', '_', '.', '@'.
fn journal_unit(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    let well_formed = !value.is_empty()
        && value.len() <= 256
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'@'));
    if well_formed {
        Ok(value.to_string())
    } else {
        Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be a systemd unit name (letters, digits and - _ . @), got {value:?}"
        )))
    }
}

/// A command line split into argv on whitespace. There is no quoting and no
/// shell: each word is one argument, and shell metacharacters are inert. The
/// program word may not begin with '-'.
fn argv_words(builtin: &str, command: &str) -> Result<Vec<String>> {
    let words: Vec<String> = command.split_whitespace().map(str::to_string).collect();
    let Some(program) = words.first() else {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: the command is empty"
        )));
    };
    crate::safety::reject_option_like(builtin, std::slice::from_ref(program))?;
    if words.len() > NET_ARGV_MAX {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!(
                "the command has {} words; the limit is {NET_ARGV_MAX}",
                words.len()
            ),
            "pass a shorter command line",
        ));
    }
    Ok(words)
}

/// The exit code of a finished run; a run ended by a signal has none, and is -1.
fn exit_code_of(run: &ToolRun) -> i64 {
    run.code.map_or(-1, i64::from)
}

/// A network request that failed before any answer came back: a coded E_IO
/// that says what was attempted.
fn net_io_error(builtin: &str, what: &str, detail: impl std::fmt::Display) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::Io,
        message: format!("{builtin}: {what}: {detail}"),
        builtin: builtin.to_string(),
        hint: "no answer came back; check the address and the network, then retry".to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: format!("{what} to complete"),
        got: "no answer".to_string(),
        extra: serde_json::Map::new(),
    })
}

/// Whether netcat's failure text says the port was closed or did not answer: a
/// determined "not open", as opposed to netcat itself failing.
fn nc_refusal(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    lower.contains("refused") || lower.contains("timed out") || lower.contains("timeout")
}

/// One socat address for socat_relay. Only an outbound TCP or UDP connection to
/// a host name or IPv4 literal and a port is allowed, with no options. EXEC,
/// SYSTEM and SHELL run programs, OPEN and CREATE write files, and every LISTEN
/// form opens a listener, so each of those is refused by policy.
fn socat_address(builtin: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    let Some((kind, rest)) = value.split_once(':') else {
        return Err(crate::safety::bad_arg(
            builtin,
            "an address such as TCP:host:port",
            value,
        ));
    };
    let kind_up = kind.to_ascii_uppercase();
    if !matches!(kind_up.as_str(), "TCP" | "TCP4" | "UDP" | "UDP4") {
        return Err(crate::safety::policy_deny(
            builtin,
            format!("{builtin}: socat address type `{kind}` is refused"),
            "only outbound TCP, TCP4, UDP and UDP4 connections to a host and port are allowed; EXEC, SYSTEM and SHELL run programs, OPEN and CREATE write files, and LISTEN forms open listeners",
        ));
    }
    let Some((host, port)) = rest.rsplit_once(':') else {
        return Err(crate::safety::bad_arg(
            builtin,
            "TCP:host:port or UDP:host:port",
            value,
        ));
    };
    let host = net_target_host(builtin, "the socat address host", host)?;
    if host.contains(':') {
        return Err(crate::safety::bad_arg(
            builtin,
            "a host name or IPv4 literal without ':' in the address",
            value,
        ));
    }
    let port = if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) {
        port.parse::<i64>().ok()
    } else {
        None
    };
    let Some(port) = port else {
        return Err(crate::safety::bad_arg(
            builtin,
            "a port number with no options after it",
            value,
        ));
    };
    let port = net_port(builtin, port)?;
    Ok(format!("{kind_up}:{host}:{port}"))
}

/// The ports nmap_scan may scan: digits, ',' and '-', with every number in
/// 1..=65535 and every range low <= high.
fn nmap_ports(builtin: &str, what: &str, value: &str) -> Result<String> {
    let ok = !value.is_empty()
        && value.len() <= 1024
        && value
            .bytes()
            .all(|b| b.is_ascii_digit() || matches!(b, b',' | b'-'))
        && value.split(',').all(|item| {
            let mut bounds = item.splitn(2, '-');
            let lo = bounds.next().and_then(|s| s.parse::<u32>().ok());
            let hi = match bounds.next() {
                Some(s) => s.parse::<u32>().ok(),
                None => lo,
            };
            matches!((lo, hi), (Some(l), Some(h)) if (1..=65535).contains(&l) && (1..=65535).contains(&h) && l <= h)
        });
    if ok {
        Ok(value.to_string())
    } else {
        Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be ports or ranges such as \"22,80,1000-1100\", each 1..=65535 (got {value:?})"
        )))
    }
}

/// The nmap flags nmap_scan accepts, whitespace-separated. Anything not in
/// NMAP_FLAGS is refused by policy.
fn nmap_flags(builtin: &str, what: &str, value: &str) -> Result<String> {
    for word in value.split_whitespace() {
        if !NMAP_FLAGS.contains(&word) {
            return Err(crate::safety::policy_deny(
                builtin,
                format!("{builtin}: {what} `{word}` is not an allowed nmap flag"),
                format!(
                    "allowed flags: {}; scripts (--script) and output files (-oN, -oG, --log-file) are refused",
                    NMAP_FLAGS.join(" ")
                ),
            ));
        }
    }
    Ok(value.to_string())
}

/// The items xargs_exec runs: an Array of scalars, or a String read as lines
/// with empty lines skipped. Each item is one argument, so an item that begins
/// with '-' is refused as an option.
fn xargs_items(builtin: &str, value: &Value) -> Result<Vec<String>> {
    let items: Vec<String> = match value {
        Value::Array(arr) => arr
            .iter()
            .map(|v| match v {
                Value::Str(s) => Ok(s.clone()),
                Value::Int(n) => Ok(n.to_string()),
                Value::Float(f) => Ok(f.to_string()),
                Value::Bool(b) => Ok(b.to_string()),
                other => Err(crate::safety::bad_arg(
                    builtin,
                    "scalar items (String, Int, Float or Bool)",
                    other.type_name(),
                )),
            })
            .collect::<Result<Vec<String>>>()?,
        Value::Str(s) => s
            .lines()
            .filter(|l| !l.is_empty())
            .map(str::to_string)
            .collect(),
        other => {
            return Err(crate::safety::bad_arg(
                builtin,
                "an Array or a String of items",
                other.type_name(),
            ))
        }
    };
    if items.len() > XARGS_MAX_ITEMS {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("{} items; the limit is {XARGS_MAX_ITEMS}", items.len()),
            "run the items in more than one call",
        ));
    }
    for item in &items {
        if item.len() > 4096 || item.contains('\0') {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: each item is at most 4096 bytes and has no NUL"
            )));
        }
        crate::safety::reject_option_like(builtin, std::slice::from_ref(item))?;
    }
    Ok(items)
}

/// One `strace -c` summary row, read from its default columns: percent,
/// seconds, usecs/call, calls, errors, syscall. A row with any other shape is
/// counted and returned as the second value, never dropped.
fn strace_summary(text: &str) -> (Vec<Value>, usize) {
    let mut rows = Vec::new();
    let mut unparsed = 0usize;
    let mut in_table = false;
    let mut after_rule = false;
    for line in text.lines() {
        let t = line.trim();
        if t.starts_with("% time") {
            in_table = true;
            continue;
        }
        if !in_table {
            continue;
        }
        if t.starts_with("------") {
            if after_rule {
                break;
            }
            after_rule = true;
            continue;
        }
        if t.is_empty() {
            continue;
        }
        let cols: Vec<&str> = t.split_whitespace().collect();
        if cols.last() == Some(&"total") {
            continue;
        }
        let parsed = match cols.as_slice() {
            [pct, secs, _usecs, calls, errors, name] => {
                match (
                    pct.parse::<f64>(),
                    secs.parse::<f64>(),
                    calls.parse::<i64>(),
                    errors.parse::<i64>(),
                ) {
                    (Ok(pct), Ok(secs), Ok(calls), Ok(errors)) => {
                        Some((pct, secs, calls, errors, *name))
                    }
                    _ => None,
                }
            }
            _ => None,
        };
        match parsed {
            Some((pct, secs, calls, errors, name)) => {
                let mut rec = BTreeMap::new();
                rec.insert("percent".to_string(), Value::Float(pct));
                rec.insert("seconds".to_string(), Value::Float(secs));
                rec.insert("calls".to_string(), Value::Int(calls));
                rec.insert("errors".to_string(), Value::Int(errors));
                rec.insert("name".to_string(), Value::Str(name.to_string()));
                rows.push(Value::Record(rec));
            }
            None => unparsed += 1,
        }
    }
    (rows, unparsed)
}

/// One line of `nm --demangle` output: `address type name`, or `type name` for
/// an undefined symbol, whose address is null. A demangled name may contain
/// spaces, so only the first fields are split off.
fn nm_record(line: &str) -> Value {
    let mut rec = BTreeMap::new();
    let t = line.trim();
    let (address, rest) = match t.split_once(' ') {
        Some((first, rest)) if first.len() >= 8 && first.bytes().all(|b| b.is_ascii_hexdigit()) => {
            (Value::Str(first.to_string()), rest.trim_start())
        }
        _ => (Value::Null, t),
    };
    match rest.split_once(' ') {
        Some((ty, name)) if ty.len() == 1 && !name.trim().is_empty() => {
            rec.insert("address".to_string(), address);
            rec.insert("type".to_string(), Value::Str(ty.to_string()));
            rec.insert("name".to_string(), Value::Str(name.trim().to_string()));
        }
        _ => {
            rec.insert("line".to_string(), Value::Str(line.to_string()));
        }
    }
    Value::Record(rec)
}

/// Directives in a logrotate configuration are checked before the tool runs.
/// A path that is absolute, starts with '~', or contains '..' could reach
/// outside the workspace, and a directive in LOGROTATE_REFUSED runs a program.
fn logrotate_config_check(builtin: &str, text: &str) -> Result<()> {
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        for token in line.split_whitespace() {
            let word = token.trim_matches(|c| c == '"' || c == '\'');
            if LOGROTATE_REFUSED.contains(&word) {
                return Err(crate::safety::policy_deny(
                    builtin,
                    format!("{builtin}: the configuration uses `{word}`, which runs a program or sends mail"),
                    "remove that directive; this call runs logrotate without a shell and cannot see the commands it would run",
                ));
            }
            let absolute = word.starts_with('/')
                || word.starts_with('\\')
                || word.starts_with('~')
                || word.as_bytes().get(1) == Some(&b':');
            if absolute || word.contains("..") {
                return Err(crate::safety::policy_deny(
                    builtin,
                    format!("{builtin}: the configuration names `{word}`, which may lie outside the workspace"),
                    "use paths relative to the configuration file, with no '..', so every file it touches is inside the workspace",
                ));
            }
        }
    }
    Ok(())
}

/// journalctl — the most recent entries of the systemd journal, optionally of one unit.
/// Usage: journalctl(), journalctl(count) or journalctl(count, unit). count is
/// 1..=1000 and defaults to 50. Returns an Array of entries, each a Record of
/// the journal's JSON fields. A line that is not JSON is E_TOOL_FAILED, never
/// skipped, and output past 16 MiB is E_BUDGET_EXCEEDED. Elsewhere the call is
/// E_UNIMPLEMENTED after its arguments are checked.
///
/// On Windows the entries are the newest `count` events of the System log, as
/// Records {time, provider, level, id, message}. `unit` is then an event
/// provider's name, such as "Service Control Manager". Nothing else maps: the
/// Linux call takes no priority, so none is accepted here.
///
/// On macOS the entries are the newest `count` entries of the unified log from
/// the last hour, as Records of the `log show --style ndjson` fields, and `unit`
/// is a process name. See journal_macos.
fn bi_journalctl(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("journalctl", &input)?;
    k8s_max_args("journalctl", &args, 2)?;
    let count = match args.first() {
        None => 50,
        Some(Value::Int(n)) if (1..=1000).contains(n) => *n,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "journalctl",
                "count: Int 1..=1000",
                other.type_name(),
            ))
        }
    };
    #[cfg(windows)]
    let unit = k8s_arg("journalctl", "unit", &args, 1, journal_provider)?;
    #[cfg(not(windows))]
    let unit = k8s_arg("journalctl", "unit", &args, 1, journal_unit)?;
    #[cfg(windows)]
    {
        journal_windows(count, unit)
    }
    #[cfg(target_os = "linux")]
    {
        let count_s = count.to_string();
        let mut argv: Vec<&str> = vec!["-n", count_s.as_str(), "-o", "json", "--no-pager"];
        if let Some(u) = unit.as_deref() {
            argv.extend(["-u", u]);
        }
        let run = tool_run(
            "journalctl",
            "journalctl",
            None,
            &argv,
            Keep::Head(TOOL_MAX_JSON),
            TOOL_DEADLINE_SECS,
        )?;
        let text = tool_text("journalctl", run)?;
        let mut entries = Vec::new();
        for line in text.lines().filter(|l| !l.trim().is_empty()) {
            let json = serde_json::from_str::<serde_json::Value>(line).map_err(|e| {
                crate::safety::tool_failed(
                    "journalctl",
                    "journalctl -o json",
                    Some(0),
                    &format!("printed a line that is not JSON ({e})"),
                )
            })?;
            entries.push(json_to_value(json));
        }
        Ok(Value::Array(entries))
    }
    #[cfg(target_os = "macos")]
    {
        journal_macos(count, unit)
    }
    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
    {
        let _ = (count, unit);
        Err(crate::safety::unimplemented(
            "journalctl",
            "journalctl reads the systemd journal on Linux, the unified log on macOS and the event log on Windows; NOTHING WAS READ on this operating system",
            "cat(path) reads a log file on every OS",
        ))
    }
}

/// An event provider name for journalctl on Windows: letters, digits, space,
/// and - _ . only. The name goes inside a single-quoted PowerShell string, so
/// nothing PowerShell would read as syntax is allowed.
#[cfg(windows)]
fn journal_provider(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    let well_formed = !value.trim().is_empty()
        && value.len() <= 256
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b' ' | b'-' | b'_' | b'.'));
    if well_formed {
        Ok(value.to_string())
    } else {
        Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be an event provider name (letters, digits, space and - _ .), got {value:?}"
        )))
    }
}

/// journalctl on Windows: the newest `count` events of the System log, or of
/// one provider. A provider with no events is an empty Array.
/// macOS: the newest `count` entries of the unified log from the last hour, as
/// `log show --style ndjson` prints them: one JSON object per line, returned as
/// Records of the log's own fields, oldest first as journalctl prints them.
/// `unit` is a process name, matched exactly by a predicate that is a single
/// argv element; it passed journal_unit, so it holds no quote or space. The
/// output is read from its end, so a busy hour keeps its newest 16 MiB and the
/// entries come from there. A line that is not JSON is E_TOOL_FAILED.
#[cfg(target_os = "macos")]
fn journal_macos(count: i64, unit: Option<String>) -> Result<Value> {
    const NAME: &str = "journalctl";
    let predicate = unit.as_deref().map(|u| {
        let q = '"';
        format!("process == {q}{u}{q}")
    });
    let mut argv: Vec<&str> = vec!["show", "--style", "ndjson", "--last", "1h"];
    if let Some(p) = predicate.as_deref() {
        argv.extend(["--predicate", p]);
    }
    let run = tool_run(
        NAME,
        "log",
        None,
        &argv,
        Keep::Tail(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    if !run.success {
        return Err(crate::safety::tool_failed(
            NAME,
            "log show --style ndjson",
            run.code,
            &run.stderr,
        ));
    }
    Ok(Value::Array(journal_ndjson_rows(
        &run.stdout,
        run.stdout_truncated,
        count,
    )?))
}

/// The newest `count` non-empty lines of `log show --style ndjson` output, each
/// parsed as a JSON object and returned as a Record, oldest first. When the
/// output was cut to its tail (`truncated`), its first line may begin mid-line,
/// so it is dropped. A line that is not JSON is E_TOOL_FAILED, never skipped.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn journal_ndjson_rows(stdout: &str, truncated: bool, count: i64) -> Result<Vec<Value>> {
    const NAME: &str = "journalctl";
    let mut text = stdout;
    if truncated {
        text = text.split_once('\n').map_or("", |(_, rest)| rest);
    }
    // `log show` may print a notice ("Filtering the log data using ...")
    // before the first entry; lines before the first JSON object are that
    // header. After it, every line must be an entry.
    let lines: Vec<&str> = text
        .lines()
        .filter(|l| !l.trim().is_empty())
        .skip_while(|l| !l.trim_start().starts_with('{'))
        .collect();
    // The stream ends with a summary, {"count": N, "finished": 1}, which is not
    // an entry (run 40845679109); it does not take one of the `count` slots.
    let mut lines = lines;
    if let Some(last) = lines.last() {
        let summary = serde_json::from_str::<serde_json::Value>(last)
            .ok()
            .and_then(|v| {
                v.as_object()
                    .map(|o| o.contains_key("finished") && !o.contains_key("timestamp"))
            })
            .unwrap_or(false);
        if summary {
            lines.pop();
        }
    }
    let keep = (count.max(0) as usize).min(lines.len());
    lines[lines.len() - keep..]
        .iter()
        .map(|line| {
            serde_json::from_str::<serde_json::Value>(line)
                .map(json_to_value)
                .map_err(|e| {
                    crate::safety::tool_failed(
                        NAME,
                        "log show --style ndjson",
                        Some(0),
                        &format!("printed a line that is not JSON ({e})"),
                    )
                })
        })
        .collect()
}

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

    fn rec_n(v: &Value) -> i64 {
        match v {
            Value::Record(m) => match m.get("n") {
                Some(Value::Int(n)) => *n,
                other => panic!("no n: {other:?}"),
            },
            other => panic!("not a record: {other:?}"),
        }
    }

    #[test]
    fn a_notice_before_the_first_entry_is_skipped() {
        // Raw strings: this file's source scanners read a backslash-quote as
        // the end of a string.
        let out = [
            r#"Filtering the log data using "process == 1""#,
            r#"{"n":1}"#,
            r#"{"n":2}"#,
        ]
        .join("\n");
        let rows = journal_ndjson_rows(&out, false, 10).expect("rows");
        assert_eq!(rows.iter().map(rec_n).collect::<Vec<_>>(), [1, 2]);
        let late = [r#"{"n":1}"#, "not json"].join("\n");
        assert!(journal_ndjson_rows(&late, false, 10).is_err());
    }

    #[test]
    fn the_closing_summary_is_not_an_entry() {
        let out = [r#"{"n":1}"#, r#"{"n":2}"#, r#"{"count":2,"finished":1}"#].join("\n");
        let rows = journal_ndjson_rows(&out, false, 1).expect("rows");
        assert_eq!(rows.iter().map(rec_n).collect::<Vec<_>>(), [2]);
    }

    #[test]
    fn the_newest_count_lines_come_back_oldest_first() {
        let text = concat!(
            r#"{"n": 1}"#,
            "\n",
            r#"{"n": 2}"#,
            "\n",
            "\n",
            r#"{"n": 3}"#,
            "\n",
            r#"{"n": 4}"#,
            "\n",
        );
        let rows = journal_ndjson_rows(text, false, 2).expect("json lines parse");
        assert_eq!(rows.iter().map(rec_n).collect::<Vec<_>>(), vec![3, 4]);
        let all = journal_ndjson_rows(text, false, 1000).expect("json lines parse");
        assert_eq!(all.len(), 4);
        assert!(journal_ndjson_rows(text, false, 0).unwrap().is_empty());
    }

    #[test]
    fn a_tail_that_starts_mid_line_drops_its_partial_first_line() {
        let text = concat!(r#"n": 0}"#, "\n", r#"{"n": 7}"#, "\n");
        let rows = journal_ndjson_rows(text, true, 5).expect("the partial line is dropped");
        assert_eq!(rows.iter().map(rec_n).collect::<Vec<_>>(), vec![7]);
    }

    #[test]
    fn a_line_that_is_not_json_is_a_tool_failure_not_a_skip() {
        let text = concat!(r#"{"n": 1}"#, "\n", "Filtering the log data\n");
        let err = journal_ndjson_rows(text, false, 5).unwrap_err();
        assert!(err.to_string().contains("E_TOOL_FAILED"), "{err}");
    }
}

#[cfg(windows)]
fn journal_windows(count: i64, provider: Option<String>) -> Result<Value> {
    let filter = match provider.as_deref() {
        Some(p) => format!("@{{LogName='System'; ProviderName='{p}'}}"),
        None => "@{LogName='System'}".to_string(),
    };
    let script = WIN_JOURNAL_SCRIPT
        .replace("__FILTER__", &filter)
        .replace("__COUNT__", &count.to_string());
    Ok(Value::Array(win_event_rows("journalctl", &script)?))
}

/// Get-WinEvent streams the newest event first. A filter that matches nothing
/// raises a NoMatching error, caught here and printed as []. Any other error
/// stops the script under ErrorActionPreference Stop and exits non-zero.
#[cfg(windows)]
const WIN_JOURNAL_SCRIPT: &str = r#"$ErrorActionPreference='Stop'; $OutputEncoding=[System.Text.UTF8Encoding]::new($false); [Console]::OutputEncoding=$OutputEncoding; $rows=@(); try { $rows=@(Get-WinEvent -FilterHashtable __FILTER__ -MaxEvents __COUNT__ | ForEach-Object { [pscustomobject]@{ time=$_.TimeCreated.ToString('o'); provider=$_.ProviderName; level=$_.LevelDisplayName; id=$_.Id; message=$_.Message } }) } catch { if ($_.FullyQualifiedErrorId -like 'NoMatching*') { $rows=@() } else { throw } }; ConvertTo-Json -InputObject $rows -Depth 3 -Compress"#;

/// pkg_history on Windows: the MsiInstaller events 1033 (installed) and 1034
/// (removed) in the Application log. They carry the product name and version as
/// properties, and status 0 is success; other statuses are failed transactions
/// and are left out. Select-Object -First stops the read at the limit.
#[cfg(windows)]
const WIN_PKG_HISTORY_SCRIPT: &str = r#"$ErrorActionPreference='Stop'; $OutputEncoding=[System.Text.UTF8Encoding]::new($false); [Console]::OutputEncoding=$OutputEncoding; $rows=@(); try { $rows=@(Get-WinEvent -FilterHashtable @{LogName='Application'; ProviderName='MsiInstaller'; Id=1033,1034} | Where-Object { $_.Properties.Count -ge 4 -and [string]$_.Properties[3].Value -eq '0' } | Select-Object -First __LIMIT__ | ForEach-Object { [pscustomobject]@{ time=$_.TimeCreated.ToString('o'); action=$(if ($_.Id -eq 1033) { 'install' } else { 'remove' }); package=[string]$_.Properties[0].Value; version=[string]$_.Properties[1].Value } }) } catch { if ($_.FullyQualifiedErrorId -like 'NoMatching*') { $rows=@() } else { throw } }; ConvertTo-Json -InputObject $rows -Depth 3 -Compress"#;

/// Run one event-log script under the tool deadline and return its records.
/// The script prints a JSON array. Anything else is an unreadable answer, never
/// an empty one.
#[cfg(windows)]
fn win_event_rows(builtin: &str, script: &str) -> Result<Vec<Value>> {
    let mut cmd = crate::safety::child_command("powershell");
    cmd.args([
        "-NoLogo",
        "-NoProfile",
        "-NonInteractive",
        "-Command",
        script,
    ])
    .stdin(std::process::Stdio::null());
    let output = bounded_cmd_output(builtin, "powershell", cmd, TOOL_DEADLINE_SECS)?;
    let text = probe_stdout(builtin, "powershell", output)?;
    let items = match serde_json::from_str::<serde_json::Value>(&text) {
        Ok(serde_json::Value::Array(items)) => items,
        _ => return Err(net_unparsed(builtin, "powershell")),
    };
    items
        .into_iter()
        .map(|item| match item {
            obj @ serde_json::Value::Object(_) => Ok(json_to_value(obj)),
            _ => Err(net_unparsed(builtin, "powershell")),
        })
        .collect()
}

/// 961: bi_lsof - List open files.
fn bi_lsof(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    linux_diagnostics::no_pipeline_input("lsof", &input)?;
    let path = match args.as_slice() {
        [] => None,
        [Value::Str(p)] => {
            linux_diagnostics::file_path("lsof", p)?;
            Some(p.clone())
        }
        [other] => {
            return Err(crate::safety::bad_arg(
                "lsof",
                "a file path String, or no argument",
                other.type_name(),
            ))
        }
        _ => {
            return Err(crate::safety::arg_err(
                "lsof: expected no argument, or one file path",
            ))
        }
    };
    #[cfg(unix)]
    {
        let limit = std::time::Duration::from_secs(30);
        let mut argv = vec!["-P".to_string(), "-n".to_string()];
        match &path {
            Some(p) => {
                if !std::path::Path::new(p).exists() {
                    return Err(crate::safety::not_found("lsof", "file", p));
                }
                argv.push(p.clone());
            }
            None => argv.push("-i".to_string()),
        }
        let run = linux_diagnostics::run_bounded("lsof", "lsof", "lsof", &argv, limit)?;
        // lsof exits 1 when nothing matched; with nothing on stderr that is an
        // empty answer, not a failure.
        if run.code == Some(1)
            && !run.timed_out
            && !run.truncated
            && run.stdout.trim().is_empty()
            && run.stderr.trim().is_empty()
        {
            return Ok(Value::Array(vec![]));
        }
        linux_diagnostics::require_success("lsof", "lsof", &run, limit)?;
        let mut lines = run.stdout.lines();
        let headers: Vec<String> = match lines.next() {
            Some(h) => h.split_whitespace().map(|h| h.to_lowercase()).collect(),
            None => return Ok(Value::Array(vec![])),
        };
        let entries: Vec<Value> = lines
            .filter(|line| !line.trim().is_empty())
            .map(|line| {
                let cols = linux_diagnostics::columns(line, headers.len());
                let mut rec = BTreeMap::new();
                for (header, col) in headers.iter().zip(cols) {
                    rec.insert(header.clone(), Value::Str(col.to_string()));
                }
                Value::Record(rec)
            })
            .collect();
        Ok(Value::Array(entries))
    }
    #[cfg(windows)]
    {
        match path {
            None => lsof_windows_sockets(),
            Some(p) => lsof_windows_path(&p),
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = path;
        Err(crate::safety::unimplemented(
            "lsof",
            "lsof runs on Linux and macOS only; NOTHING WAS LISTED on this operating system",
            "netstat_info() lists this machine's network connections on every OS",
        ))
    }
}

/// strace_cmd — trace the system calls of one program and summarise them.
/// Usage: strace_cmd(command). The command is split on whitespace into a program
/// and its arguments and run directly, with no shell; the program may not begin
/// with '-'. Returns {command, exit_code, stdout, raw, syscalls, unparsed_rows}.
/// The exit code is the traced program's, which is the answer here, so it is
/// data and not a failure of the trace. macOS uses dtruss; elsewhere strace, and
/// where it is not installed the call is E_TOOL_MISSING.
fn bi_strace_cmd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("strace_cmd", &input)?;
    k8s_max_args("strace_cmd", &args, 1)?;
    let command = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "strace_cmd: expected command string",
            ))
        }
    };
    let words = argv_words("strace_cmd", &command)?;
    crate::safety::guard_exec("strace", &command)?;
    let macos = cfg!(target_os = "macos");
    let tracer = if macos { "dtruss" } else { "strace" };
    let mut argv: Vec<&str> = if macos {
        Vec::new()
    } else {
        vec!["-c", "-e", "trace=all", "--"]
    };
    argv.extend(words.iter().map(String::as_str));
    let run = tool_run_stderr(
        "strace_cmd",
        tracer,
        None,
        &argv,
        Keep::Tail(TOOL_MAX_TEXT),
        TOOL_MAX_TEXT,
        TOOL_DEADLINE_SECS,
    )?;
    let (syscalls, unparsed) = if macos {
        (Vec::new(), 0)
    } else {
        strace_summary(&run.stderr)
    };
    let mut rec = BTreeMap::new();
    rec.insert("command".to_string(), Value::Str(command));
    rec.insert("exit_code".to_string(), Value::Int(exit_code_of(&run)));
    rec.insert("stdout".to_string(), Value::Str(run.stdout.clone()));
    rec.insert("raw".to_string(), Value::Str(run.stderr.clone()));
    rec.insert("syscalls".to_string(), Value::Array(syscalls));
    rec.insert("unparsed_rows".to_string(), Value::Int(unparsed as i64));
    Ok(Value::Record(rec))
}

/// top — Process snapshot, largest resident memory first (cross-platform via sysinfo).
/// Usage: top_snapshot() or top_snapshot(count), count 1..=10000, default 30.
/// Each entry is {pid, name, cpu_percent, memory_bytes, memory_mb}. CPU use is a
/// difference between two samples, so the call takes one sampling interval.
fn bi_top_snapshot(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("top_snapshot", &input)?;
    k8s_max_args("top_snapshot", &args, 1)?;
    let count = match args.first() {
        None => 30,
        Some(Value::Int(n)) if (1..=10_000).contains(n) => *n as usize,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "top_snapshot",
                "count: Int 1..=10000",
                other.type_name(),
            ))
        }
    };
    let mut sys = System::new_all();
    sys.refresh_all();
    // CPU use is measured between two samples; one sample reads 0 for every process.
    std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
    sys.refresh_all();
    let mut procs: Vec<_> = sys.processes().iter().collect();
    procs.sort_by(|a, b| b.1.memory().cmp(&a.1.memory()));
    let entries: Vec<Value> = procs
        .iter()
        .take(count)
        .map(|(pid, p)| {
            let mut rec = BTreeMap::new();
            rec.insert("pid".to_string(), Value::Int(pid.as_u32() as i64));
            rec.insert(
                "name".to_string(),
                Value::Str(p.name().to_string_lossy().to_string()),
            );
            rec.insert(
                "cpu_percent".to_string(),
                Value::Float(p.cpu_usage() as f64),
            );
            rec.insert("memory_bytes".to_string(), Value::Int(p.memory() as i64));
            rec.insert(
                "memory_mb".to_string(),
                Value::Float(p.memory() as f64 / 1_048_576.0),
            );
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(entries))
}

/// 970: bi_dd_copy - Copy with `dd if=<source> of=<destination>` (Unix; Windows
/// copies in-process, see dd_copy_in_process).
///
/// Each operand is one argv element, so a path cannot add a second operand. It
/// used to drop an options value that was not a Record, any key but `bs` and
/// `count`, and a `count` that was not an Int; a failed copy came back as a
/// record with `success: false`; and `dd` ran with no deadline.
fn bi_dd_copy(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("dd_copy", &input)?;
    let text = |i: usize, what: &str| -> Result<String> {
        match args.get(i) {
            Some(Value::Str(s)) if !s.is_empty() => Ok(s.clone()),
            other => Err(crate::safety::bad_arg(
                "dd_copy",
                &format!("{what}: a non-empty String"),
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            )),
        }
    };
    let src = text(0, "source")?;
    let dst = text(1, "destination")?;
    // dd truncates and writes the destination in place, on every platform.
    crate::safety::refuse_hard_linked_write("dd_copy", &dst)?;
    // The journal step names the destination (absent before, or replaced), not
    // the source, which is only read.
    crate::journal::record_file_once("dd_copy", &dst);
    let mut operands = vec![format!("if={src}"), format!("of={dst}")];
    match args.get(2) {
        None => {}
        Some(Value::Record(opts)) => {
            for (key, value) in opts {
                match (key.as_str(), value) {
                    ("bs", Value::Str(bs)) if dd_block_size(bs) => {
                        operands.push(format!("bs={bs}"))
                    }
                    ("bs", Value::Int(n)) if *n >= 1 => operands.push(format!("bs={n}")),
                    ("count", Value::Int(n)) if *n >= 1 => operands.push(format!("count={n}")),
                    ("bs", v) | ("count", v) => {
                        return Err(crate::safety::bad_arg(
                            "dd_copy",
                            "bs: a positive Int or a size such as 4M; count: a positive Int",
                            &format!("{key} = {}", v.type_name()),
                        ))
                    }
                    _ => {
                        return Err(crate::safety::bad_arg(
                            "dd_copy",
                            "options with only bs and count",
                            key,
                        ))
                    }
                }
            }
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "dd_copy",
                "options: a Record {bs?, count?}",
                other.type_name(),
            ))
        }
    }
    #[cfg(windows)]
    {
        dd_copy_in_process(&src, &dst, &operands)
    }
    #[cfg(not(windows))]
    {
        // dd opens the destination itself, so under the jail the copy runs
        // in-process instead, where the link count is read from the handle the
        // bytes are written through.
        if crate::safety::jail_enforced(crate::safety::current_mode()) {
            return dd_copy_in_process(&src, &dst, &operands);
        }
        // dd writes the destination in place, as the in-process copy does.
        crate::tx::snapshot(&dst);
        let argv: Vec<&str> = operands.iter().map(String::as_str).collect();
        let run = tool_run(
            "dd_copy",
            "dd",
            None,
            &argv,
            Keep::Tail(TOOL_STDERR_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?;
        if !run.success {
            return Err(crate::safety::tool_failed(
                "dd_copy",
                &run.command,
                run.code,
                &run.stderr,
            ));
        }
        let mut rec = BTreeMap::new();
        rec.insert("success".to_string(), Value::Bool(true));
        // dd reports what it copied on stderr.
        rec.insert("output".to_string(), Value::Str(run.stderr));
        Ok(Value::Record(rec))
    }
}

/// Largest block dd_copy's in-process copy reads at once.
const DD_BLOCK_MAX: u64 = 64 * 1024 * 1024;

/// The byte count of a `dd` block size already checked by [`dd_block_size`].
fn dd_block_bytes(bs: &str) -> Option<u64> {
    let (digits, unit) = match bs.char_indices().last() {
        Some((i, c)) if c.is_ascii_alphabetic() => {
            let unit: u64 = match c {
                'c' => 1,
                'w' => 2,
                'b' => 512,
                'k' | 'K' => 1 << 10,
                'M' => 1 << 20,
                'G' => 1 << 30,
                'T' => 1 << 40,
                _ => return None,
            };
            (&bs[..i], unit)
        }
        _ => (bs, 1),
    };
    digits.parse::<u64>().ok()?.checked_mul(unit)
}

/// dd's copy done in-process with the operands dd_copy built: always on
/// Windows, and elsewhere when the workspace jail is enforced, so the
/// destination is judged on the handle the bytes go through. The block size and
/// count are the ones the options gave (512 and no count when absent). The Unix
/// dd run has a 900 s deadline; this one is checked between blocks. The output
/// is the three report lines dd prints on stderr.
fn dd_copy_in_process(src: &str, dst: &str, operands: &[String]) -> Result<Value> {
    use std::io::{Read as _, Write as _};
    const NAME: &str = "dd_copy";
    let bs_text = operands
        .iter()
        .find_map(|o| o.strip_prefix("bs="))
        .unwrap_or("512");
    let block = dd_block_bytes(bs_text)
        .filter(|n| (1..=DD_BLOCK_MAX).contains(n))
        .ok_or_else(|| crate::safety::bad_arg(NAME, "a block size of at most 64M", bs_text))?;
    let count: Option<u64> = operands
        .iter()
        .find_map(|o| o.strip_prefix("count="))
        .map(|text| {
            text.parse::<u64>()
                .map_err(|_| crate::safety::bad_arg(NAME, "a positive Int", text))
        })
        .transpose()?;
    linux_diagnostics::file_path(NAME, src)?;
    linux_diagnostics::output_path(NAME, dst)?;
    // dd truncates its output before it reads, so a copy onto its own source
    // would destroy the source. Refuse it.
    let same = match (std::fs::canonicalize(src), std::fs::canonicalize(dst)) {
        (Ok(a), Ok(b)) => a == b,
        _ => false,
    };
    if same {
        return Err(crate::safety::bad_arg(
            NAME,
            "a destination other than the source",
            dst,
        ));
    }
    let mut input = std::fs::File::open(src).map_err(|e| dd_io(NAME, src, &e))?;
    // Record dst's pre-image (or its absence) before File::create truncates it.
    crate::tx::snapshot(dst);
    // Judged on its handle, then truncated: the copy starts with an empty file.
    let mut output =
        crate::safety::open_in_place(NAME, std::path::Path::new(dst), false).map_err(|e| {
            match e.downcast::<std::io::Error>() {
                Ok(io) => dd_io(NAME, dst, &io),
                Err(other) => other,
            }
        })?;
    let started = std::time::Instant::now();
    let limit = std::time::Duration::from_secs(TOOL_LONG_DEADLINE_SECS);
    let mut buf = vec![0u8; block as usize];
    let (mut full_in, mut part_in, mut full_out, mut part_out, mut bytes) =
        (0u64, 0u64, 0u64, 0u64, 0u64);
    let mut blocks = 0u64;
    loop {
        if let Some(n) = count {
            if blocks >= n {
                break;
            }
        }
        if started.elapsed() > limit {
            return Err(crate::safety::budget_exceeded(
                NAME,
                format!("the copy ran past {TOOL_LONG_DEADLINE_SECS} s and was stopped"),
                "copy less with count, or in smaller parts",
            ));
        }
        let n = match input.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => n,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(dd_io(NAME, src, &e)),
        };
        output
            .write_all(&buf[..n])
            .map_err(|e| dd_io(NAME, dst, &e))?;
        if n as u64 == block {
            full_in += 1;
            full_out += 1;
        } else {
            part_in += 1;
            part_out += 1;
        }
        bytes += n as u64;
        blocks += 1;
    }
    output.flush().map_err(|e| dd_io(NAME, dst, &e))?;
    let mut rec = BTreeMap::new();
    rec.insert("success".to_string(), Value::Bool(true));
    rec.insert(
        "output".to_string(),
        Value::Str(format!(
            "{full_in}+{part_in} records in\n{full_out}+{part_out} records out\n{bytes} bytes copied"
        )),
    );
    Ok(Value::Record(rec))
}

/// The coded error for a file dd_copy could not open, read or write.
fn dd_io(builtin: &str, path: &str, e: &std::io::Error) -> anyhow::Error {
    match e.kind() {
        std::io::ErrorKind::NotFound => crate::safety::not_found(builtin, "file", path),
        std::io::ErrorKind::PermissionDenied => crate::safety::os_denied(
            builtin,
            format!("`{path}` is not accessible: {e}"),
            "check the path and its permissions",
        ),
        // A device that stops answering, a full disk: still a coded refusal.
        _ => crate::safety::bad_state_with_hint(
            builtin,
            &format!("`{path}` failed: {e}"),
            "a readable source and a writable destination",
        ),
    }
}

/// A `dd` block size: digits with at most one unit suffix (`512`, `4M`, `1k`).
fn dd_block_size(bs: &str) -> bool {
    let digits = bs.trim_end_matches(|c: char| "cwbkKMGT".contains(c));
    !digits.is_empty()
        && digits.len() <= 12
        && bs.len() - digits.len() <= 1
        && digits.bytes().all(|b| b.is_ascii_digit())
        && digits.bytes().any(|b| b != b'0')
}

/// 975: bi_mount_info - Detailed mount info (cross-platform via sysinfo::Disks).
fn bi_mount_info(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let disks = Disks::new_with_refreshed_list();
    let entries: Vec<Value> = disks
        .iter()
        .map(|d| {
            let mut rec = BTreeMap::new();
            rec.insert(
                "device".to_string(),
                Value::Str(d.name().to_string_lossy().to_string()),
            );
            rec.insert(
                "mount_point".to_string(),
                Value::Str(d.mount_point().to_string_lossy().to_string()),
            );
            rec.insert(
                "file_system".to_string(),
                Value::Str(String::from_utf8_lossy(d.file_system().as_encoded_bytes()).to_string()),
            );
            rec.insert(
                "total_space".to_string(),
                Value::Int(d.total_space() as i64),
            );
            rec.insert(
                "available_space".to_string(),
                Value::Int(d.available_space() as i64),
            );
            rec.insert("is_removable".to_string(), Value::Bool(d.is_removable()));
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(entries))
}

// ============================================================================
// Remote Access Builtins (980-994)
// SSH, SCP, Rsync, SFTP, RDP, VNC, Telnet, Curl
// ============================================================================

// [removed duplicate] use std::collections::BTreeMap;
// [removed duplicate] use std::process::Command;
// [removed duplicate] use anyhow::{anyhow, Result};
// [removed duplicate] use crate::value::Value;

// ---------------------------------------------------------------------------
// Shared runner for the remote, crypto and archive tools below.
//
// A tool starts from an argv (never a shell), with a null or fixed stdin, under
// a deadline. Its output is bounded, and a run that exceeds a bound is stopped
// and refused (E_BUDGET_EXCEEDED): a cut-off answer reads like a complete one.
// ---------------------------------------------------------------------------

/// Most bytes a tool run may write to captured stdout, or to stderr.
const TOOL_OUTPUT_CAP: u64 = 16 * 1024 * 1024;
/// Most bytes a tool run may write to a file. For xz and zstd this is the
/// decompressed size, which is the bomb a small archive can hide.
const FILE_OUTPUT_CAP: u64 = 1024 * 1024 * 1024;
/// Deadline for a command or transfer that contacts a host, or that may stop
/// for a prompt that nobody will answer.
const NETWORK_DEADLINE_SECS: u64 = 120;
/// Deadline for a local crypto, archive or transfer run.
const LOCAL_DEADLINE_SECS: u64 = 600;
/// Most bytes of JSON text the jq builtins accept.
const JQ_INPUT_CAP: usize = 64 * 1024 * 1024;
/// Options every ssh run gets: no terminal, and no prompt that waits for a
/// person to type. A host that needs a password fails instead of hanging.
const SSH_OPTS: &[&str] = &["-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=20"];
/// The scp equivalent of [`SSH_OPTS`].
const SCP_OPTS: &[&str] = &["-o", "BatchMode=yes", "-o", "ConnectTimeout=20"];

const HALT_NONE: u8 = 0;
const HALT_OVER_CAP: u8 = 1;
const HALT_IO: u8 = 2;

/// Copies one pipe into `sink` until the pipe closes. When the stream passes
/// `cap`, or a read or write fails, it records why in `halt` and stops.
fn pump<R, W>(
    mut pipe: R,
    sink: std::sync::Arc<std::sync::Mutex<W>>,
    cap: u64,
    halt: std::sync::Arc<std::sync::atomic::AtomicU8>,
    done: std::sync::mpsc::Sender<()>,
) where
    R: std::io::Read + Send + 'static,
    W: std::io::Write + Send + 'static,
{
    use std::io::ErrorKind;
    use std::sync::atomic::Ordering;
    std::thread::spawn(move || {
        let mut total: u64 = 0;
        let mut chunk = [0u8; 8192];
        loop {
            match pipe.read(&mut chunk) {
                Ok(0) => break,
                Ok(n) => {
                    total = total.saturating_add(n as u64);
                    if total > cap {
                        halt.store(HALT_OVER_CAP, Ordering::SeqCst);
                        break;
                    }
                    let mut w = sink
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    if w.write_all(&chunk[..n]).is_err() {
                        halt.store(HALT_IO, Ordering::SeqCst);
                        break;
                    }
                }
                Err(e) if e.kind() == ErrorKind::Interrupted => {}
                Err(_) => {
                    halt.store(HALT_IO, Ordering::SeqCst);
                    break;
                }
            }
        }
        let _ = done.send(());
    });
}

/// The refusal for a run that was stopped: over a cap, a failed pipe, or the deadline.
fn halt_error(builtin: &str, tool: &str, flag: u8, secs: u64, cap: u64) -> anyhow::Error {
    match flag {
        HALT_OVER_CAP => crate::safety::budget_exceeded(
            builtin,
            format!("{tool} wrote more than {cap} bytes and was stopped"),
            "the output would be cut short, so it is refused; narrow the request",
        ),
        HALT_IO => crate::safety::tool_failed(
            builtin,
            tool,
            None,
            "its output could not be read or written",
        ),
        _ => crate::safety::budget_exceeded(
            builtin,
            format!("{tool} did not finish within {secs} s and was stopped"),
            "the call is refused rather than answered in part; check the host, file or network and try again",
        ),
    }
}

/// Runs `cmd` for at most `secs`. Stdout goes to `stdout`; stderr is captured.
/// Returns the exit status and the stderr text. A run that exceeds `cap`, or
/// its deadline, is killed and refused. A nonzero exit is not an error here;
/// see [`tool_ok`].
fn run_tool<W>(
    builtin: &str,
    tool: &str,
    mut cmd: std::process::Command,
    stdin: Option<Vec<u8>>,
    stdout: std::sync::Arc<std::sync::Mutex<W>>,
    secs: u64,
    cap: u64,
) -> Result<(std::process::ExitStatus, String)>
where
    W: std::io::Write + Send + 'static,
{
    use std::io::Write as _;
    use std::process::Stdio;
    use std::sync::atomic::{AtomicU8, Ordering};
    use std::sync::{mpsc, Arc, Mutex, PoisonError};
    use std::time::{Duration, Instant};

    let halt = Arc::new(AtomicU8::new(HALT_NONE));
    crate::safety::strip_ironshell_env(&mut cmd);
    cmd.stdin(if stdin.is_some() {
        Stdio::piped()
    } else {
        Stdio::null()
    })
    .stdout(Stdio::piped())
    .stderr(Stdio::piped());
    #[cfg(unix)]
    {
        // The child leads its own group, so a deadline or cap kills its whole tree.
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    let mut child = cmd
        .spawn()
        .map_err(|e| crate::safety::spawn_error(builtin, tool, &e))?;
    #[cfg(windows)]
    let job = TreeJob::for_child(&child);
    let (Some(out_pipe), Some(err_pipe)) = (child.stdout.take(), child.stderr.take()) else {
        #[cfg(windows)]
        kill_job(job.as_ref());
        kill_tree(&mut child);
        return Err(crate::safety::tool_failed(
            builtin,
            tool,
            None,
            "its output pipes were not opened",
        ));
    };
    if let (Some(payload), Some(mut pipe)) = (stdin, child.stdin.take()) {
        // Detached: a child that never reads its stdin must not hold this call.
        // A failed write just ends early, and the exit status reports why.
        std::thread::spawn(move || {
            let _ = pipe.write_all(&payload);
        });
    }
    let stderr = Arc::new(Mutex::new(Vec::<u8>::new()));
    let (out_done, out_closed) = mpsc::channel();
    let (err_done, err_closed) = mpsc::channel();
    pump(out_pipe, stdout, cap, Arc::clone(&halt), out_done);
    pump(
        err_pipe,
        Arc::clone(&stderr),
        cap,
        Arc::clone(&halt),
        err_done,
    );

    let limit = Duration::from_secs(secs);
    let started = Instant::now();
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) => {}
            Err(e) => {
                #[cfg(windows)]
                kill_job(job.as_ref());
                kill_tree(&mut child);
                return Err(crate::safety::tool_failed(
                    builtin,
                    tool,
                    None,
                    &e.to_string(),
                ));
            }
        }
        if halt.load(Ordering::SeqCst) != HALT_NONE || started.elapsed() >= limit {
            #[cfg(windows)]
            kill_job(job.as_ref());
            kill_tree(&mut child);
            return Err(halt_error(
                builtin,
                tool,
                halt.load(Ordering::SeqCst),
                secs,
                cap,
            ));
        }
        std::thread::sleep(Duration::from_millis(10));
    };
    // The pipes close with the child. A grandchild that keeps one open must not
    // hold the call, and output that has not closed is not returned.
    let wait = Duration::from_secs(2);
    let closed = out_closed.recv_timeout(wait).is_ok() && err_closed.recv_timeout(wait).is_ok();
    let flag = halt.load(Ordering::SeqCst);
    if !closed || flag != HALT_NONE {
        // A descendant still holds a pipe, or the run was halted: kill its group
        // so nothing it started keeps running after the call returns.
        #[cfg(windows)]
        kill_job(job.as_ref());
        kill_group(child.id());
    }
    if flag != HALT_NONE {
        return Err(halt_error(builtin, tool, flag, secs, cap));
    }
    if !closed {
        return Err(crate::safety::tool_failed(
            builtin,
            tool,
            status.code(),
            "its output stayed open after it exited",
        ));
    }
    let bytes = stderr.lock().unwrap_or_else(PoisonError::into_inner);
    Ok((status, String::from_utf8_lossy(&bytes).into_owned()))
}

/// A nonzero exit is a coded tool failure, with the exit status and the tail of stderr.
fn tool_ok(
    builtin: &str,
    tool: &str,
    status: std::process::ExitStatus,
    stderr: &str,
) -> Result<()> {
    if status.success() {
        return Ok(());
    }
    Err(crate::safety::tool_failed(
        builtin,
        tool,
        status.code(),
        stderr_tail(stderr),
    ))
}

/// The last 4 KiB of a tool's stderr, for an error message.
fn stderr_tail(text: &str) -> &str {
    const KEEP: usize = 4096;
    let text = text.trim();
    if text.len() <= KEEP {
        return text;
    }
    let mut start = text.len() - KEEP;
    while !text.is_char_boundary(start) {
        start += 1;
    }
    text[start..].trim()
}

/// Runs a tool that answers on stdout. Returns that text and the stderr text
/// once the tool exits 0; any other exit is a coded tool failure.
fn run_checked(
    builtin: &str,
    tool: &str,
    cmd: std::process::Command,
    secs: u64,
) -> Result<(String, String)> {
    let out = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
    let (status, stderr) = run_tool(
        builtin,
        tool,
        cmd,
        None,
        std::sync::Arc::clone(&out),
        secs,
        TOOL_OUTPUT_CAP,
    )?;
    tool_ok(builtin, tool, status, &stderr)?;
    let bytes = std::mem::take(
        &mut *out
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner),
    );
    Ok((String::from_utf8_lossy(&bytes).into_owned(), stderr))
}

/// Runs a tool whose stdout is the new file `out_path`. The file is created
/// exclusively, so an existing file is refused, and it is removed when the run fails.
fn tool_to_new_file(builtin: &str, tool: &str, argv: &[&str], out_path: &str) -> Result<()> {
    let file = create_new_output(builtin, out_path)?;
    let sink = std::sync::Arc::new(std::sync::Mutex::new(file));
    let mut cmd = crate::safety::child_command(tool);
    cmd.args(argv);
    let result = run_tool(
        builtin,
        tool,
        cmd,
        None,
        sink,
        LOCAL_DEADLINE_SECS,
        FILE_OUTPUT_CAP,
    )
    .and_then(|(status, stderr)| tool_ok(builtin, tool, status, &stderr));
    if result.is_err() {
        remove_partial(out_path);
    }
    result
}

/// Runs a tool whose stdout is a stream, and writes that stream gzipped to the
/// new file `out_path` (in-process, flate2: no gzip program is needed). Like
/// [`tool_to_new_file`], an existing file is refused and a failed run removes it.
fn tool_to_new_gzip_file(builtin: &str, tool: &str, argv: &[&str], out_path: &str) -> Result<()> {
    let file = create_new_output(builtin, out_path)?;
    let sink = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
    let mut cmd = crate::safety::child_command(tool);
    cmd.args(argv);
    let result = run_tool(
        builtin,
        tool,
        cmd,
        None,
        sink.clone(),
        LOCAL_DEADLINE_SECS,
        FILE_OUTPUT_CAP,
    )
    .and_then(|(status, stderr)| tool_ok(builtin, tool, status, &stderr))
    .and_then(|()| {
        let bytes = std::mem::take(
            &mut *sink
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        );
        let mut enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
        std::io::Write::write_all(&mut enc, &bytes)
            .and_then(|()| enc.finish().map(|_| ()))
            .map_err(|e| crate::safety::fs_error(builtin, out_path, &e))
    });
    if result.is_err() {
        remove_partial(out_path);
    }
    result
}

/// Creates a new file for a tool's output. Existing files are refused, and the
/// check and the create are one open, so a file that appears meanwhile is refused too.
fn create_new_output(builtin: &str, path: &str) -> Result<std::fs::File> {
    // Record that the path did not exist, so a rollback removes the file this
    // creates. A safety net: the tool_to_new_file builtins (tar_create, bzip2, xz,
    // zstd) are in tx::IRREVERSIBLE and refused inside a transaction before they
    // get here, and the gzip builtins snapshot their output themselves.
    crate::tx::snapshot(path);
    // The undo journal's step for the file this call creates: absent before, so
    // undo removes it. Only a builtin that writes files is recorded; a failed
    // call's step is dropped by the dispatcher.
    if matches!(
        crate::safety::effect_of(builtin),
        crate::safety::Effect::WriteLocal | crate::safety::Effect::Destructive
    ) {
        crate::journal::record_group(
            builtin,
            crate::safety::Effect::WriteLocal,
            vec![path.to_string()],
        );
    }
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|e| {
            if e.kind() == std::io::ErrorKind::AlreadyExists {
                crate::safety::bad_state_with_hint(
                    builtin,
                    &format!("{path} already exists"),
                    "remove it first; the existing file is not overwritten",
                )
            } else {
                crate::safety::fs_error(builtin, path, &e)
            }
        })
}

/// The undo journal's step for a file the call is about to create (absent
/// before, so undo removes it). For a tool that writes its own output file, which
/// no argument of the journal's guess names, or names as a bare file name.
fn journal_new_file(builtin: &str, path: &str) {
    crate::journal::record_group(
        builtin,
        crate::safety::Effect::WriteLocal,
        vec![path.to_string()],
    );
}

/// Refuses an output path that already exists, for a tool that writes its own file.
fn refuse_existing(builtin: &str, path: &str) -> Result<()> {
    if std::path::Path::new(path).exists() {
        return Err(crate::safety::bad_state_with_hint(
            builtin,
            &format!("{path} already exists"),
            "remove it first; the existing file is not overwritten",
        ));
    }
    Ok(())
}

/// Removes a file a failed run may have left. Only ever called on a path that
/// was checked absent before the run, so the file is the run's own. A failure
/// other than absence is logged; output that may be secret, or that the caller
/// is told is gone, goes through `fail_removing_partial` so the error names it.
fn remove_partial(path: &str) {
    if let Err(e) = std::fs::remove_file(path) {
        if e.kind() != std::io::ErrorKind::NotFound {
            tracing::warn!("{path} was left behind by a failed run and could not be removed: {e}");
        }
    }
}

/// Removes a failed run's output and returns the run's error, naming the file if
/// it could not be removed. For output that may be secret or that the caller is
/// told is gone: the caller has to know it is still there.
fn fail_removing_partial(error: anyhow::Error, path: &str) -> anyhow::Error {
    match std::fs::remove_file(path) {
        Err(e) if e.kind() != std::io::ErrorKind::NotFound => crate::safety::with_note(
            error,
            &format!("{path} was left behind and could not be removed: {e}"),
        ),
        _ => error,
    }
}

#[cfg(test)]
mod partial_cleanup_tests {
    use super::fail_removing_partial;

    #[test]
    fn a_partial_that_cannot_be_removed_is_named_and_keeps_the_code() {
        // remove_file never deletes a directory, on any platform, so a directory
        // stands in for a partial output that cannot be removed.
        let dir = std::env::temp_dir().join(format!("ish-partial-cleanup-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("create the stand-in directory");
        let dir_str = dir.to_str().expect("temp path is UTF-8");
        let err = fail_removing_partial(crate::safety::bad_arg("t", "x", "y"), dir_str);
        let plain = crate::safety::bad_arg("t", "x", "y");
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(crate::safety::code_of(&err), crate::safety::code_of(&plain));
        // Where an agent reads it: the coded error, not an anyhow context layer.
        let coded = err
            .downcast_ref::<crate::safety::SafetyError>()
            .expect("still a coded error");
        assert!(coded.message.contains("left behind"), "got: {coded}");
    }

    #[test]
    fn a_partial_already_gone_adds_nothing() {
        let path = std::env::temp_dir().join(format!("ish-partial-absent-{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let path_str = path.to_str().expect("temp path is UTF-8");
        let expected = format!("{:#}", crate::safety::bad_arg("t", "x", "y"));
        let err = fail_removing_partial(crate::safety::bad_arg("t", "x", "y"), path_str);
        assert_eq!(format!("{err:#}"), expected);
    }
}

/// A caller value in a positional slot, refused when it could be read as an option.
fn refuse_option(builtin: &str, value: &str) -> Result<()> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])
}

/// The path must name an existing regular file.
fn regular_file_arg(builtin: &str, path: &str) -> Result<()> {
    let meta = std::fs::metadata(path).map_err(|e| crate::safety::fs_error(builtin, path, &e))?;
    if !meta.is_file() {
        return Err(crate::safety::bad_arg(builtin, "a regular file", path));
    }
    Ok(())
}

/// A `[user@]host` for ssh, scp and ssh-copy-id. It is refused when it could be
/// read as an option (`-oProxyCommand=…`), when it is empty, or when it holds a
/// character a host name, address or user name does not use.
fn ssh_target_arg(builtin: &str, what: &str, target: &str) -> Result<()> {
    refuse_option(builtin, target)?;
    let (user, host) = match target.rsplit_once('@') {
        Some((user, host)) => (Some(user), host),
        None => (None, target),
    };
    let chars_ok = target.chars().all(|c| {
        c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | ':' | '[' | ']' | '%' | '@')
    });
    let user_ok = match user {
        Some(user) => !user.is_empty() && !user.starts_with('-'),
        None => true,
    };
    if !target.is_empty()
        && target.len() <= 255
        && chars_ok
        && user_ok
        && !host.is_empty()
        && !host.starts_with('-')
    {
        return Ok(());
    }
    Err(crate::safety::bad_arg(
        builtin,
        &format!("{what} as [user@]host of letters, digits and . _ - : [ ] % @"),
        target,
    ))
}

/// A tunnel's destination: a host name, an IPv4 address, or a bracketed IPv6 address.
fn tunnel_host_arg(builtin: &str, host: &str) -> Result<()> {
    refuse_option(builtin, host)?;
    let ok = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
        Some(addr) => {
            !addr.is_empty()
                && addr
                    .chars()
                    .all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.'))
        }
        None => {
            !host.is_empty()
                && host.len() <= 253
                && host
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
        }
    };
    if ok {
        return Ok(());
    }
    Err(crate::safety::bad_arg(
        builtin,
        "remote_host as a host name, an IPv4 address or a bracketed IPv6 address",
        host,
    ))
}

/// An scp remote, `[user@]host:path`. The host is checked as [`ssh_target_arg`]
/// checks it. The path must be one file: it may not hold a shell
/// metacharacter, a glob, or a control character, because the remote side may
/// read it through a shell.
fn scp_remote_arg(builtin: &str, remote: &str) -> Result<()> {
    let bad = || crate::safety::bad_arg(builtin, "a remote of the form [user@]host:path", remote);
    // A user name ends at the first '@' that comes before any ':' or '/'. A
    // later '@' belongs to the path.
    let user_len = match remote.find('@') {
        Some(i) if !remote[..i].contains([':', '/']) => i + 1,
        _ => 0,
    };
    let rest = &remote[user_len..];
    let colon = if rest.starts_with('[') {
        rest.find("]:").map(|i| i + 1)
    } else {
        rest.find(':')
    };
    let Some(colon) = colon else {
        return Err(bad());
    };
    ssh_target_arg(builtin, "remote host", &remote[..user_len + colon])?;
    let path = &remote[user_len + colon + 1..];
    if path.is_empty() {
        return Err(bad());
    }
    if path
        .chars()
        .any(|c| c.is_control() || "`$;&|<>()'\"\\{}*?[]".contains(c))
    {
        return Err(crate::safety::bad_arg(
            builtin,
            "a remote path with no shell or glob characters (one file)",
            path,
        ));
    }
    Ok(())
}

/// The host of an scp remote that [`scp_remote_arg`] has accepted: the part
/// between the user's `@` and the `:` that ends it (a bracketed address keeps its
/// brackets).
fn scp_remote_host(remote: &str) -> &str {
    let rest = match remote.find('@') {
        Some(i) if !remote[..i].contains([':', '/']) => &remote[i + 1..],
        _ => remote,
    };
    let end = if rest.starts_with('[') {
        rest.find("]:").map_or(rest.len(), |i| i + 1)
    } else {
        rest.find(':').unwrap_or(rest.len())
    };
    &rest[..end]
}

/// A local scp operand. scp reads a path with a ':' in it as a host, so a local
/// path must not have one, apart from a Windows drive letter.
fn scp_local_arg(builtin: &str, path: &str) -> Result<()> {
    refuse_option(builtin, path)?;
    let bytes = path.as_bytes();
    let rest = if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
        &path[2..]
    } else {
        path
    };
    if rest.contains(':') {
        return Err(crate::safety::bad_arg(
            builtin,
            "a local path without ':' (scp would read it as a host)",
            path,
        ));
    }
    Ok(())
}

/// The text, when it is one OpenSSH public key line: a key type, a base64 blob
/// and an optional comment, and nothing else. Anything else is refused by the
/// caller, and its content is not echoed.
fn public_key_line(text: &str) -> Option<&str> {
    let line = text.trim();
    if line.is_empty() || line.len() > 16 * 1024 || line.contains(['\n', '\r']) {
        return None;
    }
    let mut parts = line.splitn(3, ' ');
    let kind = parts.next()?;
    let blob = parts.next()?;
    let kind_ok =
        (kind.starts_with("ssh-") || kind.starts_with("ecdsa-sha2-") || kind.starts_with("sk-"))
            && kind
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '@' | '.'));
    let blob_ok = !blob.is_empty()
        && blob
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '='));
    let comment_ok = match parts.next() {
        None => true,
        Some(comment) => comment
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '@' | '.' | '_' | '-' | '+' | ' ')),
    };
    if kind_ok && blob_ok && comment_ok {
        Some(line)
    } else {
        None
    }
}

// 980: bi_ssh_exec - Run one command on a remote host over ssh.
//
// The command is one string and the remote account's login shell reads it, so
// the remote side expands it as that shell does. The host never reaches a
// local shell. Exit 0 returns the output. Any other exit is E_TOOL_FAILED with
// the exit status and the tail of stderr. Output past the cap, or a run past
// its deadline, is refused.
fn bi_ssh_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("ssh_exec", &input)?;
    let host = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "ssh_exec: first argument must be host string (user@host)",
            ))
        }
    };
    let command = match args.get(1) {
        Some(Value::Str(s)) if !s.trim().is_empty() && !s.contains('\0') => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "ssh_exec: second argument must be a non-empty command string",
            ))
        }
    };
    let port = match args.get(2) {
        Some(Value::Int(p)) => Some(*p),
        _ => None,
    };
    ssh_target_arg("ssh_exec", "host", &host)?;
    // The destination is the host argument as written. An ssh config alias that
    // is not a dotted name is refused by the allowlist (no host can be read), and
    // a dotted alias is judged by its name, not by the HostName ssh config gives it.
    let egress_host = crate::safety::ssh_egress_host("ssh_exec", &host)?;
    crate::safety::check_egress("ssh_exec", std::slice::from_ref(&egress_host))?;
    // Runs an arbitrary command on another host: the widest blast radius in the
    // builtin table. Checked after the arguments, so a refused call is not audited
    // as a run.
    crate::safety::guard_exec("ssh_exec", format!("ssh {} {}", host, command))?;
    let mut cmd = crate::safety::child_command("ssh");
    cmd.args(SSH_OPTS);
    if let Some(p) = port {
        cmd.arg("-p").arg(p.to_string());
    }
    cmd.arg(&host).arg(&command);
    let (stdout, stderr) = run_checked("ssh_exec", "ssh", cmd, NETWORK_DEADLINE_SECS)?;
    Ok(rec(vec![
        ("stdout", s(&stdout)),
        ("stderr", s(&stderr)),
        ("exit_code", Value::Int(0)),
        ("success", Value::Bool(true)),
    ]))
}

// 981: bi_ssh_tunnel - Open a local port forward through an ssh host.
//
// ssh runs in the foreground (`-N`, not `-f`), so this process holds the ssh
// pid and the call answers it: proc_kill(pid) stops the tunnel. The call returns
// once the forward is listening, or fails when ssh exits or the deadline passes.
// The local port must be free before ssh starts: a connect to a port something
// else holds would report a tunnel that ssh never opened. ExitOnForwardFailure
// makes a port that cannot be bound an error rather than a silent tunnel that
// does nothing.
fn bi_ssh_tunnel(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("ssh_tunnel", &input)?;
    let local_port = match args.first() {
        Some(Value::Int(p)) => *p,
        _ => {
            return Err(crate::safety::arg_err(
                "ssh_tunnel: first argument must be local_port (Int)",
            ))
        }
    };
    let remote_host = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "ssh_tunnel: second argument must be remote_host string",
            ))
        }
    };
    let remote_port = match args.get(2) {
        Some(Value::Int(p)) => *p,
        _ => {
            return Err(crate::safety::arg_err(
                "ssh_tunnel: third argument must be remote_port (Int)",
            ))
        }
    };
    let ssh_host = match args.get(3) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "ssh_tunnel: fourth argument must be ssh_host string",
            ))
        }
    };
    for (what, port) in [("local_port", local_port), ("remote_port", remote_port)] {
        if !(1..=65535).contains(&port) {
            return Err(crate::safety::bad_arg(
                "ssh_tunnel",
                &format!("{what} in 1..=65535"),
                &port.to_string(),
            ));
        }
    }
    tunnel_host_arg("ssh_tunnel", &remote_host)?;
    ssh_target_arg("ssh_tunnel", "ssh_host", &ssh_host)?;
    // Both named hosts are judged: ssh_host is connected to, and remote_host is
    // the destination the forward reaches through it. Each is judged by its name.
    // remote_host is not passed through `ssh_egress_host`, on purpose: in
    // `ssh -L port:remote_host:port host` the far end opens the connection to
    // remote_host with its own resolver, so the local ~/.ssh/config (which only
    // rewrites the destination ssh itself connects to) has no bearing on it.
    // The name as written is what the server will be asked to reach.
    let ssh_egress = crate::safety::ssh_egress_host("ssh_tunnel", &ssh_host)?;
    crate::safety::check_egress("ssh_tunnel", &[ssh_egress, remote_host.clone()])?;
    // Checked above to be in 1..=65535.
    let port = local_port as u16;
    // Refused when something already holds the port. The probe listener is
    // dropped here, before ssh is started. A bind error other than "in use"
    // (for example a privileged port) is refused the same way, with the OS text.
    match std::net::TcpListener::bind(("127.0.0.1", port)) {
        Ok(listener) => drop(listener),
        Err(e) => {
            return Err(crate::safety::bad_arg(
                "ssh_tunnel",
                &format!("a local_port that is free on 127.0.0.1 (bind said: {e})"),
                &local_port.to_string(),
            ))
        }
    }
    let spec = format!("{local_port}:{remote_host}:{remote_port}");
    // ssh's stderr goes to a new file, not a pipe: nothing reads a pipe after
    // this call returns, and a full pipe would block ssh. The file name carries
    // the port and this process's pid, plus a uuid so a stale file cannot collide.
    let stderr_path = std::env::temp_dir().join(format!(
        "ae-ssh-tunnel-{local_port}-{}-{}.err",
        std::process::id(),
        uuid::Uuid::new_v4().simple()
    ));
    let stderr_path = stderr_path.to_string_lossy().into_owned();
    let stderr_file = create_new_output("ssh_tunnel", &stderr_path)?;
    let mut cmd = crate::safety::child_command("ssh");
    crate::safety::strip_ironshell_env(&mut cmd);
    cmd.args(["-N", "-o", "ExitOnForwardFailure=yes"])
        .args(SSH_OPTS)
        .arg("-L")
        .arg(&spec)
        .arg(&ssh_host)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(stderr_file);
    let mut child = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            remove_partial(&stderr_path);
            return Err(crate::safety::spawn_error("ssh_tunnel", "ssh", &e));
        }
    };
    drop(cmd);
    // Wait until the forward listens, ssh exits, or the deadline passes. The
    // deadline is the network one, or the evaluation's own if that is sooner.
    let mut limit = std::time::Duration::from_secs(NETWORK_DEADLINE_SECS);
    if let Some(left) = crate::safety::remaining_deadline() {
        limit = limit.min(left);
    }
    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    let started = std::time::Instant::now();
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let stderr = std::fs::read_to_string(&stderr_path).unwrap_or_default();
                remove_partial(&stderr_path);
                return Err(crate::safety::tool_failed(
                    "ssh_tunnel",
                    "ssh",
                    status.code(),
                    &tail_text(stderr.trim(), 300),
                ));
            }
            Ok(None) => {}
            Err(e) => {
                let _ = child.kill();
                let _ = child.wait();
                remove_partial(&stderr_path);
                return Err(crate::safety::tool_failed(
                    "ssh_tunnel",
                    "ssh",
                    None,
                    &e.to_string(),
                ));
            }
        }
        if std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(200))
            .is_ok()
        {
            break;
        }
        if started.elapsed() >= limit {
            let _ = child.kill();
            let _ = child.wait();
            remove_partial(&stderr_path);
            return Err(crate::safety::budget_exceeded(
                "ssh_tunnel",
                format!(
                    "ssh did not open the forward on 127.0.0.1:{port} within {:.1} s and was stopped",
                    limit.as_secs_f64()
                ),
                "the call is refused rather than answered in part; check the host, its key authentication and the network, and try again",
            ));
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    // The forward is up. The child is not waited for: dropping it does not kill
    // it, and it is the tunnel. Its pid is the answer, and proc_wait may reap it.
    remove_partial(&stderr_path);
    let pid = i64::from(child.id());
    spawned_note(pid);
    Ok(rec(vec![
        ("success", Value::Bool(true)),
        ("pid", Value::Int(pid)),
        ("local_port", Value::Int(local_port)),
        ("remote_host", Value::Str(remote_host)),
        ("remote_port", Value::Int(remote_port)),
        ("ssh_host", Value::Str(ssh_host)),
    ]))
}

// 982: bi_ssh_keygen - Generate an SSH key pair.
//
// The private key is written with no passphrase (`-N ""`), so anyone who can
// read the file can use the key. A key or public-key file that already exists
// is refused, not replaced. The jail applies to the private key's path, so a
// default under ~/.ssh is refused unless that path is inside the workspace.
fn bi_ssh_keygen(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("ssh_keygen", &input)?;
    let key_type = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => "ed25519".to_string(),
    };
    if !matches!(key_type.as_str(), "ed25519" | "rsa" | "ecdsa") {
        return Err(crate::safety::bad_arg(
            "ssh_keygen",
            "type: ed25519, rsa or ecdsa",
            &key_type,
        ));
    }
    let filename = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            let home = std::env::var("HOME")
                .or_else(|_| std::env::var("USERPROFILE"))
                .unwrap_or_else(|_| ".".to_string());
            format!("{}/.ssh/id_{}", home, key_type)
        }
    };
    refuse_option("ssh_keygen", &filename)?;
    // The jail is checked first, so the existence test looks at the path the
    // key would really be written to.
    let filename = guard_local_write("ssh_keygen", &filename)?;
    let public = format!("{filename}.pub");
    refuse_existing("ssh_keygen", &filename)?;
    refuse_existing("ssh_keygen", &public)?;
    // Both files are new: one journal step, so undo removes the pair (the
    // public key is derived, so no argument names it).
    crate::journal::record_group(
        "ssh_keygen",
        crate::safety::Effect::WriteLocal,
        vec![filename.clone(), public.clone()],
    );
    let mut cmd = crate::safety::child_command("ssh-keygen");
    cmd.args(["-t", key_type.as_str(), "-f", filename.as_str(), "-N", ""]);
    match run_checked("ssh_keygen", "ssh-keygen", cmd, LOCAL_DEADLINE_SECS) {
        Ok((output, _)) => Ok(rec(vec![
            ("passphrase", Value::Bool(false)),
            ("type", Value::Str(key_type)),
            ("private_key", Value::Str(filename)),
            ("public_key", Value::Str(public)),
            ("output", Value::Str(output)),
        ])),
        Err(e) => {
            // Both paths were checked absent above, so anything there now is ours.
            Err(fail_removing_partial(
                fail_removing_partial(e, &filename),
                &public,
            ))
        }
    }
}

// 983: bi_ssh_copy_id - Install a public key in a remote account's authorized_keys.
//
// This writes to the remote host. The key must be one OpenSSH public-key line,
// so a private key or a stray file is refused without its content being shown.
// On Windows the line is appended by a remote shell command. Its quoting relies
// on the key holding no quote character, which public_key_line guarantees, and
// a grep keeps a second copy from being appended.
fn bi_ssh_copy_id(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("ssh_copy_id", &input)?;
    let host = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "ssh_copy_id: first argument must be host string (user@host)",
            ))
        }
    };
    let key_file = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            let home = std::env::var("HOME")
                .or_else(|_| std::env::var("USERPROFILE"))
                .unwrap_or_else(|_| ".".to_string());
            format!("{}/.ssh/id_ed25519.pub", home)
        }
    };
    ssh_target_arg("ssh_copy_id", "host", &host)?;
    let egress_host = crate::safety::ssh_egress_host("ssh_copy_id", &host)?;
    crate::safety::check_egress("ssh_copy_id", std::slice::from_ref(&egress_host))?;
    refuse_option("ssh_copy_id", &key_file)?;
    let key_file = crate::safety::resolve_path_str(&key_file);
    regular_file_arg("ssh_copy_id", &key_file)?;
    let size = std::fs::metadata(&key_file).map(|m| m.len()).unwrap_or(0);
    if size > 16 * 1024 {
        return Err(crate::safety::bad_arg(
            "ssh_copy_id",
            "key_file: an OpenSSH public key",
            &key_file,
        ));
    }
    let text = read_text_capped("ssh_copy_id", &key_file)?;
    let Some(key) = public_key_line(&text) else {
        return Err(crate::safety::bad_arg(
            "ssh_copy_id",
            "key_file: an OpenSSH public key (type, base64, optional comment)",
            &key_file,
        ));
    };
    if cfg!(target_os = "windows") {
        // ssh-copy-id may not be installed here, so the key is appended by hand.
        let remote = format!(
            "mkdir -p ~/.ssh && (grep -qxF '{key}' ~/.ssh/authorized_keys 2>/dev/null || echo '{key}' >> ~/.ssh/authorized_keys) && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"
        );
        let mut cmd = crate::safety::child_command("ssh");
        cmd.args(["-T", "-o", "ConnectTimeout=20"])
            .arg(&host)
            .arg(&remote);
        run_checked("ssh_copy_id", "ssh", cmd, NETWORK_DEADLINE_SECS)?;
        Ok(rec(vec![
            ("success", Value::Bool(true)),
            ("method", s("manual")),
            ("host", Value::Str(host)),
        ]))
    } else {
        let mut cmd = crate::safety::child_command("ssh-copy-id");
        cmd.args(["-i", key_file.as_str()]).arg(&host);
        run_checked("ssh_copy_id", "ssh-copy-id", cmd, NETWORK_DEADLINE_SECS)?;
        Ok(rec(vec![
            ("success", Value::Bool(true)),
            ("method", s("ssh-copy-id")),
            ("host", Value::Str(host)),
        ]))
    }
}

/// The value of an ssh config `Port` line: a decimal number from 1 to 65535.
/// Anything else is `None`.
fn ssh_port_value(val: &str) -> Option<i64> {
    val.trim()
        .parse::<u16>()
        .ok()
        .filter(|p| *p != 0)
        .map(i64::from)
}

// 984: bi_ssh_config - Read and parse SSH config file
fn bi_ssh_config(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let config_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            let home = std::env::var("HOME")
                .or_else(|_| std::env::var("USERPROFILE"))
                .unwrap_or_else(|_| ".".to_string());
            format!("{}/.ssh/config", home)
        }
    };
    // A missing file is E_NOT_FOUND from the read; a denied or oversized one
    // keeps its own code. Every failure used to read as "not found".
    let content = read_text_capped("ssh_config", &config_path)?;
    let mut hosts: Vec<Value> = Vec::new();
    let mut current: Option<BTreeMap<String, Value>> = None;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let parts: Vec<&str> = trimmed.splitn(2, char::is_whitespace).collect();
        if parts.len() < 2 {
            continue;
        }
        let key = parts[0].to_lowercase();
        let val = parts[1].trim().to_string();
        if key == "host" {
            if let Some(entry) = current.take() {
                hosts.push(Value::Record(entry));
            }
            let mut entry = BTreeMap::new();
            entry.insert("Host".to_string(), Value::Str(val));
            current = Some(entry);
        } else if let Some(ref mut entry) = current {
            match key.as_str() {
                "hostname" => {
                    entry.insert("HostName".to_string(), Value::Str(val));
                }
                "user" => {
                    entry.insert("User".to_string(), Value::Str(val));
                }
                "port" => {
                    // A malformed Port used to become 22, a connection to a
                    // port the host may not serve. It is refused instead.
                    let port = ssh_port_value(&val).ok_or_else(|| {
                        let host = match entry.get("Host") {
                            Some(Value::Str(h)) => h.as_str(),
                            _ => "?",
                        };
                        crate::safety::bad_arg(
                            "ssh_config",
                            "a Port number from 1 to 65535",
                            &format!("Port `{val}` for host `{host}`"),
                        )
                    })?;
                    entry.insert("Port".to_string(), Value::Int(port));
                }
                "identityfile" => {
                    entry.insert("IdentityFile".to_string(), Value::Str(val));
                }
                other => {
                    entry.insert(other.to_string(), Value::Str(val));
                }
            }
        }
    }
    if let Some(entry) = current {
        hosts.push(Value::Record(entry));
    }
    Ok(Value::Array(hosts))
}

// 985: bi_scp_upload - Copy one local file to a remote host with scp.
//
// The remote side is validated before the local file is looked at, so a bad
// remote is refused without touching the disk.
fn bi_scp_upload(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("scp_upload", &input)?;
    let local_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "scp_upload: first argument must be local_path string",
            ))
        }
    };
    let remote = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "scp_upload: second argument must be remote string (user@host:path)",
            ))
        }
    };
    let port = match args.get(2) {
        Some(Value::Int(p)) => Some(*p),
        _ => None,
    };
    scp_remote_arg("scp_upload", &remote)?;
    let egress_host = crate::safety::ssh_egress_host("scp_upload", scp_remote_host(&remote))?;
    crate::safety::check_egress("scp_upload", &[egress_host])?;
    let local_path = crate::safety::resolve_path_str(&local_path);
    scp_local_arg("scp_upload", &local_path)?;
    regular_file_arg("scp_upload", &local_path)?;
    let mut cmd = crate::safety::child_command("scp");
    cmd.args(SCP_OPTS);
    if let Some(p) = port {
        cmd.arg("-P").arg(p.to_string());
    }
    cmd.arg(&local_path).arg(&remote);
    run_checked("scp_upload", "scp", cmd, LOCAL_DEADLINE_SECS)?;
    Ok(rec(vec![
        ("success", Value::Bool(true)),
        ("local_path", Value::Str(local_path)),
        ("remote", Value::Str(remote)),
    ]))
}

// 986: bi_scp_download - Copy one remote file to a new local file with scp.
//
// The local destination is jailed like any write and must not exist: scp
// would otherwise replace it without a word. A failed transfer leaves no file.
fn bi_scp_download(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("scp_download", &input)?;
    let remote = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "scp_download: first argument must be remote string (user@host:path)",
            ))
        }
    };
    let local_path = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "scp_download: second argument must be local_path string",
            ))
        }
    };
    let port = match args.get(2) {
        Some(Value::Int(p)) => Some(*p),
        _ => None,
    };
    scp_remote_arg("scp_download", &remote)?;
    let egress_host = crate::safety::ssh_egress_host("scp_download", scp_remote_host(&remote))?;
    crate::safety::check_egress("scp_download", &[egress_host])?;
    refuse_option("scp_download", &local_path)?;
    // Self-guarded for the local write, so the fetch is guarded here too, as
    // `web_download` does: otherwise the central Network gate is skipped.
    guard_network("scp_download", &remote)?;
    let local_path = guard_local_write("scp_download", &local_path)?;
    scp_local_arg("scp_download", &local_path)?;
    refuse_existing("scp_download", &local_path)?;
    let mut cmd = crate::safety::child_command("scp");
    cmd.args(SCP_OPTS);
    if let Some(p) = port {
        cmd.arg("-P").arg(p.to_string());
    }
    cmd.arg(&remote).arg(&local_path);
    if let Err(e) = run_checked("scp_download", "scp", cmd, LOCAL_DEADLINE_SECS) {
        remove_partial(&local_path);
        return Err(e);
    }
    Ok(rec(vec![
        ("success", Value::Bool(true)),
        ("remote", Value::Str(remote)),
        ("local_path", Value::Str(local_path)),
    ]))
}

// 987: bi_rsync_sync - Rsync synchronization

/// 987 – rsync_sync(source, destination, [options]): rsync with a local path
/// inside the workspace or a `[user@]host:path` remote spec on either side. The
/// options Record names archive, compress, delete, verbose, progress and exclude;
/// with no Record the default is `-az`. A nonzero exit is E_TOOL_FAILED. Runs
/// with a 15 minute deadline. `delete` removes files on the destination.
fn bi_rsync_sync(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "rsync_sync";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    let source = k8s_need(B, "a source path or remote spec", &args, 0, ops_sync_path)?;
    let destination = k8s_need(
        B,
        "a destination path or remote spec",
        &args,
        1,
        ops_sync_path,
    )?;
    // A `host:path` operand runs over ssh, so ssh config can name another host.
    // A `host::module` operand is the rsync daemon, which ssh config does not reach.
    for spec in [&source, &destination] {
        if !ops_is_remote(spec) {
            continue;
        }
        let host = spec
            .split(':')
            .next()
            .unwrap_or("")
            .rsplit('@')
            .next()
            .unwrap_or("");
        let egress_host = if spec.contains("::") {
            host.to_string()
        } else {
            crate::safety::ssh_egress_host(B, host)?
        };
        crate::safety::check_egress(B, &[egress_host])?;
    }
    let mut argv = rsync_flags(B, args.get(2))?;
    argv.push(source.clone());
    argv.push(destination.clone());
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = tool_run(
        B,
        "rsync",
        None,
        &refs,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    pkg_done(
        B,
        run,
        vec![
            ("source", Value::Str(source)),
            ("destination", Value::Str(destination)),
        ],
    )
}

// ============================================================================
// Security & Firewall Builtins (995-1014)
// Firewall, SELinux, AppArmor, auditd, fail2ban, OpenSSL, GPG
// ============================================================================

// [removed duplicate] use std::collections::BTreeMap;
// [removed duplicate] use std::process::Command;
// [removed duplicate] use anyhow::{anyhow, Result};

// Assuming Value is defined in the crate root or a value module
// [removed duplicate] use crate::value::Value;

// ---------------------------------------------------------------------------
// Helper: run a command, return stdout or error
// ---------------------------------------------------------------------------
/// Deadline for one security-tool query, such as gpg listing its keyring.
const SEC_RUN_DEADLINE_SECS: u64 = 60;
/// The most output one security-tool query may print. More is E_BUDGET_EXCEEDED.
const SEC_RUN_MAX_OUTPUT: usize = 16 * 1024 * 1024;

fn sec_run_cmd(program: &str, args: &[&str]) -> Result<String> {
    sec_run_cmd_within(program, args, SEC_RUN_DEADLINE_SECS)
}

/// [`sec_run_cmd`] with its deadline given. Past it the tree is killed and the
/// call is a coded budget error. Output over the cap is refused the same way.
fn sec_run_cmd_within(program: &str, args: &[&str], deadline_secs: u64) -> Result<String> {
    let output = run_output(
        program,
        program,
        program,
        args,
        |_| {},
        None,
        deadline_secs,
        SEC_RUN_MAX_OUTPUT,
    )?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(crate::safety::tool_failed(
            program,
            &format!("{} {}", program, args.join(" ")),
            output.status.code(),
            &stderr,
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

fn sec_run_cmd_ok(program: &str, args: &[&str]) -> Option<String> {
    sec_run_cmd(program, args).ok()
}

/// Test hook: [`sec_run_cmd`] with a deadline the test chooses, so a silent
/// child can be shown to be killed at it. Not part of the public API.
#[doc(hidden)]
pub fn __test_sec_run_cmd(program: &str, args: &[&str], deadline_secs: u64) -> Result<String> {
    sec_run_cmd_within(program, args, deadline_secs)
}

fn cmd_exists(program: &str) -> bool {
    // This used to find out whether a program existed by RUNNING it with
    // `--version`, with no time limit, and then running `which` as well.
    on_path(program)
}

fn rec(pairs: Vec<(&str, Value)>) -> Value {
    let mut m = BTreeMap::new();
    for (k, v) in pairs {
        m.insert(k.to_string(), v);
    }
    Value::Record(m)
}

fn s(v: &str) -> Value {
    Value::Str(v.to_string())
}

// ============================================================================
// 1010: bi_openssl_cert_info
// ============================================================================
// Reads a certificate's fields with `openssl x509 -text -noout`. A private key
// given here fails in openssl, and its content is not echoed.
fn bi_openssl_cert_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("openssl_cert_info", &input)?;
    let file_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "openssl_cert_info",
                "file: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    refuse_option("openssl_cert_info", &file_path)?;
    let file_path = crate::safety::resolve_path_str(&file_path);
    let mut cmd = crate::safety::child_command("openssl");
    cmd.args(["x509", "-in", file_path.as_str(), "-text", "-noout"]);
    let (out, _) = run_checked("openssl_cert_info", "openssl", cmd, LOCAL_DEADLINE_SECS)?;
    let mut m = BTreeMap::new();
    m.insert("file".to_string(), s(&file_path));

    for line in out.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("Issuer:") {
            m.insert(
                "issuer".to_string(),
                s(trimmed.strip_prefix("Issuer:").unwrap_or("").trim()),
            );
        } else if trimmed.starts_with("Subject:") {
            m.insert(
                "subject".to_string(),
                s(trimmed.strip_prefix("Subject:").unwrap_or("").trim()),
            );
        } else if trimmed.starts_with("Not Before:") {
            m.insert(
                "not_before".to_string(),
                s(trimmed.strip_prefix("Not Before:").unwrap_or("").trim()),
            );
        } else if trimmed.starts_with("Not After :") || trimmed.starts_with("Not After:") {
            let val = trimmed
                .strip_prefix("Not After :")
                .or_else(|| trimmed.strip_prefix("Not After:"))
                .unwrap_or("")
                .trim();
            m.insert("not_after".to_string(), s(val));
        } else if trimmed.starts_with("Serial Number:") {
            m.insert(
                "serial_number".to_string(),
                s(trimmed.strip_prefix("Serial Number:").unwrap_or("").trim()),
            );
        } else if trimmed.starts_with("Signature Algorithm:") {
            m.insert(
                "signature_algorithm".to_string(),
                s(trimmed
                    .strip_prefix("Signature Algorithm:")
                    .unwrap_or("")
                    .trim()),
            );
        } else if trimmed.starts_with("Public Key Algorithm:") {
            m.insert(
                "public_key_algorithm".to_string(),
                s(trimmed
                    .strip_prefix("Public Key Algorithm:")
                    .unwrap_or("")
                    .trim()),
            );
        }
    }
    m.insert("raw".to_string(), s(out.trim()));
    Ok(Value::Record(m))
}

// ============================================================================
// 1011: bi_openssl_genrsa
// ============================================================================
// Generates an RSA private key into a new, unencrypted file (no passphrase).
// `bits` is 2048 to 16384, default 4096. An existing file is refused. A failed
// run removes the file it started. The key is never returned in the result.
fn bi_openssl_genrsa(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("openssl_genrsa", &input)?;
    let file_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "openssl_genrsa",
                "file: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let bits = match args.get(1) {
        Some(Value::Int(n)) => *n,
        None => 4096,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "openssl_genrsa",
                "bits: Int",
                other.type_name(),
            ))
        }
    };
    if !(2048..=16384).contains(&bits) {
        return Err(crate::safety::bad_arg(
            "openssl_genrsa",
            "bits in 2048..=16384",
            &bits.to_string(),
        ));
    }
    refuse_option("openssl_genrsa", &file_path)?;
    let file_path = guard_local_write("openssl_genrsa", &file_path)?;
    refuse_existing("openssl_genrsa", &file_path)?;
    journal_new_file("openssl_genrsa", &file_path);
    let bits_text = bits.to_string();
    let mut cmd = crate::safety::child_command("openssl");
    cmd.args(["genrsa", "-out", file_path.as_str(), bits_text.as_str()]);
    let (raw, _) = match run_checked("openssl_genrsa", "openssl", cmd, LOCAL_DEADLINE_SECS) {
        Ok(done) => done,
        Err(e) => {
            remove_partial(&file_path);
            return Err(e);
        }
    };
    Ok(rec(vec![
        ("action", s("genrsa")),
        ("file", s(&file_path)),
        ("bits", Value::Int(bits)),
        ("raw", s(raw.trim())),
    ]))
}

// ============================================================================
// 1012: bi_gpg_list_keys
// ============================================================================
fn bi_gpg_list_keys(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Takes no arguments and no piped input; both used to be silently dropped.
    no_args_or_input("gpg_list_keys", &args, &input)?;

    let out = sec_run_cmd("gpg", &["--list-keys", "--with-colons"])?;
    let mut keys = Vec::new();
    let mut current: Option<BTreeMap<String, Value>> = None;

    for line in out.lines() {
        let fields: Vec<&str> = line.split(':').collect();
        if fields.is_empty() {
            continue;
        }
        match fields[0] {
            "pub" => {
                // Save previous key if any
                if let Some(k) = current.take() {
                    keys.push(Value::Record(k));
                }
                let mut m = BTreeMap::new();
                m.insert("type".to_string(), s("pub"));
                if fields.len() > 1 {
                    m.insert("validity".to_string(), s(fields[1]));
                }
                if fields.len() > 2 {
                    m.insert("key_length".to_string(), s(fields[2]));
                }
                if fields.len() > 3 {
                    m.insert("algorithm".to_string(), s(fields[3]));
                }
                if fields.len() > 4 {
                    m.insert("key_id".to_string(), s(fields[4]));
                }
                if fields.len() > 5 {
                    m.insert("creation_date".to_string(), s(fields[5]));
                }
                if fields.len() > 6 {
                    m.insert("expiration_date".to_string(), s(fields[6]));
                }
                current = Some(m);
            }
            "uid" => {
                if let Some(ref mut m) = current {
                    if fields.len() > 9 {
                        m.insert("uid".to_string(), s(fields[9]));
                    }
                }
            }
            "sub" => {
                if let Some(ref mut m) = current {
                    let mut sub_info = String::new();
                    if fields.len() > 2 {
                        sub_info.push_str(fields[2]);
                        sub_info.push('/');
                    }
                    if fields.len() > 4 {
                        sub_info.push_str(fields[4]);
                    }
                    // Append to existing subkeys or create
                    let existing = m
                        .entry("subkeys".to_string())
                        .or_insert_with(|| Value::Array(Vec::new()));
                    if let Value::Array(ref mut arr) = existing {
                        arr.push(s(&sub_info));
                    }
                }
            }
            "fpr" => {
                if let Some(ref mut m) = current {
                    if fields.len() > 9 {
                        m.insert("fingerprint".to_string(), s(fields[9]));
                    }
                }
            }
            _ => {}
        }
    }
    // Push last key
    if let Some(k) = current {
        keys.push(Value::Record(k));
    }

    Ok(Value::Array(keys))
}

// ============================================================================
// 1013: bi_gpg_encrypt
// ============================================================================
// Encrypts a file to one recipient, into file.gpg. The output is refused if it
// exists. gpg runs with --batch and --no-tty, so it never waits at a prompt, and
// it writes the output file itself. The recipient is a key id, fingerprint or
// user id. No passphrase is ever taken on the command line.
fn bi_gpg_encrypt(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("gpg_encrypt", &input)?;
    let file_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "gpg_encrypt",
                "file: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let recipient = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "gpg_encrypt",
                "recipient: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    refuse_option("gpg_encrypt", &file_path)?;
    refuse_option("gpg_encrypt", &recipient)?;
    if recipient.trim().is_empty() || recipient.chars().any(char::is_control) {
        return Err(crate::safety::bad_arg(
            "gpg_encrypt",
            "recipient: a key id, fingerprint or user id",
            &recipient,
        ));
    }
    let input = crate::safety::resolve_path_str(&file_path);
    regular_file_arg("gpg_encrypt", &input)?;
    let output_file = guard_local_write("gpg_encrypt", &format!("{input}.gpg"))?;
    refuse_existing("gpg_encrypt", &output_file)?;
    journal_new_file("gpg_encrypt", &output_file);
    let mut cmd = crate::safety::child_command("gpg");
    cmd.args([
        "--batch",
        "--no-tty",
        "--output",
        output_file.as_str(),
        "--encrypt",
        "--recipient",
        recipient.as_str(),
        input.as_str(),
    ]);
    let (raw, _) = match run_checked("gpg_encrypt", "gpg", cmd, LOCAL_DEADLINE_SECS) {
        Ok(done) => done,
        Err(e) => return Err(fail_removing_partial(e, &output_file)),
    };
    Ok(rec(vec![
        ("action", s("encrypt")),
        ("input_file", s(&input)),
        ("output_file", s(&output_file)),
        ("recipient", s(&recipient)),
        ("raw", s(raw.trim())),
    ]))
}

// Decrypts a .gpg or .asc file to the same name without that suffix, or to
// `<name>.decrypted` otherwise. The plaintext is written to the file and never
// returned. An existing output is refused. A passphrase, if the key needs one,
// comes from the agent's prompt, and the deadline stops the run if no one answers it.
fn bi_gpg_decrypt(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("gpg_decrypt", &input)?;
    let file_path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "gpg_decrypt",
                "file: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    refuse_option("gpg_decrypt", &file_path)?;
    let input = crate::safety::resolve_path_str(&file_path);
    regular_file_arg("gpg_decrypt", &input)?;
    let stem = input
        .strip_suffix(".gpg")
        .or_else(|| input.strip_suffix(".asc"))
        .map(str::to_string)
        .unwrap_or_else(|| format!("{input}.decrypted"));
    let output_file = guard_local_write("gpg_decrypt", &stem)?;
    refuse_existing("gpg_decrypt", &output_file)?;
    journal_new_file("gpg_decrypt", &output_file);
    let mut cmd = crate::safety::child_command("gpg");
    cmd.args([
        "--batch",
        "--no-tty",
        "--output",
        output_file.as_str(),
        "--decrypt",
        input.as_str(),
    ]);
    if let Err(e) = run_checked("gpg_decrypt", "gpg", cmd, LOCAL_DEADLINE_SECS) {
        return Err(fail_removing_partial(e, &output_file));
    }
    Ok(rec(vec![
        ("action", s("decrypt")),
        ("input_file", s(&input)),
        ("output_file", s(&output_file)),
    ]))
}

// ---------------------------------------------------------------------------
// Monitor builtins: shared argument checks, sampling and the alert store.
// ---------------------------------------------------------------------------

/// The most rules the alert store keeps. A create past this is refused.
const MONITOR_MAX_RULES: usize = 1000;
/// The most history events the alert store keeps; the oldest are dropped.
const MONITOR_MAX_HISTORY: usize = 1000;
/// Gap between the CPU samples of `monitor_watch_cpu`.
const MONITOR_WATCH_INTERVAL_MS: u64 = 500;
const MONITOR_METRICS: &[&str] = &["cpu", "memory", "disk"];
const MONITOR_CONDITIONS: &[&str] = &[">", ">=", "<", "<="];
const MONITOR_SEVERITIES: &[&str] = &["info", "warning", "critical"];

/// Refuse pipeline input and more than `max` arguments: these builtins read the
/// machine, so input piped in would otherwise be dropped without a word.
fn monitor_direct_call(
    builtin: &str,
    args: &[Value],
    input: &Option<Value>,
    max: usize,
) -> Result<()> {
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            builtin,
            "a direct call; pipeline input is not accepted",
            "pipeline input",
        ));
    }
    if args.len() > max {
        return Err(crate::safety::bad_arg(
            builtin,
            &format!("at most {max} argument(s)"),
            &format!("{} arguments", args.len()),
        ));
    }
    Ok(())
}

/// How a rejected argument is described to the caller.
fn monitor_got(v: Option<&Value>) -> String {
    match v {
        None => "nothing".to_string(),
        Some(Value::Str(s)) => format!("\"{}\"", s.chars().take(40).collect::<String>()),
        Some(other) => other.type_name().to_string(),
    }
}

/// An optional Int argument from `lo` to `hi`, or `default` when absent.
fn monitor_int_arg(
    builtin: &str,
    args: &[Value],
    idx: usize,
    default: i64,
    lo: i64,
    hi: i64,
    what: &str,
) -> Result<i64> {
    let expected = format!("{what} from {lo} to {hi}");
    match args.get(idx) {
        None => Ok(default),
        Some(Value::Int(n)) if (lo..=hi).contains(n) => Ok(*n),
        Some(Value::Int(n)) => Err(crate::safety::bad_arg(builtin, &expected, &n.to_string())),
        Some(_) => Err(crate::safety::bad_arg(
            builtin,
            &expected,
            &monitor_got(args.get(idx)),
        )),
    }
}

/// An optional percentage (Int or Float) from 0 to 100, or `default` when absent.
fn monitor_percent_arg(builtin: &str, args: &[Value], idx: usize, default: f64) -> Result<f64> {
    let expected = "a finite percentage from 0 to 100";
    match args.get(idx) {
        None => Ok(default),
        Some(Value::Int(n)) if (0..=100).contains(n) => Ok(*n as f64),
        Some(Value::Float(f)) if f.is_finite() && (0.0..=100.0).contains(f) => Ok(*f),
        Some(Value::Int(n)) => Err(crate::safety::bad_arg(builtin, expected, &n.to_string())),
        Some(Value::Float(f)) => Err(crate::safety::bad_arg(builtin, expected, &f.to_string())),
        Some(_) => Err(crate::safety::bad_arg(
            builtin,
            expected,
            &monitor_got(args.get(idx)),
        )),
    }
}

/// An optional string argument that must be one of `choices`.
fn monitor_choice_arg(
    builtin: &str,
    args: &[Value],
    idx: usize,
    choices: &[&str],
    default: &str,
) -> Result<String> {
    match args.get(idx) {
        None => Ok(default.to_string()),
        Some(Value::Str(s)) if choices.contains(&s.as_str()) => Ok(s.clone()),
        Some(_) => {
            let listed = choices
                .iter()
                .map(|c| format!("\"{c}\""))
                .collect::<Vec<_>>()
                .join(", ");
            Err(crate::safety::bad_arg(
                builtin,
                &format!("one of {listed}"),
                &monitor_got(args.get(idx)),
            ))
        }
    }
}

/// An optional interface name. Absent is None; a given name must be a String
/// that is not option-like and is at most 256 bytes. On Unix it must also pass
/// the interface rule, because ip and ifconfig take it as a positional argument.
/// On Windows it is matched in Rust and never reaches a PowerShell script.
fn monitor_iface_arg(builtin: &str, args: &[Value], idx: usize) -> Result<Option<String>> {
    match args.get(idx) {
        None => Ok(None),
        Some(Value::Str(name)) => {
            crate::safety::reject_option_like(builtin, std::slice::from_ref(name))?;
            if name.is_empty() || name.len() > 256 || name.chars().any(char::is_control) {
                return Err(crate::safety::bad_arg(
                    builtin,
                    "an interface name of 1 to 256 characters",
                    &monitor_got(args.get(idx)),
                ));
            }
            #[cfg(not(target_os = "windows"))]
            {
                linux_diagnostics::interface_name(builtin, name)?;
            }
            Ok(Some(name.clone()))
        }
        Some(_) => Err(crate::safety::bad_arg(
            builtin,
            "an interface name String",
            &monitor_got(args.get(idx)),
        )),
    }
}

/// A search keyword: 1 to 256 characters, no control character, and not
/// option-like, since journalctl and grep would read a leading `-` as a flag.
fn monitor_keyword(builtin: &str, keyword: &str) -> Result<()> {
    crate::safety::reject_option_like(builtin, &[keyword.to_string()])?;
    if keyword.is_empty() || keyword.len() > 256 || keyword.chars().any(char::is_control) {
        return Err(crate::safety::bad_arg(
            builtin,
            "a keyword of 1 to 256 characters with no control character",
            &format!("{:?}", keyword.chars().take(40).collect::<String>()),
        ));
    }
    Ok(())
}

/// The stdout of one bounded, read-only query. A nonzero exit is E_TOOL_FAILED
/// with the stderr tail; output past `cap` is E_BUDGET_EXCEEDED; a missing
/// program is E_TOOL_MISSING.
fn monitor_text(builtin: &str, program: &str, args: &[&str], cap: usize) -> Result<String> {
    let run = tool_run(
        builtin,
        program,
        None,
        args,
        Keep::Head(cap),
        TOOL_DEADLINE_SECS,
    )?;
    tool_text(builtin, run)
}

/// The records of one bounded query that prints JSON.
fn monitor_json_records(builtin: &str, program: &str, args: &[&str]) -> Result<Value> {
    let text = monitor_text(builtin, program, args, TOOL_MAX_JSON)?;
    monitor_parse::json_array(builtin, program, &text)
}

/// The records of one bounded PowerShell query that prints JSON. A failure names
/// `label` rather than the script, which can be long.
fn monitor_ps_json(builtin: &str, label: &str, script: &str) -> Result<Value> {
    let mut run = tool_run(
        builtin,
        "powershell",
        None,
        &["-NoProfile", "-Command", script],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    run.command = label.to_string();
    let text = tool_text(builtin, run)?;
    monitor_parse::json_array(builtin, label, &text)
}

/// Keeps the records whose `field` contains `name`, ignoring case. An empty
/// result for a name the caller gave is E_NOT_FOUND, as `ip` answers.
#[cfg(target_os = "windows")]
fn monitor_named(builtin: &str, records: Value, name: Option<&str>, field: &str) -> Result<Value> {
    let Some(name) = name else {
        return Ok(records);
    };
    let want = name.to_lowercase();
    let items = match records {
        Value::Array(items) => items,
        other => return Ok(other),
    };
    let kept: Vec<Value> = items
        .into_iter()
        .filter(|r| match r {
            Value::Record(m) => {
                matches!(m.get(field), Some(Value::Str(s)) if s.to_lowercase().contains(&want))
            }
            _ => false,
        })
        .collect();
    if kept.is_empty() {
        return Err(crate::safety::not_found(builtin, "interface", name));
    }
    Ok(Value::Array(kept))
}

/// Whether a failure is a program that is not installed (E_TOOL_MISSING).
#[cfg(target_os = "linux")]
fn monitor_tool_missing(err: &anyhow::Error) -> bool {
    err.downcast_ref::<crate::safety::SafetyError>()
        .is_some_and(|se| matches!(se.code, crate::safety::ErrorCode::ToolMissing))
}

/// The last `count` items of an array. Used where the tool cannot limit its own
/// output and answers oldest first.
#[cfg(target_os = "macos")]
fn monitor_newest(records: Value, count: i64) -> Value {
    match records {
        Value::Array(items) => {
            let keep = count.max(0) as usize;
            let start = items.len().saturating_sub(keep);
            Value::Array(items.into_iter().skip(start).collect())
        }
        other => other,
    }
}

/// A System with CPU usage. sysinfo reports 0% from a single refresh, because a
/// usage figure is the change between two refreshes.
fn monitor_sample_system() -> System {
    let mut sys = System::new_all();
    sys.refresh_all();
    std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
    sys.refresh_all();
    sys
}

/// Percent of the summed disk space in use across all mounts. With no disks,
/// or zero total space, the old code returned 0.0% used, so a disk alert could
/// never fire. That is now a coded error.
fn monitor_disk_used_percent() -> Result<f64> {
    let disks = Disks::new_with_refreshed_list();
    let count = disks.iter().count();
    let total: u64 = disks.iter().map(|d| d.total_space()).sum();
    let avail: u64 = disks.iter().map(|d| d.available_space()).sum();
    if count == 0 || total == 0 {
        return Err(crate::safety::bad_state(
            "monitor_alert_list",
            &format!(
                "disk usage unavailable ({} disks, {} bytes total)",
                count, total
            ),
            "platform_disk_usage",
        ));
    }
    Ok(total.saturating_sub(avail) as f64 / total as f64 * 100.0)
}

fn monitor_memory_used_percent(sys: &System) -> f64 {
    let total = sys.total_memory();
    if total > 0 {
        sys.used_memory() as f64 / total as f64 * 100.0
    } else {
        0.0
    }
}

/// The live reading for an alert metric; None for a metric it does not know.
fn monitor_metric_value(metric: &str, sys: &System, disk_pct: Option<f64>) -> Option<f64> {
    match metric {
        "cpu" => Some(sys.global_cpu_usage() as f64),
        "memory" => Some(monitor_memory_used_percent(sys)),
        "disk" => disk_pct,
        _ => None,
    }
}

fn monitor_breached(value: f64, condition: &str, threshold: f64) -> bool {
    match condition {
        ">" => value > threshold,
        ">=" => value >= threshold,
        "<" => value < threshold,
        "<=" => value <= threshold,
        _ => false,
    }
}

/// The alert store: `alerts.json` in the monitor directory of the data
/// directory. `IRONSHELL_DATA_HOME` moves it, which is how tests keep it out of
/// the real data directory.
fn monitor_store_path() -> std::path::PathBuf {
    crate::config::ShellConfig::data_dir()
        .join("monitor")
        .join("alerts.json")
}

#[derive(Default)]
struct MonitorStore {
    rules: Vec<serde_json::Value>,
    history: Vec<serde_json::Value>,
}

/// A store file that exists but does not parse. It is reported and left
/// alone: starting an empty store over it would destroy the user's rules.
fn monitor_store_error(builtin: &str, path: &std::path::Path, why: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::Io,
        message: format!(
            "{builtin}: the alert store {} cannot be read: {why}",
            path.display()
        ),
        builtin: builtin.to_string(),
        hint: "move the file aside to start with an empty store; nothing was changed".to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "an alert store written by monitor_alert_create".to_string(),
        got: "a file that does not parse".to_string(),
        extra: serde_json::Map::new(),
    })
}

fn monitor_store_load(builtin: &str) -> Result<MonitorStore> {
    let path = monitor_store_path();
    let text = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(MonitorStore::default()),
        Err(e) => return Err(crate::safety::fs_error(builtin, &path, &e)),
    };
    let doc: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| monitor_store_error(builtin, &path, &e.to_string()))?;
    let list = |key: &str| -> Result<Vec<serde_json::Value>> {
        doc.get(key)
            .and_then(|v| v.as_array())
            .cloned()
            .ok_or_else(|| monitor_store_error(builtin, &path, &format!("no \"{key}\" array")))
    };
    Ok(MonitorStore {
        rules: list("rules")?,
        history: list("history")?,
    })
}

/// Write the store through a temporary file, so a crash leaves either the old
/// store or the new one.
fn monitor_store_save(builtin: &str, store: &MonitorStore) -> Result<()> {
    let path = monitor_store_path();
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| crate::safety::fs_error(builtin, dir, &e))?;
    }
    let doc = serde_json::json!({ "rules": store.rules, "history": store.history });
    let bytes = serde_json::to_vec_pretty(&doc)?;
    let path_text = path.to_str().ok_or_else(|| {
        crate::safety::bad_arg(builtin, "a UTF-8 store path", &path.display().to_string())
    })?;
    // A unique temporary name (not a shared "json.tmp") and cleanup on failure
    // are both done by write_file_atomically.
    write_file_atomically(builtin, path_text, &bytes)
}

fn monitor_history_push(store: &mut MonitorStore, event: &str, rule: &serde_json::Value) {
    store.history.push(serde_json::json!({
        "event": event,
        "rule_id": rule.get("id").cloned().unwrap_or(serde_json::Value::Null),
        "name": rule.get("name").cloned().unwrap_or(serde_json::Value::Null),
        "at": chrono::Local::now().to_rfc3339(),
    }));
    let overflow = store.history.len().saturating_sub(MONITOR_MAX_HISTORY);
    store.history.drain(..overflow);
}

fn monitor_rule_str<'a>(builtin: &str, rule: &'a serde_json::Value, key: &str) -> Result<&'a str> {
    rule.get(key).and_then(|v| v.as_str()).ok_or_else(|| {
        monitor_store_error(
            builtin,
            &monitor_store_path(),
            &format!("a rule has no \"{key}\" text"),
        )
    })
}

fn monitor_rule_f64(builtin: &str, rule: &serde_json::Value, key: &str) -> Result<f64> {
    rule.get(key).and_then(|v| v.as_f64()).ok_or_else(|| {
        monitor_store_error(
            builtin,
            &monitor_store_path(),
            &format!("a rule has no \"{key}\" number"),
        )
    })
}

// ============================================================================
// Monitoring & Diagnostics Builtins (1015-1034)
// System monitoring, network diagnostics, performance counters
// ============================================================================

// [removed duplicate] use std::collections::BTreeMap;
// [removed duplicate] use std::process::Command;
// [removed duplicate] use anyhow::anyhow;

// [removed duplicate] use crate::value::Value;
// [removed duplicate] use crate::builtins::json_to_value;

// ---------------------------------------------------------------------------
// 1015: bi_htop_snapshot — Process monitor snapshot (top 20 by memory)
// ---------------------------------------------------------------------------
// 1015: bi_htop_snapshot - Interactive-style process monitor (cross-platform via sysinfo)
// ---------------------------------------------------------------------------
pub fn bi_htop_snapshot(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_htop";
    monitor_direct_call(B, &args, &input, 1)?;
    let count = monitor_int_arg(B, &args, 0, 20, 1, 500, "a process count")? as usize;
    let sys = monitor_sample_system();
    let mut procs: Vec<_> = sys.processes().iter().collect();
    procs.sort_by(|a, b| b.1.memory().cmp(&a.1.memory()));
    let entries: Vec<Value> = procs
        .iter()
        .take(count)
        .map(|(pid, p)| {
            let mut rec = BTreeMap::new();
            rec.insert("pid".to_string(), Value::Int(pid.as_u32() as i64));
            rec.insert(
                "name".to_string(),
                Value::Str(p.name().to_string_lossy().to_string()),
            );
            rec.insert(
                "cpu_percent".to_string(),
                Value::Float(p.cpu_usage() as f64),
            );
            rec.insert("memory_bytes".to_string(), Value::Int(p.memory() as i64));
            rec.insert(
                "memory_mb".to_string(),
                Value::Float(p.memory() as f64 / 1_048_576.0),
            );
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(entries))
}

// ---------------------------------------------------------------------------
// 1016: bi_iotop_snapshot — I/O monitor snapshot
// ---------------------------------------------------------------------------
// 1016: bi_iotop_snapshot - I/O monitor snapshot (cross-platform via sysinfo)
// ---------------------------------------------------------------------------
fn bi_iotop_snapshot(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_iotop";
    monitor_direct_call(B, &args, &input, 1)?;
    let count = monitor_int_arg(B, &args, 0, 20, 1, 500, "a process count")? as usize;
    let sys = monitor_sample_system();
    let mut procs: Vec<_> = sys.processes().iter().collect();
    procs.sort_by(|a, b| {
        let a_io = a.1.disk_usage().total_read_bytes + a.1.disk_usage().total_written_bytes;
        let b_io = b.1.disk_usage().total_read_bytes + b.1.disk_usage().total_written_bytes;
        b_io.cmp(&a_io)
    });
    let entries: Vec<Value> = procs
        .iter()
        .take(count)
        .map(|(pid, p)| {
            let du = p.disk_usage();
            let mut rec = BTreeMap::new();
            rec.insert("pid".to_string(), Value::Int(pid.as_u32() as i64));
            rec.insert(
                "name".to_string(),
                Value::Str(p.name().to_string_lossy().to_string()),
            );
            rec.insert(
                "total_read_bytes".to_string(),
                Value::Int(du.total_read_bytes as i64),
            );
            rec.insert(
                "total_written_bytes".to_string(),
                Value::Int(du.total_written_bytes as i64),
            );
            rec.insert("read_bytes".to_string(), Value::Int(du.read_bytes as i64));
            rec.insert(
                "written_bytes".to_string(),
                Value::Int(du.written_bytes as i64),
            );
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(entries))
}

// ---------------------------------------------------------------------------
// 1017: bi_nethogs_info — Network traffic per process
// ---------------------------------------------------------------------------
fn bi_nethogs_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_nethogs";
    monitor_direct_call(B, &args, &input, 0)?;

    #[cfg(target_os = "windows")]
    {
        let ps_cmd = "Get-NetTCPConnection | Where-Object { $_.State -eq 'Established' } | Select-Object OwningProcess, LocalAddress, LocalPort, RemoteAddress, RemotePort, State | ForEach-Object { $proc = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue; $_ | Add-Member -NotePropertyName ProcessName -NotePropertyValue $(if($proc){$proc.ProcessName}else{'unknown'}) -PassThru } | Select-Object -First 30 | ConvertTo-Json -Depth 3";
        monitor_ps_json(B, "Get-NetTCPConnection", ps_cmd)
    }

    // nethogs is the only source on Unix (it needs root). The ss fallback this
    // used to take answered records of another shape under the same name, so a
    // missing or failing nethogs is now the coded error and nothing else.
    #[cfg(not(target_os = "windows"))]
    {
        let text = monitor_text(B, "nethogs", &["-t", "-c", "1"], TOOL_MAX_TEXT)?;
        Ok(Value::Array(monitor_parse::nethogs_trace(&text)?))
    }
}

// ---------------------------------------------------------------------------
// 1018: bi_iftop_info — Network bandwidth info
// ---------------------------------------------------------------------------
fn bi_iftop_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_iftop";
    monitor_direct_call(B, &args, &input, 0)?;

    #[cfg(target_os = "windows")]
    {
        let text = monitor_text(B, "netstat", &["-s"], TOOL_MAX_TEXT)?;
        let mut rec = BTreeMap::new();
        rec.insert("source".to_string(), Value::Str("netstat -s".to_string()));
        for (key, value) in monitor_parse::netstat_counters(&text)? {
            rec.insert(key.to_string(), value);
        }
        rec.insert("raw_output".to_string(), Value::Str(text));
        Ok(Value::Record(rec))
    }

    #[cfg(not(target_os = "windows"))]
    {
        // ss -s on Linux; netstat -s on macOS, which has no ss.
        let tool = if cfg!(target_os = "macos") {
            "netstat"
        } else {
            "ss"
        };
        let text = monitor_text(B, tool, &["-s"], TOOL_MAX_TEXT)?;
        let mut rec = BTreeMap::new();
        rec.insert("source".to_string(), Value::Str(format!("{tool} -s")));
        for line in text.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("TCP:") {
                rec.insert("tcp_summary".to_string(), Value::Str(trimmed.to_string()));
            } else if trimmed.starts_with("UDP:") {
                rec.insert("udp_summary".to_string(), Value::Str(trimmed.to_string()));
            } else if trimmed.starts_with("Total:") || trimmed.starts_with("Transport") {
                rec.insert("total_summary".to_string(), Value::Str(trimmed.to_string()));
            }
        }
        rec.insert("raw_output".to_string(), Value::Str(text));
        Ok(Value::Record(rec))
    }
}
// ---------------------------------------------------------------------------
// 1017: bi_nmon_snapshot - System performance snapshot (cross-platform via sysinfo)
// ---------------------------------------------------------------------------
pub fn bi_nmon_snapshot(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    monitor_direct_call("monitor_nmon", &args, &input, 0)?;
    let sys = monitor_sample_system();
    let total_mem = sys.total_memory();
    let used_mem = sys.used_memory();
    let disks = Disks::new_with_refreshed_list();
    let total_disk: u64 = disks.iter().map(|d| d.total_space()).sum();
    let avail_disk: u64 = disks.iter().map(|d| d.available_space()).sum();
    let mut rec = BTreeMap::new();
    rec.insert("cpu_count".to_string(), Value::Int(sys.cpus().len() as i64));
    rec.insert(
        "cpu_percent".to_string(),
        Value::Float(sys.global_cpu_usage() as f64),
    );
    load_fields(&mut rec);
    rec.insert("memory_total".to_string(), Value::Int(total_mem as i64));
    rec.insert("memory_used".to_string(), Value::Int(used_mem as i64));
    rec.insert(
        "memory_free".to_string(),
        Value::Int(total_mem.saturating_sub(used_mem) as i64),
    );
    rec.insert("disk_total".to_string(), Value::Int(total_disk as i64));
    rec.insert("disk_available".to_string(), Value::Int(avail_disk as i64));
    rec.insert(
        "timestamp".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}
// ---------------------------------------------------------------------------
// 1018: bi_glances_info - Comprehensive system info (cross-platform via sysinfo)
// ---------------------------------------------------------------------------
fn bi_glances_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    monitor_direct_call("monitor_glances", &args, &input, 0)?;
    let sys = monitor_sample_system();
    let total_mem = sys.total_memory();
    let used_mem = sys.used_memory();
    let total_swap = sys.total_swap();
    let used_swap = sys.used_swap();
    let cpus: Vec<Value> = sys
        .cpus()
        .iter()
        .map(|c| {
            let mut m = BTreeMap::new();
            m.insert("name".to_string(), Value::Str(c.name().to_string()));
            m.insert(
                "usage_percent".to_string(),
                Value::Float(c.cpu_usage() as f64),
            );
            m.insert(
                "frequency_mhz".to_string(),
                Value::Int(c.frequency() as i64),
            );
            Value::Record(m)
        })
        .collect();
    let disks_list = Disks::new_with_refreshed_list();
    let disk_entries: Vec<Value> = disks_list
        .iter()
        .map(|d| {
            let mut m = BTreeMap::new();
            m.insert(
                "name".to_string(),
                Value::Str(d.name().to_string_lossy().to_string()),
            );
            m.insert(
                "mount".to_string(),
                Value::Str(d.mount_point().to_string_lossy().to_string()),
            );
            m.insert(
                "fs_type".to_string(),
                Value::Str(d.file_system().to_string_lossy().to_string()),
            );
            m.insert(
                "total_bytes".to_string(),
                Value::Int(d.total_space() as i64),
            );
            m.insert(
                "available_bytes".to_string(),
                Value::Int(d.available_space() as i64),
            );
            let used = d.total_space().saturating_sub(d.available_space());
            let pct = if d.total_space() > 0 {
                used as f64 / d.total_space() as f64 * 100.0
            } else {
                0.0
            };
            m.insert("use_percent".to_string(), Value::Float(pct));
            Value::Record(m)
        })
        .collect();
    let nets = Networks::new_with_refreshed_list();
    let net_entries: Vec<Value> = nets
        .iter()
        .map(|(name, data)| {
            let mut m = BTreeMap::new();
            m.insert("interface".to_string(), Value::Str(name.clone()));
            m.insert(
                "rx_bytes".to_string(),
                Value::Int(data.total_received() as i64),
            );
            m.insert(
                "tx_bytes".to_string(),
                Value::Int(data.total_transmitted() as i64),
            );
            m.insert(
                "rx_packets".to_string(),
                Value::Int(data.total_packets_received() as i64),
            );
            m.insert(
                "tx_packets".to_string(),
                Value::Int(data.total_packets_transmitted() as i64),
            );
            Value::Record(m)
        })
        .collect();
    let mut rec = BTreeMap::new();
    // A missing host name was "", which read as a name. platform_snapshot
    // gets it from sys_hostname, which refuses when it cannot be read.
    rec.insert("hostname".to_string(), bi_sys_hostname(Vec::new(), None)?);
    rec.insert(
        "uptime_seconds".to_string(),
        Value::Int(System::uptime() as i64),
    );
    rec.insert("cpu_count".to_string(), Value::Int(sys.cpus().len() as i64));
    rec.insert("cpus".to_string(), Value::Array(cpus));
    rec.insert("memory_total".to_string(), Value::Int(total_mem as i64));
    rec.insert("memory_used".to_string(), Value::Int(used_mem as i64));
    rec.insert(
        "memory_percent".to_string(),
        Value::Float(if total_mem > 0 {
            used_mem as f64 / total_mem as f64 * 100.0
        } else {
            0.0
        }),
    );
    rec.insert("swap_total".to_string(), Value::Int(total_swap as i64));
    rec.insert("swap_used".to_string(), Value::Int(used_swap as i64));
    rec.insert("disks".to_string(), Value::Array(disk_entries));
    rec.insert("networks".to_string(), Value::Array(net_entries));
    load_fields(&mut rec);
    Ok(Value::Record(rec))
}
// chrono_timestamp helper - returns RFC3339 timestamp
fn chrono_timestamp() -> String {
    chrono::Local::now().to_rfc3339()
}

// ---------------------------------------------------------------------------
// 1021: bi_tcpdump_capture — Packet capture
// ---------------------------------------------------------------------------
fn bi_tcpdump_capture(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_tcpdump";
    linux_diagnostics::no_pipeline_input(B, &input)?;
    if args.len() > 3 {
        return Err(crate::safety::arg_err(
            "monitor_tcpdump: expected at most (interface, count, seconds)",
        ));
    }
    let iface = match args.first() {
        None => "any".to_string(),
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                B,
                "an interface name String",
                other.type_name(),
            ))
        }
    };
    let count = match args.get(1) {
        None => 10,
        Some(Value::Int(n)) if (1..=1000).contains(n) => *n,
        Some(Value::Int(n)) => {
            return Err(crate::safety::bad_arg(
                B,
                "a packet count from 1 to 1000",
                &n.to_string(),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                B,
                "a packet count Int",
                other.type_name(),
            ))
        }
    };
    let seconds = match args.get(2) {
        None => 10,
        Some(Value::Int(n)) if (1..=60).contains(n) => *n,
        Some(Value::Int(n)) => {
            return Err(crate::safety::bad_arg(
                B,
                "a duration in seconds from 1 to 60",
                &n.to_string(),
            ))
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                B,
                "a duration Int in seconds",
                other.type_name(),
            ))
        }
    };
    linux_diagnostics::interface_name(B, &iface)?;
    #[cfg(unix)]
    {
        // The deadline is the capture's duration: tcpdump stops at `count`
        // packets or is killed (with its group) at `seconds`.
        let limit = std::time::Duration::from_secs(seconds as u64);
        let argv = vec![
            "-l".to_string(),
            "-nn".to_string(),
            "-q".to_string(),
            "-i".to_string(),
            iface.clone(),
            "-c".to_string(),
            count.to_string(),
        ];
        let run = linux_diagnostics::run_bounded(B, "tcpdump", "tcpdump", &argv, limit)?;
        if run.truncated {
            return Err(crate::safety::budget_exceeded(
                B,
                format!(
                    "tcpdump wrote more than {} bytes",
                    linux_diagnostics::MAX_OUTPUT
                ),
                "use a smaller packet count",
            ));
        }
        if !run.timed_out && run.code != Some(0) {
            return Err(crate::safety::tool_failed(
                B,
                "tcpdump",
                run.code,
                &run.stderr,
            ));
        }
        let packets: Vec<Value> = run
            .stdout
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(|line| {
                let mut rec = BTreeMap::new();
                rec.insert("line".to_string(), Value::Str(line.to_string()));
                Value::Record(rec)
            })
            .collect();
        let mut result = BTreeMap::new();
        result.insert("interface".to_string(), Value::Str(iface));
        result.insert("count".to_string(), Value::Int(count));
        result.insert("captured".to_string(), Value::Int(packets.len() as i64));
        result.insert("timed_out".to_string(), Value::Bool(run.timed_out));
        result.insert("packets".to_string(), Value::Array(packets));
        Ok(Value::Record(result))
    }
    #[cfg(not(unix))]
    {
        let _ = (iface, count, seconds);
        Err(crate::safety::unimplemented(
            B,
            "tcpdump_capture runs on Linux and macOS only; NOTHING WAS CAPTURED on this operating system",
            "run it on Linux",
        ))
    }
}

// ---------------------------------------------------------------------------
// 1022: bi_ss_info — Socket statistics
// ---------------------------------------------------------------------------
fn bi_ss_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_sockets";
    monitor_direct_call(B, &args, &input, 1)?;
    let filter = monitor_choice_arg(B, &args, 0, &["all", "tcp", "udp", "listening"], "all")?;

    #[cfg(target_os = "windows")]
    {
        let text = monitor_text(B, "netstat", &["-an"], TOOL_MAX_TEXT)?;
        Ok(Value::Array(monitor_parse::socket_records_windows(
            &text, &filter,
        )?))
    }

    #[cfg(not(target_os = "windows"))]
    {
        if cfg!(target_os = "macos") {
            let text = monitor_text(B, "netstat", &["-an"], TOOL_MAX_TEXT)?;
            Ok(Value::Array(monitor_parse::socket_records_bsd(
                &text, &filter,
            )?))
        } else {
            // One query for every TCP and UDP socket, with the filter applied to
            // what it printed: "tcp" and "udp" include established sockets.
            let text = monitor_text(B, "ss", &["-tuanH"], TOOL_MAX_TEXT)?;
            Ok(Value::Array(monitor_parse::socket_records_ss(
                &text, &filter,
            )?))
        }
    }
}

// ---------------------------------------------------------------------------
// 1023: bi_ip_addr — IP address management
// ---------------------------------------------------------------------------
fn bi_ip_addr(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_ip_addr";
    monitor_direct_call(B, &args, &input, 1)?;
    let iface = monitor_iface_arg(B, &args, 0)?;

    #[cfg(target_os = "windows")]
    {
        let ps_cmd = "Get-NetIPAddress | Select-Object InterfaceAlias, IPAddress, PrefixLength, AddressFamily, Type | ConvertTo-Json -Depth 3";
        let records = monitor_ps_json(B, "Get-NetIPAddress", ps_cmd)?;
        monitor_named(B, records, iface.as_deref(), "InterfaceAlias")
    }

    #[cfg(target_os = "linux")]
    {
        let mut argv = vec!["-j", "addr", "show"];
        argv.extend(iface.as_deref());
        monitor_json_records(B, "ip", &argv)
    }

    #[cfg(target_os = "macos")]
    {
        let mut argv: Vec<&str> = Vec::new();
        argv.extend(iface.as_deref());
        let text = monitor_text(B, "ifconfig", &argv, TOOL_MAX_TEXT)?;
        let mut records = Vec::new();
        let mut current_iface = String::new();
        for line in text.lines() {
            if !line.starts_with('\t') && !line.starts_with(' ') && line.contains(':') {
                current_iface = line.split(':').next().unwrap_or("").to_string();
            } else if line.trim().starts_with("inet ") {
                let parts: Vec<&str> = line.trim().split_whitespace().collect();
                if parts.len() >= 2 {
                    let mut rec = BTreeMap::new();
                    rec.insert("interface".to_string(), Value::Str(current_iface.clone()));
                    rec.insert("address".to_string(), Value::Str(parts[1].to_string()));
                    rec.insert("family".to_string(), Value::Str("inet".to_string()));
                    if let Some(pos) = parts.iter().position(|&x| x == "netmask") {
                        if parts.len() > pos + 1 {
                            rec.insert(
                                "netmask".to_string(),
                                Value::Str(parts[pos + 1].to_string()),
                            );
                        }
                    }
                    records.push(Value::Record(rec));
                }
            } else if line.trim().starts_with("inet6 ") {
                let parts: Vec<&str> = line.trim().split_whitespace().collect();
                if parts.len() >= 2 {
                    let mut rec = BTreeMap::new();
                    rec.insert("interface".to_string(), Value::Str(current_iface.clone()));
                    rec.insert("address".to_string(), Value::Str(parts[1].to_string()));
                    rec.insert("family".to_string(), Value::Str("inet6".to_string()));
                    records.push(Value::Record(rec));
                }
            }
        }
        Ok(Value::Array(records))
    }
}

// ---------------------------------------------------------------------------
// 1024: bi_ip_route — IP route table
// ---------------------------------------------------------------------------
fn bi_ip_route(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_ip_route";
    monitor_direct_call(B, &args, &input, 0)?;

    #[cfg(target_os = "windows")]
    {
        let ps_cmd = "Get-NetRoute | Select-Object DestinationPrefix, NextHop, InterfaceAlias, RouteMetric, InterfaceMetric | ConvertTo-Json -Depth 3";
        monitor_ps_json(B, "Get-NetRoute", ps_cmd)
    }

    #[cfg(target_os = "linux")]
    {
        monitor_json_records(B, "ip", &["-j", "route", "show"])
    }

    #[cfg(target_os = "macos")]
    {
        let text = monitor_text(B, "netstat", &["-rn"], TOOL_MAX_TEXT)?;
        let mut records = Vec::new();
        let mut header_seen = false;
        for line in text.lines() {
            if line.starts_with("Destination") {
                header_seen = true;
                continue;
            }
            if header_seen {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 4 {
                    let mut rec = BTreeMap::new();
                    rec.insert("destination".to_string(), Value::Str(parts[0].to_string()));
                    rec.insert("gateway".to_string(), Value::Str(parts[1].to_string()));
                    rec.insert("flags".to_string(), Value::Str(parts[2].to_string()));
                    rec.insert(
                        "interface".to_string(),
                        Value::Str(parts.last().unwrap_or(&"").to_string()),
                    );
                    records.push(Value::Record(rec));
                }
            }
        }
        Ok(Value::Array(records))
    }
}

// ---------------------------------------------------------------------------
// 1025: bi_ip_link — Network link info
// ---------------------------------------------------------------------------
fn bi_ip_link(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_ip_link";
    monitor_direct_call(B, &args, &input, 1)?;
    let iface = monitor_iface_arg(B, &args, 0)?;

    #[cfg(target_os = "windows")]
    {
        let ps_cmd = "Get-NetAdapter | Select-Object Name, InterfaceDescription, Status, MacAddress, LinkSpeed, MediaType | ConvertTo-Json -Depth 3";
        let records = monitor_ps_json(B, "Get-NetAdapter", ps_cmd)?;
        monitor_named(B, records, iface.as_deref(), "Name")
    }

    #[cfg(target_os = "linux")]
    {
        let mut argv = vec!["-j", "link", "show"];
        argv.extend(iface.as_deref());
        monitor_json_records(B, "ip", &argv)
    }

    #[cfg(target_os = "macos")]
    {
        let mut argv: Vec<&str> = Vec::new();
        argv.extend(iface.as_deref());
        let text = monitor_text(B, "ifconfig", &argv, TOOL_MAX_TEXT)?;
        let mut records = Vec::new();
        let mut current_iface = String::new();
        let mut current_rec = BTreeMap::new();
        for line in text.lines() {
            if !line.starts_with('\t') && !line.starts_with(' ') && line.contains(':') {
                if !current_iface.is_empty() {
                    current_rec.insert("interface".to_string(), Value::Str(current_iface.clone()));
                    records.push(Value::Record(current_rec.clone()));
                }
                current_iface = line.split(':').next().unwrap_or("").to_string();
                current_rec = BTreeMap::new();
                let flags_part = line.split('<').nth(1).and_then(|s| s.split('>').next());
                if let Some(flags) = flags_part {
                    current_rec.insert("flags".to_string(), Value::Str(flags.to_string()));
                }
            } else if line.trim().starts_with("ether ") {
                let parts: Vec<&str> = line.trim().split_whitespace().collect();
                if parts.len() >= 2 {
                    current_rec.insert("mac_address".to_string(), Value::Str(parts[1].to_string()));
                }
            } else if line.trim().starts_with("status:") {
                let parts: Vec<&str> = line.trim().split_whitespace().collect();
                if parts.len() >= 2 {
                    current_rec.insert("status".to_string(), Value::Str(parts[1].to_string()));
                }
            }
        }
        if !current_iface.is_empty() {
            current_rec.insert("interface".to_string(), Value::Str(current_iface));
            records.push(Value::Record(current_rec));
        }
        Ok(Value::Array(records))
    }
}

/// Windows: an adapter name, matched exactly (not as a -Name wildcard), so
/// `Local Area Connection* 1` names that adapter and no other. Letters,
/// digits, spaces and `- _ . ( ) # *` cover the names Windows gives adapters
/// ("Wi-Fi 4", "vEthernet (Default Switch)"); a `;` or `/` is refused, as
/// interface names are on Linux.
#[cfg(windows)]
fn ethtool_adapter(device: &str) -> Result<()> {
    let plain = !device.trim().is_empty()
        && device.len() <= 256
        && !device.starts_with('-')
        && device
            .chars()
            .all(|c| c.is_alphanumeric() || " -_.()#*".contains(c));
    if plain {
        Ok(())
    } else {
        Err(crate::safety::bad_arg(
            "monitor_ethtool",
            "an adapter name such as \"Ethernet\" or \"Wi-Fi 4\"",
            device,
        ))
    }
}

/// Windows: one adapter's settings from Get-NetAdapter. The keys match the
/// ethtool record where the fact is the same: speed, duplex, link_detected. A
/// field the adapter does not report is left out.
#[cfg(windows)]
fn ethtool_windows(device: &str) -> Result<Value> {
    const NAME: &str = "monitor_ethtool";
    ethtool_adapter(device)?;
    let script = crate::ps_script!(
        "$n = {}; $a = Get-NetAdapter -ErrorAction Stop | Where-Object {{ $_.Name -eq $n }}; $a | Select-Object Name,LinkSpeed,FullDuplex,MediaConnectionState,DriverDescription,DriverVersion,MacAddress | ConvertTo-Json",
        crate::safety::ps_quote(device)
    );
    let out = net_run(
        NAME,
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script.as_str()],
        NET_TOOL_SECS,
    )?;
    net_checked(NAME, "powershell", &out)?;
    // An adapter that does not exist matches nothing and prints nothing.
    let Some(item) = net_ps_items(NAME, &out.stdout)?.into_iter().next() else {
        return Err(crate::safety::not_found(NAME, "network interface", device));
    };
    let Some(o) = item.as_object() else {
        return Err(net_unparsed(NAME, "powershell"));
    };
    let text = |key: &str| {
        o.get(key)
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(|s| Value::Str(s.to_string()))
    };
    let mut rec = BTreeMap::new();
    rec.insert("device".to_string(), Value::Str(device.to_string()));
    for (out_key, json_key) in [
        ("speed", "LinkSpeed"),
        ("driver_description", "DriverDescription"),
        ("driver_version", "DriverVersion"),
        ("mac_address", "MacAddress"),
    ] {
        if let Some(v) = text(json_key) {
            rec.insert(out_key.to_string(), v);
        }
    }
    match o.get("FullDuplex").and_then(|v| v.as_bool()) {
        Some(true) => {
            rec.insert("duplex".to_string(), Value::Str("Full".to_string()));
        }
        Some(false) => {
            rec.insert("duplex".to_string(), Value::Str("Half".to_string()));
        }
        None => {}
    }
    // ConvertTo-Json writes the MediaConnectionState enum as a number: 1 is
    // Connected, 2 is Disconnected, and 0 (Unknown) is left out.
    match o.get("MediaConnectionState").and_then(|v| v.as_i64()) {
        Some(1) => {
            rec.insert("link_detected".to_string(), Value::Str("yes".to_string()));
        }
        Some(2) => {
            rec.insert("link_detected".to_string(), Value::Str("no".to_string()));
        }
        _ => {}
    }
    Ok(Value::Record(rec))
}

/// macOS: one interface from `ifconfig <name>`, which changes nothing. mtu comes
/// from the header line, mac_address from the ether line, and link_detected is
/// yes or no from the status line (active or inactive). A line the interface does
/// not print is left out: loopback has neither a status nor an ether line. speed
/// and duplex are Null, since ifconfig does not report them.
#[cfg(target_os = "macos")]
fn ethtool_macos(device: &str) -> Result<Value> {
    const NAME: &str = "monitor_ethtool";
    let limit = std::time::Duration::from_secs(20);
    let run =
        linux_diagnostics::run_bounded(NAME, "ifconfig", "ifconfig", &[device.to_string()], limit)?;
    if !run.timed_out
        && !run.truncated
        && run.code == Some(1)
        && run.stderr.contains("does not exist")
    {
        return Err(crate::safety::not_found(NAME, "network interface", device));
    }
    linux_diagnostics::require_success(NAME, "ifconfig", &run, limit)?;
    let mut rec = BTreeMap::new();
    rec.insert("device".to_string(), Value::Str(device.to_string()));
    rec.insert("speed".to_string(), Value::Null);
    rec.insert("duplex".to_string(), Value::Null);
    for line in run.stdout.lines() {
        if !line.starts_with(char::is_whitespace) {
            // The header: `lo0: flags=8049<UP,LOOPBACK,RUNNING> mtu 16384`.
            if let Some(i) = line.find(" mtu ") {
                if let Some(mtu) = line[i + 5..].split_whitespace().next() {
                    rec.insert("mtu".to_string(), Value::Str(mtu.to_string()));
                }
            }
            continue;
        }
        let t = line.trim();
        if let Some(mac) = t.strip_prefix("ether ") {
            if let Some(m) = mac.split_whitespace().next() {
                rec.insert("mac_address".to_string(), Value::Str(m.to_string()));
            }
        } else if let Some(status) = t.strip_prefix("status: ") {
            let link = match status.trim() {
                "active" => Some("yes"),
                "inactive" => Some("no"),
                _ => None,
            };
            if let Some(link) = link {
                rec.insert("link_detected".to_string(), Value::Str(link.to_string()));
            }
        }
    }
    Ok(Value::Record(rec))
}

// ---------------------------------------------------------------------------
// 1026: bi_ethtool_info — Ethernet device info (Linux and macOS; Windows reads Get-NetAdapter)
// ---------------------------------------------------------------------------
fn bi_ethtool_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    linux_diagnostics::no_pipeline_input("monitor_ethtool", &input)?;
    let device = match args.as_slice() {
        [Value::Str(s)] => s.clone(),
        [other] => {
            return Err(crate::safety::bad_arg(
                "monitor_ethtool",
                "a device name String such as \"eth0\"",
                other.type_name(),
            ))
        }
        _ => {
            return Err(crate::safety::arg_err(
                "monitor_ethtool: expected one device name, e.g. \"eth0\"",
            ))
        }
    };
    #[cfg(not(windows))]
    linux_diagnostics::interface_name("monitor_ethtool", &device)?;
    #[cfg(target_os = "linux")]
    {
        let text = monitor_text(
            "monitor_ethtool",
            "ethtool",
            &[device.as_str()],
            TOOL_MAX_TEXT,
        )?;
        let mut rec = BTreeMap::new();
        rec.insert("device".to_string(), Value::Str(device.clone()));
        for line in text.lines() {
            if let Some((key, val)) = line.trim().split_once(':') {
                let k = key.trim().to_lowercase().replace([' ', '-'], "_");
                let v = val.trim();
                if !k.is_empty() && !v.is_empty() {
                    rec.insert(k, Value::Str(v.to_string()));
                }
            }
        }
        Ok(Value::Record(rec))
    }
    #[cfg(windows)]
    {
        ethtool_windows(&device)
    }
    #[cfg(target_os = "macos")]
    {
        ethtool_macos(&device)
    }
    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
    {
        let _ = device;
        Err(crate::safety::unimplemented(
            "monitor_ethtool",
            "ethtool is Linux, macOS and Windows only; NOTHING WAS INSPECTED on this operating system",
            "monitor_ip_link() lists interfaces on every OS",
        ))
    }
}

// ---------------------------------------------------------------------------
// perf stat on Windows: the figures a finished child reports through its handle
// ---------------------------------------------------------------------------

/// What a finished child reports about itself: CPU times in 100 ns ticks, its
/// peak working set in bytes, and its page-fault count.
#[cfg(windows)]
struct WinProcStats {
    user_ticks: u64,
    kernel_ticks: u64,
    peak_rss: u64,
    page_faults: u32,
}

/// The Win32 PROCESS_MEMORY_COUNTERS record, laid out as K32GetProcessMemoryInfo
/// fills it. Only `peak_working_set_size` and `page_fault_count` are read.
#[cfg(windows)]
#[repr(C)]
#[derive(Default)]
#[allow(dead_code)]
struct WinProcessMemoryCounters {
    cb: u32,
    page_fault_count: u32,
    peak_working_set_size: usize,
    working_set_size: usize,
    quota_peak_paged_pool_usage: usize,
    quota_paged_pool_usage: usize,
    quota_peak_non_paged_pool_usage: usize,
    quota_non_paged_pool_usage: usize,
    pagefile_usage: usize,
    peak_pagefile_usage: usize,
}

/// Reads a child's CPU times, peak working set and page faults through its
/// process handle. The child must have exited or been killed, and its `Child`
/// must not be dropped yet: the handle is what keeps these figures readable.
#[cfg(windows)]
fn win_process_stats(child: &std::process::Child) -> std::io::Result<WinProcStats> {
    use std::ffi::c_void;
    use std::os::windows::io::AsRawHandle;
    #[link(name = "kernel32")]
    extern "system" {
        fn GetProcessTimes(
            process: *mut c_void,
            creation: *mut WinFileTime,
            exit: *mut WinFileTime,
            kernel: *mut WinFileTime,
            user: *mut WinFileTime,
        ) -> i32;
        fn K32GetProcessMemoryInfo(
            process: *mut c_void,
            counters: *mut WinProcessMemoryCounters,
            cb: u32,
        ) -> i32;
    }
    let handle = child.as_raw_handle();
    let mut creation = WinFileTime::default();
    let mut exit = WinFileTime::default();
    let mut kernel = WinFileTime::default();
    let mut user = WinFileTime::default();
    // SAFETY: `handle` is the child's process handle, borrowed from `child`,
    // which is alive for this call; each out-pointer is a local of the type the
    // API writes.
    if unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) } == 0 {
        return Err(std::io::Error::last_os_error());
    }
    let cb = std::mem::size_of::<WinProcessMemoryCounters>() as u32;
    let mut mem = WinProcessMemoryCounters {
        cb,
        ..Default::default()
    };
    // SAFETY: as above; `mem` is a repr(C) record whose `cb` is its own size,
    // which is what the API checks against.
    if unsafe { K32GetProcessMemoryInfo(handle, &mut mem, cb) } == 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(WinProcStats {
        user_ticks: user.ticks(),
        kernel_ticks: kernel.ticks(),
        peak_rss: mem.peak_working_set_size as u64,
        page_faults: mem.page_fault_count,
    })
}

// ---------------------------------------------------------------------------
// 1027: bi_perf_stat — Performance counters (Linux and Windows)
// ---------------------------------------------------------------------------
fn bi_perf_stat(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    linux_diagnostics::no_pipeline_input("perf_stat", &input)?;
    if args.is_empty() || args.len() > 2 {
        return Err(crate::safety::arg_err(
            "perf_stat: expected an argv array and optionally an event list, e.g. perf_stat([\"/usr/bin/true\"], \"cycles\")",
        ));
    }
    let argv = linux_diagnostics::argv_arg("perf_stat", &args[0])?;
    let events = match args.get(1) {
        None => "cycles,instructions,cache-misses".to_string(),
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "perf_stat",
                "an event list String such as \"cycles,instructions\"",
                other.type_name(),
            ))
        }
    };
    linux_diagnostics::event_list("perf_stat", &events)?;
    let command = argv.join(" ");
    crate::safety::guard_exec("perf_stat", command.clone())?;
    #[cfg(target_os = "linux")]
    {
        let limit = std::time::Duration::from_secs(120);
        let mut pargs = vec![
            "stat".to_string(),
            "-e".to_string(),
            events.clone(),
            "--".to_string(),
        ];
        pargs.extend(argv.iter().cloned());
        let run = linux_diagnostics::run_bounded("perf_stat", "perf", "perf", &pargs, limit)?;
        linux_diagnostics::require_success("perf_stat", "perf stat", &run, limit)?;
        // perf stat writes its report to stderr.
        let mut counters = Vec::new();
        for line in run.stderr.lines() {
            let line = line.trim();
            if line.is_empty()
                || line.starts_with('#')
                || line.starts_with("Performance counter stats")
            {
                continue;
            }
            // "value  event  # comment", or "<not supported> event".
            let body = line.split('#').next().unwrap_or("").trim();
            let (value, name) = if let Some(rest) = body.strip_prefix("<not") {
                let (what, name) = rest.split_once('>').unwrap_or(("", rest));
                (format!("<not{what}>"), name.trim().to_string())
            } else {
                match body.split_once(char::is_whitespace) {
                    Some((v, n)) => (v.to_string(), n.trim().to_string()),
                    None => continue,
                }
            };
            if name.is_empty() {
                continue;
            }
            let mut counter = BTreeMap::new();
            counter.insert("value".to_string(), Value::Str(value));
            counter.insert("name".to_string(), Value::Str(name));
            counters.push(Value::Record(counter));
        }
        if counters.is_empty() {
            return Err(crate::safety::tool_failed(
                "perf_stat",
                "perf stat",
                run.code,
                &format!("no counters were reported; stderr was: {}", run.stderr),
            ));
        }
        let mut rec = BTreeMap::new();
        rec.insert("command".to_string(), Value::Str(command));
        rec.insert("events".to_string(), Value::Str(events));
        rec.insert("counters".to_string(), Value::Array(counters));
        rec.insert("raw_output".to_string(), Value::Str(run.stderr));
        Ok(Value::Record(rec))
    }
    #[cfg(windows)]
    {
        // The event list is Linux only. It was checked above; a call that passes
        // one is refused here rather than read and ignored.
        if args.len() == 2 {
            return Err(crate::safety::unimplemented(
                "perf_stat",
                "the event list is Linux only: Windows reads a fixed set of counters; NOTHING WAS RUN",
                "call monitor_perf_stat(argv) with the argv alone",
            ));
        }
        let _ = events;
        // The argv runs as given: argv[0] is the program, found on PATH, with no
        // shell and no perf in between.
        let limit = std::time::Duration::from_secs(120);
        let mut cmd = crate::safety::child_command(&argv[0]);
        cmd.args(&argv[1..]);
        let mut sampled = None;
        let tree = run_tree_cmd_observed(
            cmd,
            None,
            limit,
            Keep::Head(linux_diagnostics::MAX_OUTPUT),
            Keep::Head(linux_diagnostics::MAX_OUTPUT),
            |child, waited| sampled = Some((win_process_stats(child), waited)),
        )
        .map_err(|e| match e {
            TreeError::Spawn(e) => crate::safety::spawn_error("perf_stat", &argv[0], &e),
            TreeError::Wait(e) => e.into(),
        })?;
        let run = linux_diagnostics::Run {
            code: tree.code,
            timed_out: tree.timed_out,
            truncated: tree.stdout_truncated || tree.stderr_truncated || tree.pipes_abandoned,
            stdout: String::from_utf8_lossy(&tree.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&tree.stderr).into_owned(),
        };
        linux_diagnostics::require_success("perf_stat", &command, &run, limit)?;
        let (stats, waited) = match sampled {
            Some((Ok(stats), waited)) => (stats, waited),
            Some((Err(e), _)) => {
                return Err(crate::safety::bad_state_with_hint(
                    "perf_stat",
                    &format!(
                        "GetProcessTimes or K32GetProcessMemoryInfo failed on `{}`: {e}",
                        argv[0]
                    ),
                    "a child this process started, read before its handle is closed",
                ))
            }
            None => {
                return Err(crate::safety::bad_state_with_hint(
                    "perf_stat",
                    "the child was not sampled before it was reaped",
                    "a child this process started and waited for",
                ))
            }
        };
        let ms = |ticks: u64| Value::Int((ticks / 10_000) as i64);
        let counter = |name: &str, value: Value| {
            let mut c = BTreeMap::new();
            c.insert("name".to_string(), Value::Str(name.to_string()));
            c.insert("value".to_string(), value);
            Value::Record(c)
        };
        let counters = vec![
            counter("task_clock_ms", ms(stats.user_ticks + stats.kernel_ticks)),
            counter("user_ms", ms(stats.user_ticks)),
            counter("system_ms", ms(stats.kernel_ticks)),
            counter("elapsed_ms", Value::Int(waited.as_millis() as i64)),
            counter("peak_rss_bytes", Value::Int(stats.peak_rss as i64)),
            counter("page_faults", Value::Int(i64::from(stats.page_faults))),
        ];
        let mut rec = BTreeMap::new();
        rec.insert("command".to_string(), Value::Str(command));
        rec.insert("counters".to_string(), Value::Array(counters));
        rec.insert("raw_output".to_string(), Value::Str(run.stderr));
        Ok(Value::Record(rec))
    }
    #[cfg(not(any(target_os = "linux", windows)))]
    {
        let _ = (command, events);
        Err(crate::safety::unimplemented(
            "perf_stat",
            "perf stat is Linux only; NOTHING WAS RUN on this operating system",
            "run it on Linux",
        ))
    }
}

// ---------------------------------------------------------------------------
// 1028: bi_perf_record — Performance recording info (Linux only)
// ---------------------------------------------------------------------------
fn bi_perf_record(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    linux_diagnostics::no_pipeline_input("perf_record", &input)?;
    if args.is_empty() || args.len() > 2 {
        return Err(crate::safety::arg_err(
            "perf_record: expected an argv array and optionally an output path, e.g. perf_record([\"/usr/bin/true\"], \"/tmp/x.data\")",
        ));
    }
    let argv = linux_diagnostics::argv_arg("perf_record", &args[0])?;
    let output_file = match args.get(1) {
        None => "perf.data".to_string(),
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "perf_record",
                "an output path String",
                other.type_name(),
            ))
        }
    };
    linux_diagnostics::output_path("perf_record", &output_file)?;
    let command = argv.join(" ");
    crate::safety::guard_exec("perf_record", command.clone())?;
    #[cfg(target_os = "linux")]
    {
        let limit = std::time::Duration::from_secs(120);
        let mut pargs = vec![
            "record".to_string(),
            "-o".to_string(),
            output_file.clone(),
            "--".to_string(),
        ];
        pargs.extend(argv.iter().cloned());
        let run = linux_diagnostics::run_bounded("perf_record", "perf", "perf", &pargs, limit)?;
        linux_diagnostics::require_success("perf_record", "perf record", &run, limit)?;
        let bytes = match std::fs::metadata(&output_file) {
            Ok(meta) => meta.len(),
            Err(_) => {
                return Err(crate::safety::tool_failed(
                    "perf_record",
                    "perf record",
                    Some(0),
                    &format!("perf exited 0 but wrote no file at {output_file}"),
                ))
            }
        };
        let mut rec = BTreeMap::new();
        rec.insert("command".to_string(), Value::Str(command));
        rec.insert("output_file".to_string(), Value::Str(output_file.clone()));
        rec.insert("bytes".to_string(), Value::Int(bytes as i64));
        rec.insert("success".to_string(), Value::Bool(true));
        rec.insert(
            "details".to_string(),
            Value::Str(run.stderr.trim().to_string()),
        );
        rec.insert(
            "hint".to_string(),
            Value::Str(format!(
                "Use 'perf report -i {output_file}' to analyze the recorded data"
            )),
        );
        Ok(Value::Record(rec))
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (command, output_file);
        Err(crate::safety::unimplemented(
            "perf_record",
            "perf record is Linux only; NOTHING WAS RUN on this operating system",
            "run it on Linux",
        ))
    }
}
// ---------------------------------------------------------------------------
// 1019: bi_free_mem - Memory usage (cross-platform via sysinfo)
// ---------------------------------------------------------------------------
pub fn bi_free_mem(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    monitor_direct_call("monitor_memory", &args, &input, 0)?;
    let mut sys = System::new();
    sys.refresh_memory();
    let total = sys.total_memory();
    let used = sys.used_memory();
    let free = sys.free_memory();
    let available = sys.available_memory();
    let swap_total = sys.total_swap();
    let swap_used = sys.used_swap();
    let swap_free = swap_total.saturating_sub(swap_used);
    let mut rec = BTreeMap::new();
    rec.insert("total".to_string(), Value::Int(total as i64));
    rec.insert("used".to_string(), Value::Int(used as i64));
    rec.insert("free".to_string(), Value::Int(free as i64));
    rec.insert("available".to_string(), Value::Int(available as i64));
    rec.insert(
        "use_percent".to_string(),
        Value::Float(if total > 0 {
            used as f64 / total as f64 * 100.0
        } else {
            0.0
        }),
    );
    rec.insert("swap_total".to_string(), Value::Int(swap_total as i64));
    rec.insert("swap_used".to_string(), Value::Int(swap_used as i64));
    rec.insert("swap_free".to_string(), Value::Int(swap_free as i64));
    Ok(Value::Record(rec))
}
// ---------------------------------------------------------------------------
// 1020: bi_uptime_extended - Extended uptime info (cross-platform via sysinfo)
// ---------------------------------------------------------------------------
fn bi_uptime_extended(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let _ = args;
    let secs = System::uptime();
    let days = secs / 86400;
    let hours = (secs % 86400) / 3600;
    let minutes = (secs % 3600) / 60;
    let seconds = secs % 60;
    let human = format!("{}d {}h {}m {}s", days, hours, minutes, seconds);
    let mut rec = BTreeMap::new();
    rec.insert("uptime_seconds".to_string(), Value::Int(secs as i64));
    rec.insert("uptime_human".to_string(), Value::Str(human));
    rec.insert("days".to_string(), Value::Int(days as i64));
    rec.insert("hours".to_string(), Value::Int(hours as i64));
    rec.insert("minutes".to_string(), Value::Int(minutes as i64));
    rec.insert("seconds".to_string(), Value::Int(seconds as i64));
    load_fields(&mut rec);
    // A missing host name was "" (see bi_glances_info).
    rec.insert("hostname".to_string(), bi_sys_hostname(Vec::new(), None)?);
    Ok(Value::Record(rec))
}

// ---------------------------------------------------------------------------
// 1031: bi_who_users — Currently logged in users
// ---------------------------------------------------------------------------
fn bi_who_users(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_users";
    monitor_direct_call(B, &args, &input, 0)?;

    #[cfg(target_os = "windows")]
    {
        // query.exe exits 1 and says "No User exists" when nobody is logged on.
        // That is an empty answer, not a failure.
        let run = tool_run(
            B,
            "query",
            None,
            &["user"],
            Keep::Head(TOOL_MAX_TEXT),
            TOOL_DEADLINE_SECS,
        )?;
        if !run.success && format!("{}{}", run.stdout, run.stderr).contains("No User exists") {
            return Ok(Value::Array(Vec::new()));
        }
        let text = tool_text(B, run)?;
        Ok(Value::Array(monitor_parse::query_user_records(&text)?))
    }

    #[cfg(not(target_os = "windows"))]
    {
        let text = monitor_text(B, "who", &[], TOOL_MAX_TEXT)?;
        Ok(Value::Array(monitor_parse::who_records(&text)?))
    }
}

// ---------------------------------------------------------------------------
// 1032: bi_last_logins — Recent login history
// ---------------------------------------------------------------------------
fn bi_last_logins(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_logins";
    monitor_direct_call(B, &args, &input, 1)?;
    let count = monitor_int_arg(B, &args, 0, 20, 1, 1000, "a login count")?;

    #[cfg(target_os = "windows")]
    {
        let ps_cmd = crate::ps_script!(
            // Always an array (one event serialised as a bare object); no
            // events is []; anything else -- access denied above all -- is an
            // error, where all of it used to be {available: false, reason}.
            r#"try {{
    $r = @(Get-WinEvent -FilterHashtable @{{LogName='Security'; Id=4624}} -MaxEvents {} -ErrorAction Stop |
        Select-Object TimeCreated, Id, @{{Name='User';Expression={{$_.Properties[5].Value}}}}, @{{Name='LogonType';Expression={{$_.Properties[8].Value}}}}, @{{Name='SourceIP';Expression={{$_.Properties[18].Value}}}})
    ConvertTo-Json -InputObject $r -Depth 3
}} catch {{
    if ($_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {{ '[]' }}
    else {{ [Console]::Error.WriteLine($_.Exception.Message); exit 1 }}
}}"#,
            count
        );
        monitor_ps_json(
            B,
            "Get-WinEvent (the Security log needs an elevated shell)",
            &ps_cmd,
        )
    }

    #[cfg(not(target_os = "windows"))]
    {
        let n = count.to_string();
        let text = monitor_text(B, "last", &["-n", n.as_str()], TOOL_MAX_TEXT)?;
        Ok(Value::Array(monitor_parse::last_records(&text)?))
    }
}

// ---------------------------------------------------------------------------
// 1033: bi_syslog_search — System log search
// ---------------------------------------------------------------------------
fn bi_syslog_search(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_syslog";
    monitor_direct_call(B, &args, &input, 2)?;
    let keyword = match args.first() {
        Some(Value::Str(k)) => k.clone(),
        _ => {
            return Err(crate::safety::bad_arg(
                B,
                "a keyword String",
                &monitor_got(args.first()),
            ))
        }
    };
    monitor_keyword(B, &keyword)?;
    let count = monitor_int_arg(B, &args, 1, 50, 1, 1000, "a match count")?;

    #[cfg(target_os = "windows")]
    {
        let ps_cmd = crate::ps_script!(
            // Always an array; no events is []; any other failure is an error,
            // where it used to be {available: false, reason} at exit 0. Only the
            // newest 500 System events are searched.
            r#"try {{
    $r = @(Get-WinEvent -FilterHashtable @{{LogName='System'}} -MaxEvents 500 -ErrorAction Stop |
        Where-Object {{ $_.Message -match [regex]::Escape({}) }} |
        Select-Object -First {} |
        Select-Object TimeCreated, Id, LevelDisplayName, ProviderName, Message)
    ConvertTo-Json -InputObject $r -Depth 3
}} catch {{
    if ($_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {{ '[]' }}
    else {{ [Console]::Error.WriteLine($_.Exception.Message); exit 1 }}
}}"#,
            crate::safety::ps_quote(&keyword),
            count
        );
        monitor_ps_json(B, "Get-WinEvent", &ps_cmd)
    }

    #[cfg(target_os = "linux")]
    {
        // journalctl first. The syslog file is read only when journalctl is not
        // installed; a journalctl that runs and fails is an error, not a cue to
        // answer from a different source.
        let n = count.to_string();
        let journal = tool_run(
            B,
            "journalctl",
            None,
            &[
                "-g",
                keyword.as_str(),
                "-n",
                n.as_str(),
                "--no-pager",
                "-o",
                "json",
            ],
            Keep::Head(TOOL_MAX_JSON),
            TOOL_DEADLINE_SECS,
        );
        match journal {
            Ok(run) => {
                let text = tool_text(B, run)?;
                Ok(Value::Array(monitor_parse::journal_records(&text)?))
            }
            Err(e) if monitor_tool_missing(&e) => {
                let log = ["/var/log/syslog", "/var/log/messages"]
                    .into_iter()
                    .find(|p| std::path::Path::new(p).exists())
                    .ok_or_else(|| {
                        crate::safety::tool_missing(
                            B,
                            "journalctl",
                            "and there is no /var/log/syslog or /var/log/messages to read instead",
                        )
                    })?;
                // grep: exit 1 is "no line matched"; `-e` keeps a keyword from
                // being read as an option.
                let run = tool_run(
                    B,
                    "grep",
                    None,
                    &["-i", "-e", keyword.as_str(), log],
                    Keep::Tail(TOOL_MAX_TEXT),
                    TOOL_DEADLINE_SECS,
                )?;
                if run.code == Some(1) {
                    return Ok(Value::Array(Vec::new()));
                }
                if !run.success {
                    return Err(crate::safety::tool_failed(B, "grep", run.code, &run.stderr));
                }
                // A tail cut short starts mid-line, so that fragment is dropped.
                let text = if run.stdout_truncated {
                    run.stdout.split_once('\n').map_or("", |(_, rest)| rest)
                } else {
                    run.stdout.as_str()
                };
                Ok(Value::Array(monitor_parse::grep_records(
                    text,
                    count as usize,
                    log,
                )))
            }
            Err(e) => Err(e),
        }
    }

    #[cfg(target_os = "macos")]
    {
        // Backslashes first: escaping only the quote let a trailing backslash
        // re-open the string.
        let predicate = format!(
            "eventMessage contains \"{}\"",
            keyword.replace('\\', "\\\\").replace('"', "\\\"")
        );
        let records = monitor_json_records(
            B,
            "log",
            &[
                "show",
                "--predicate",
                predicate.as_str(),
                "--last",
                "1h",
                "--style",
                "json",
            ],
        )?;
        Ok(monitor_newest(records, count))
    }
}

// ---------------------------------------------------------------------------
// 1034: bi_dstat_info — System resource stats (aggregate)
// ---------------------------------------------------------------------------
// 1034: bi_dstat_info - System resource stats (cross-platform via sysinfo)
// ---------------------------------------------------------------------------
pub fn bi_dstat_info(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    monitor_direct_call("monitor_dstat", &args, &input, 0)?;
    let sys = monitor_sample_system();
    let mut stats = BTreeMap::new();
    // Per-CPU usage
    let cpus: Vec<Value> = sys
        .cpus()
        .iter()
        .map(|c| {
            let mut m = BTreeMap::new();
            m.insert("name".to_string(), Value::Str(c.name().to_string()));
            m.insert(
                "usage_percent".to_string(),
                Value::Float(c.cpu_usage() as f64),
            );
            Value::Record(m)
        })
        .collect();
    stats.insert("cpus".to_string(), Value::Array(cpus));
    stats.insert(
        "cpu_percent".to_string(),
        Value::Float(sys.global_cpu_usage() as f64),
    );
    // Memory
    let total_mem = sys.total_memory();
    let used_mem = sys.used_memory();
    let mut mem = BTreeMap::new();
    mem.insert("total".to_string(), Value::Int(total_mem as i64));
    mem.insert("used".to_string(), Value::Int(used_mem as i64));
    mem.insert(
        "free".to_string(),
        Value::Int(total_mem.saturating_sub(used_mem) as i64),
    );
    stats.insert("memory".to_string(), Value::Record(mem));
    // Disks
    let disks = Disks::new_with_refreshed_list();
    let disk_entries: Vec<Value> = disks
        .iter()
        .map(|d| {
            let mut m = BTreeMap::new();
            m.insert(
                "name".to_string(),
                Value::Str(d.name().to_string_lossy().to_string()),
            );
            m.insert(
                "total_bytes".to_string(),
                Value::Int(d.total_space() as i64),
            );
            m.insert(
                "available_bytes".to_string(),
                Value::Int(d.available_space() as i64),
            );
            Value::Record(m)
        })
        .collect();
    stats.insert("disk".to_string(), Value::Array(disk_entries));
    // Networks
    let nets = Networks::new_with_refreshed_list();
    let net_entries: Vec<Value> = nets
        .iter()
        .map(|(name, data)| {
            let mut m = BTreeMap::new();
            m.insert("interface".to_string(), Value::Str(name.clone()));
            m.insert(
                "rx_bytes".to_string(),
                Value::Int(data.total_received() as i64),
            );
            m.insert(
                "tx_bytes".to_string(),
                Value::Int(data.total_transmitted() as i64),
            );
            m.insert(
                "rx_packets".to_string(),
                Value::Int(data.total_packets_received() as i64),
            );
            m.insert(
                "tx_packets".to_string(),
                Value::Int(data.total_packets_transmitted() as i64),
            );
            Value::Record(m)
        })
        .collect();
    stats.insert("network".to_string(), Value::Array(net_entries));
    stats.insert(
        "timestamp".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(stats))
}

// ===========================================================================
// Proactive Monitoring & Alerting Builtins (836-843)
// ===========================================================================

// 836: bi_health_check - Comprehensive system health check
pub fn bi_health_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    monitor_direct_call("monitor_health_check", &args, &input, 0)?;
    let sys = monitor_sample_system();

    let cpu = sys.global_cpu_usage() as f64;
    let total_mem = sys.total_memory();
    let used_mem = sys.used_memory();
    let mem_pct = if total_mem > 0 {
        used_mem as f64 / total_mem as f64 * 100.0
    } else {
        0.0
    };

    let disks = Disks::new_with_refreshed_list();
    let total_disk: u64 = disks.iter().map(|d| d.total_space()).sum();
    let avail_disk: u64 = disks.iter().map(|d| d.available_space()).sum();
    let disk_pct = if total_disk > 0 {
        total_disk.saturating_sub(avail_disk) as f64 / total_disk as f64 * 100.0
    } else {
        0.0
    };

    // Determine overall health status
    let status = if cpu > 95.0 || mem_pct > 95.0 || disk_pct > 95.0 {
        "critical"
    } else if cpu > 80.0 || mem_pct > 80.0 || disk_pct > 85.0 {
        "warning"
    } else {
        "healthy"
    };

    let mut alerts = Vec::new();
    if cpu > 80.0 {
        let mut a = BTreeMap::new();
        a.insert("type".to_string(), Value::Str("cpu".to_string()));
        a.insert(
            "severity".to_string(),
            Value::Str(if cpu > 95.0 { "critical" } else { "warning" }.to_string()),
        );
        a.insert(
            "message".to_string(),
            Value::Str(format!("CPU usage at {:.1}%", cpu)),
        );
        a.insert("value".to_string(), Value::Float(cpu));
        a.insert("threshold".to_string(), Value::Float(80.0));
        alerts.push(Value::Record(a));
    }
    if mem_pct > 80.0 {
        let mut a = BTreeMap::new();
        a.insert("type".to_string(), Value::Str("memory".to_string()));
        a.insert(
            "severity".to_string(),
            Value::Str(
                if mem_pct > 95.0 {
                    "critical"
                } else {
                    "warning"
                }
                .to_string(),
            ),
        );
        a.insert(
            "message".to_string(),
            Value::Str(format!("Memory usage at {:.1}%", mem_pct)),
        );
        a.insert("value".to_string(), Value::Float(mem_pct));
        a.insert("threshold".to_string(), Value::Float(80.0));
        alerts.push(Value::Record(a));
    }
    if disk_pct > 85.0 {
        let mut a = BTreeMap::new();
        a.insert("type".to_string(), Value::Str("disk".to_string()));
        a.insert(
            "severity".to_string(),
            Value::Str(
                if disk_pct > 95.0 {
                    "critical"
                } else {
                    "warning"
                }
                .to_string(),
            ),
        );
        a.insert(
            "message".to_string(),
            Value::Str(format!("Disk usage at {:.1}%", disk_pct)),
        );
        a.insert("value".to_string(), Value::Float(disk_pct));
        a.insert("threshold".to_string(), Value::Float(85.0));
        alerts.push(Value::Record(a));
    }

    let mut rec = BTreeMap::new();
    rec.insert("status".to_string(), Value::Str(status.to_string()));
    rec.insert("cpu_percent".to_string(), Value::Float(cpu));
    rec.insert("memory_percent".to_string(), Value::Float(mem_pct));
    rec.insert("disk_percent".to_string(), Value::Float(disk_pct));
    load_fields(&mut rec);
    rec.insert(
        "process_count".to_string(),
        Value::Int(sys.processes().len() as i64),
    );
    rec.insert("alerts".to_string(), Value::Array(alerts));
    rec.insert(
        "timestamp".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}

// 837: bi_alert_create - Create an alert rule for a metric
pub fn bi_alert_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_alert_create";
    monitor_direct_call(B, &args, &input, 5)?;
    let name = match args.first() {
        Some(Value::Str(s)) if !s.trim().is_empty() && s.chars().count() <= 100 => {
            s.trim().to_string()
        }
        _ => {
            return Err(crate::safety::bad_arg(
                B,
                "a rule name: a non-empty String of at most 100 characters",
                &monitor_got(args.first()),
            ))
        }
    };
    let metric = match args.get(1) {
        Some(Value::Str(s)) if MONITOR_METRICS.contains(&s.as_str()) => s.clone(),
        _ => {
            return Err(crate::safety::bad_arg(
                B,
                "a metric: \"cpu\", \"memory\" or \"disk\"",
                &monitor_got(args.get(1)),
            ))
        }
    };
    let condition = monitor_choice_arg(B, &args, 2, MONITOR_CONDITIONS, ">")?;
    let threshold = monitor_percent_arg(B, &args, 3, 80.0)?;
    let severity = monitor_choice_arg(B, &args, 4, MONITOR_SEVERITIES, "warning")?;

    let mut store = monitor_store_load(B)?;
    if store.rules.len() >= MONITOR_MAX_RULES {
        return Err(crate::safety::budget_exceeded(
            B,
            format!("the alert store already holds {MONITOR_MAX_RULES} rules"),
            "remove a rule with monitor_alert_remove before creating another",
        ));
    }
    let base = format!(
        "alert_{}_{}",
        metric,
        chrono::Local::now().timestamp_millis()
    );
    let mut id = base.clone();
    let mut n = 1usize;
    while store
        .rules
        .iter()
        .any(|r| r.get("id").and_then(|v| v.as_str()) == Some(id.as_str()))
    {
        id = format!("{base}_{n}");
        n += 1;
    }
    let rule = serde_json::json!({
        "id": id,
        "name": name,
        "metric": metric,
        "condition": condition,
        "threshold": threshold,
        "severity": severity,
        "status": "active",
        "created_at": chrono::Local::now().to_rfc3339(),
    });
    store.rules.push(rule.clone());
    monitor_history_push(&mut store, "created", &rule);
    monitor_store_save(B, &store)?;
    Ok(json_to_value(rule))
}

// 838: bi_alert_list - List active alert rules
pub fn bi_alert_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_alert_list";
    monitor_direct_call(B, &args, &input, 0)?;
    let store = monitor_store_load(B)?;
    if store.rules.is_empty() {
        return Ok(Value::Array(Vec::new()));
    }
    let sys = monitor_sample_system();
    // Read the disks only when a rule needs them, so a host whose disks
    // cannot be measured still evaluates its cpu and memory rules.
    let wants_disk = store
        .rules
        .iter()
        .any(|r| r.get("metric").and_then(|m| m.as_str()) == Some("disk"));
    let disk_pct = if wants_disk {
        Some(monitor_disk_used_percent()?)
    } else {
        None
    };
    let mut out = Vec::with_capacity(store.rules.len());
    for rule in &store.rules {
        let metric = monitor_rule_str(B, rule, "metric")?;
        let condition = monitor_rule_str(B, rule, "condition")?;
        let threshold = monitor_rule_f64(B, rule, "threshold")?;
        let current = monitor_metric_value(metric, &sys, disk_pct).ok_or_else(|| {
            monitor_store_error(
                B,
                &monitor_store_path(),
                &format!("a rule has the unknown metric \"{metric}\""),
            )
        })?;
        let mut rec = rule.clone();
        rec["current_value"] = serde_json::json!(current);
        rec["triggered"] = serde_json::json!(monitor_breached(current, condition, threshold));
        out.push(json_to_value(rec));
    }
    Ok(Value::Array(out))
}

// 839: bi_alert_history - Get alert history
pub fn bi_alert_history(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_alert_history";
    monitor_direct_call(B, &args, &input, 1)?;
    let limit = monitor_int_arg(B, &args, 0, 50, 1, 1000, "an event count")? as usize;
    let store = monitor_store_load(B)?;
    let out: Vec<Value> = store
        .history
        .iter()
        .rev()
        .take(limit)
        .cloned()
        .map(json_to_value)
        .collect();
    Ok(Value::Array(out))
}

// 840: bi_alert_remove - Remove an alert rule by ID
pub fn bi_alert_remove(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_alert_remove";
    monitor_direct_call(B, &args, &input, 1)?;
    let id = match args.first() {
        Some(Value::Str(s)) if !s.is_empty() && s.len() <= 100 => s.clone(),
        _ => {
            return Err(crate::safety::bad_arg(
                B,
                "an alert id: a non-empty String of at most 100 bytes",
                &monitor_got(args.first()),
            ))
        }
    };
    let mut store = monitor_store_load(B)?;
    let Some(pos) = store
        .rules
        .iter()
        .position(|r| r.get("id").and_then(|v| v.as_str()) == Some(id.as_str()))
    else {
        return Err(crate::safety::not_found(B, "alert", &id));
    };
    let rule = store.rules.remove(pos);
    monitor_history_push(&mut store, "removed", &rule);
    monitor_store_save(B, &store)?;
    Ok(json_to_value(serde_json::json!({
        "id": id,
        "removed": true,
        "timestamp": chrono::Local::now().to_rfc3339(),
    })))
}

// 841: bi_watch_cpu - Monitor CPU usage with threshold alerting
pub fn bi_watch_cpu(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_watch_cpu";
    monitor_direct_call(B, &args, &input, 2)?;
    let threshold = monitor_percent_arg(B, &args, 0, 80.0)?;
    // At most 10 samples, 500 ms apart: a watch lasts at most about 5 seconds.
    let samples = monitor_int_arg(B, &args, 1, 5, 1, 10, "a sample count")? as usize;

    let mut sys = System::new();
    sys.refresh_cpu_all();
    let mut readings = Vec::with_capacity(samples);
    let mut total = 0.0_f64;
    let mut breaches = 0_usize;
    for i in 0..samples {
        std::thread::sleep(std::time::Duration::from_millis(MONITOR_WATCH_INTERVAL_MS));
        sys.refresh_cpu_all();
        let cpu = sys.global_cpu_usage() as f64;
        let above = cpu > threshold;
        total += cpu;
        if above {
            breaches += 1;
        }
        let mut sample = BTreeMap::new();
        sample.insert("sample".to_string(), Value::Int(i as i64 + 1));
        sample.insert("cpu_percent".to_string(), Value::Float(cpu));
        sample.insert("above_threshold".to_string(), Value::Bool(above));
        sample.insert(
            "timestamp".to_string(),
            Value::Str(chrono::Local::now().to_rfc3339()),
        );
        readings.push(Value::Record(sample));
    }

    let avg = total / samples as f64;
    let mut rec = BTreeMap::new();
    rec.insert("threshold".to_string(), Value::Float(threshold));
    rec.insert("samples".to_string(), Value::Int(samples as i64));
    rec.insert("average_cpu".to_string(), Value::Float(avg));
    rec.insert("breaches".to_string(), Value::Int(breaches as i64));
    rec.insert("alert".to_string(), Value::Bool(breaches > samples / 2));
    rec.insert("readings".to_string(), Value::Array(readings));
    Ok(Value::Record(rec))
}

// 842: bi_watch_memory - Monitor memory usage with threshold alerting
pub fn bi_watch_memory(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_watch_memory";
    monitor_direct_call(B, &args, &input, 1)?;
    let threshold = monitor_percent_arg(B, &args, 0, 80.0)?;
    let mut sys = System::new();
    sys.refresh_memory();

    let total = sys.total_memory();
    let used = sys.used_memory();
    let free = sys.free_memory();
    let available = sys.available_memory();
    let pct = if total > 0 {
        used as f64 / total as f64 * 100.0
    } else {
        0.0
    };

    let swap_total = sys.total_swap();
    let swap_used = sys.used_swap();
    let swap_pct = if swap_total > 0 {
        swap_used as f64 / swap_total as f64 * 100.0
    } else {
        0.0
    };

    let status = if pct > 95.0 {
        "critical"
    } else if pct > threshold {
        "warning"
    } else {
        "healthy"
    };

    let mut rec = BTreeMap::new();
    rec.insert("status".to_string(), Value::Str(status.to_string()));
    rec.insert("threshold".to_string(), Value::Float(threshold));
    rec.insert("total_bytes".to_string(), Value::Int(total as i64));
    rec.insert("used_bytes".to_string(), Value::Int(used as i64));
    rec.insert("free_bytes".to_string(), Value::Int(free as i64));
    rec.insert("available_bytes".to_string(), Value::Int(available as i64));
    rec.insert("use_percent".to_string(), Value::Float(pct));
    rec.insert("above_threshold".to_string(), Value::Bool(pct > threshold));
    rec.insert("swap_total".to_string(), Value::Int(swap_total as i64));
    rec.insert("swap_used".to_string(), Value::Int(swap_used as i64));
    rec.insert("swap_percent".to_string(), Value::Float(swap_pct));
    rec.insert(
        "timestamp".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}

// 843: bi_watch_disk - Monitor disk usage with threshold alerting
pub fn bi_watch_disk(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "monitor_watch_disk";
    monitor_direct_call(B, &args, &input, 1)?;
    let threshold = monitor_percent_arg(B, &args, 0, 85.0)?;
    let disks = Disks::new_with_refreshed_list();
    let mut disk_entries = Vec::new();
    let mut any_alert = false;

    for disk in disks.iter() {
        let total = disk.total_space();
        let avail = disk.available_space();
        let used = total.saturating_sub(avail);
        let pct = if total > 0 {
            used as f64 / total as f64 * 100.0
        } else {
            0.0
        };
        let above = pct > threshold;
        if above {
            any_alert = true;
        }

        let mut rec = BTreeMap::new();
        rec.insert(
            "mount".to_string(),
            Value::Str(disk.mount_point().to_string_lossy().to_string()),
        );
        rec.insert(
            "filesystem".to_string(),
            Value::Str(disk.file_system().to_string_lossy().to_string()),
        );
        rec.insert("total_bytes".to_string(), Value::Int(total as i64));
        rec.insert("used_bytes".to_string(), Value::Int(used as i64));
        rec.insert("available_bytes".to_string(), Value::Int(avail as i64));
        rec.insert("use_percent".to_string(), Value::Float(pct));
        rec.insert("above_threshold".to_string(), Value::Bool(above));
        let status = if pct > 95.0 {
            "critical"
        } else if above {
            "warning"
        } else {
            "healthy"
        };
        rec.insert("status".to_string(), Value::Str(status.to_string()));
        disk_entries.push(Value::Record(rec));
    }

    let mut rec = BTreeMap::new();
    rec.insert("threshold".to_string(), Value::Float(threshold));
    rec.insert("alert".to_string(), Value::Bool(any_alert));
    rec.insert(
        "disk_count".to_string(),
        Value::Int(disk_entries.len() as i64),
    );
    rec.insert("disks".to_string(), Value::Array(disk_entries));
    rec.insert(
        "timestamp".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}

// ===================== Cloud Platform Builtins =====================

/// The current OS username (cross-platform). Neither variable set used to be
/// "unknown", which passed as a real user: workspace membership and package
/// authorship would record that name. It is refused instead.
///
/// Asked through `whoami`, which reads the user database by effective uid on
/// Unix: $USER is unset under cron, systemd units and many containers.
fn get_current_username(builtin: &str) -> Result<String> {
    match bi_whoami(Vec::new(), None)? {
        Value::Str(name) => Ok(name),
        other => Err(crate::safety::bad_state(
            builtin,
            &format!("whoami answered {}", other.type_name()),
            "whoami",
        )),
    }
}

/// 844 – cloud_deploy(name, [options]): not implemented. No cloud provider
/// client is wired in, so no deployment is created. The name and options are
/// checked first, so a malformed call is refused as an argument error.
fn bi_cloud_deploy(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cloud_deploy";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    k8s_need(B, "a deployment name", &args, 0, pkg_plain)?;
    cloud_options(B, args.get(1), &["region", "instance_id", "script"])?;
    Err(cloud_unimplemented(B))
}

/// List all cloud instances.
/// Usage: cloud.instances()
///
/// Not implemented. Nothing ever recorded an instance in this process, so the
/// old answer was always an empty list, which read as "no instances exist".
fn bi_cloud_instances(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cloud_instances";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 0)?;
    Err(cloud_unimplemented(B))
}

/// 846 – cloud_instance_create(name, [options]): not implemented, so no instance
/// is created. Checked first, as cloud_deploy is.
fn bi_cloud_instance_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cloud_instance_create";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    k8s_need(B, "an instance name", &args, 0, pkg_plain)?;
    cloud_options(B, args.get(1), &["region", "type", "workspace"])?;
    Err(cloud_unimplemented(B))
}

/// 847 – cloud_instance_destroy(id): approval-gated in agent mode, then not
/// implemented. The gate runs first, so the approval a person grants is never
/// answered by a silent no-op: the call stops with E_UNIMPLEMENTED and nothing
/// is destroyed.
fn bi_cloud_instance_destroy(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cloud_instance_destroy";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let id = k8s_need(B, "an instance ID", &args, 0, pkg_plain)?;
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: B,
        effect: crate::safety::Effect::Destructive,
        what: B,
        targets: vec![id.clone()],
        blast_radius: serde_json::json!({ "instance": id }),
        reversible: false,
        fs_paths: false,
    })?;
    Err(cloud_unimplemented(B))
}

/// 848 – cloud_instance_status(id): not implemented. It has no provider to ask.
fn bi_cloud_instance_status(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cloud_instance_status";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    k8s_need(B, "an instance ID", &args, 0, pkg_plain)?;
    Err(cloud_unimplemented(B))
}

/// 849 – cloud_instance_connect(id): not implemented. No session is opened.
fn bi_cloud_instance_connect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cloud_instance_connect";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    k8s_need(B, "an instance ID", &args, 0, pkg_plain)?;
    Err(cloud_unimplemented(B))
}

/// List available cloud regions.
/// Usage: cloud.regions()
///
/// Not implemented. The old answer was a fixed AWS-style list that no provider
/// had supplied, so it was presented as this host's regions when it was not.
fn bi_cloud_regions(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cloud_regions";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 0)?;
    Err(cloud_unimplemented(B))
}

/// Get or set cloud platform configuration.
/// Usage: cloud.config() or cloud.config({provider?, region?, endpoint?, instance_type?})
fn bi_cloud_config(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if let Some(Value::Record(opts)) = args.first() {
        // Set config
        let provider = opts
            .get("provider")
            .and_then(|v| {
                if let Value::Str(s) = v {
                    Some(s.clone())
                } else {
                    None
                }
            })
            .unwrap_or_else(|| "ironshell".to_string());
        let region = opts
            .get("region")
            .and_then(|v| {
                if let Value::Str(s) = v {
                    Some(s.clone())
                } else {
                    None
                }
            })
            .unwrap_or_else(|| "us-east-1".to_string());
        let endpoint = opts.get("endpoint").and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.clone())
            } else {
                None
            }
        });
        let instance_type = opts
            .get("instance_type")
            .and_then(|v| {
                if let Value::Str(s) = v {
                    Some(s.clone())
                } else {
                    None
                }
            })
            .unwrap_or_else(|| "ae.small".to_string());

        let config = CloudConfig {
            provider: provider.clone(),
            region: region.clone(),
            api_endpoint: endpoint.clone(),
            default_instance_type: instance_type.clone(),
        };

        let mut guard = CLOUD_CONFIG
            .write()
            .map_err(|_| crate::safety::lock_poisoned("cloud_config", "the cloud configuration"))?;
        *guard = Some(config);

        let mut rec = BTreeMap::new();
        rec.insert("provider".to_string(), Value::Str(provider));
        rec.insert("region".to_string(), Value::Str(region));
        if let Some(ep) = endpoint {
            rec.insert("endpoint".to_string(), Value::Str(ep));
        }
        rec.insert("instance_type".to_string(), Value::Str(instance_type));
        rec.insert("status".to_string(), Value::Str("configured".to_string()));
        Ok(Value::Record(rec))
    } else {
        // Get config
        let guard = CLOUD_CONFIG
            .read()
            .map_err(|_| crate::safety::lock_poisoned("cloud_config", "the cloud configuration"))?;
        if let Some(ref config) = *guard {
            let mut rec = BTreeMap::new();
            rec.insert("provider".to_string(), Value::Str(config.provider.clone()));
            rec.insert("region".to_string(), Value::Str(config.region.clone()));
            if let Some(ref ep) = config.api_endpoint {
                rec.insert("endpoint".to_string(), Value::Str(ep.clone()));
            }
            rec.insert(
                "instance_type".to_string(),
                Value::Str(config.default_instance_type.clone()),
            );
            Ok(Value::Record(rec))
        } else {
            Ok(Value::Null)
        }
    }
}

// ===================== Remote REPL Builtins =====================
//
// repl_serve starts a loopback TCP listener that evaluates code sent by a peer
// holding the token it returns, and only in agent mode. repl_connect is one
// request per connection: it sends {token, code} and returns the value. Remote
// code reaches the same builtin dispatcher as local code, so `guard_dispatch`
// judges every call it makes; nothing on this path skips it.
//
// Wire format: one newline-terminated JSON object each way.
//   request:  {"token": "<token>", "code": "<source>"}
//   response: {"ok": true, "value": <json>, "type": "<type name>"}
//             {"ok": false, "error": "<message>"}
// A wrong token gets {"ok": false, "error": "unauthorized"} and the connection
// closes. repl_broadcast stays refused: no session is held open, so no peer set
// exists.

/// Longest request or response line, in bytes.
const REPL_MAX_LINE: usize = 1024 * 1024;
/// Connections served at once; one beyond this is refused with one error line.
const REPL_MAX_CONNECTIONS: usize = 8;
/// Wall-clock limit on one remote evaluation.
const REPL_EVAL_LIMIT: Duration = Duration::from_secs(30);
/// Read and write timeout on each socket operation.
const REPL_IO_TIMEOUT: Duration = Duration::from_secs(10);

/// The running listener, if any. One per process.
struct ReplServer {
    addr: std::net::SocketAddr,
    token: String,
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

/// A request line that passed the shape check.
#[derive(Debug, PartialEq, Eq)]
struct ReplRequest {
    token: String,
    code: String,
}

/// Parse one request line. The error text is what the peer is told.
fn repl_parse_request(line: &[u8]) -> std::result::Result<ReplRequest, String> {
    let text = std::str::from_utf8(line).map_err(|_| "request is not UTF-8".to_string())?;
    let value: serde_json::Value =
        serde_json::from_str(text.trim_end()).map_err(|e| format!("request is not JSON: {e}"))?;
    let object = value
        .as_object()
        .ok_or_else(|| "request must be a JSON object".to_string())?;
    let token = object
        .get("token")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "request needs a string token".to_string())?;
    let code = object
        .get("code")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "request needs a string code".to_string())?;
    Ok(ReplRequest {
        token: token.to_string(),
        code: code.to_string(),
    })
}

/// Whether `given` is `expected`. Every byte of an equal-length pair is compared,
/// so a mismatch does not reveal how much of the token matched.
fn repl_token_matches(expected: &str, given: &str) -> bool {
    let (a, b) = (expected.as_bytes(), given.as_bytes());
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

/// Read one newline-terminated line of at most `max` bytes, newline excluded.
/// `Ok(None)` is EOF before any byte. A longer line is an error. The reader is
/// never asked for more than one buffer past the cap, so a peer cannot grow the
/// line without bound.
fn repl_read_line<R: std::io::BufRead>(
    reader: &mut R,
    max: usize,
) -> std::result::Result<Option<Vec<u8>>, String> {
    let mut line: Vec<u8> = Vec::new();
    loop {
        let (complete, used) = {
            let buf = reader.fill_buf().map_err(|e| format!("read failed: {e}"))?;
            if buf.is_empty() {
                return if line.is_empty() {
                    Ok(None)
                } else {
                    Err("connection closed mid-line".to_string())
                };
            }
            match buf.iter().position(|&b| b == b'\n') {
                Some(i) => {
                    line.extend_from_slice(&buf[..i]);
                    (true, i + 1)
                }
                None => {
                    line.extend_from_slice(buf);
                    (false, buf.len())
                }
            }
        };
        reader.consume(used);
        if line.len() > max {
            return Err(format!("line is longer than {max} bytes"));
        }
        if complete {
            return Ok(Some(line));
        }
    }
}

/// Evaluate remote source as `ish -c` evaluates local source: parse, then
/// `eval_program` in the module environment. Each builtin the source calls is
/// dispatched, and so guarded, exactly as it is locally.
fn repl_eval(code: &str) -> std::result::Result<Value, String> {
    let stmts = crate::parser::parse_program(code).map_err(|e| format!("parse error: {e}"))?;
    let mut env = crate::modules::env_with_modules();
    crate::eval::eval_program(&stmts, &mut env).map_err(|e| format!("{e}"))
}

fn repl_error_reply(reason: &str) -> serde_json::Value {
    serde_json::json!({"ok": false, "error": reason})
}

/// Write one reply line. A peer that has gone away is not something the server
/// can act on, so the write result is dropped.
fn repl_send(stream: &mut std::net::TcpStream, reply: &serde_json::Value) {
    use std::io::Write as _;
    let mut line = reply.to_string();
    line.push('\n');
    let _ = stream.write_all(line.as_bytes());
}

/// Serve one connection: one request, one reply, then close.
fn repl_handle_connection(mut stream: std::net::TcpStream, token: &str) {
    let _ = stream.set_read_timeout(Some(REPL_IO_TIMEOUT));
    let _ = stream.set_write_timeout(Some(REPL_IO_TIMEOUT));
    let read_side = match stream.try_clone() {
        Ok(s) => s,
        Err(_) => return,
    };
    let mut reader = std::io::BufReader::new(read_side);
    let line = match repl_read_line(&mut reader, REPL_MAX_LINE) {
        Ok(Some(line)) => line,
        Ok(None) => return,
        Err(reason) => {
            repl_send(&mut stream, &repl_error_reply(&reason));
            return;
        }
    };
    let request = match repl_parse_request(&line) {
        Ok(request) => request,
        Err(reason) => {
            repl_send(&mut stream, &repl_error_reply(&reason));
            return;
        }
    };
    if crate::safety::current_mode() != crate::safety::Mode::Agent {
        repl_send(
            &mut stream,
            &repl_error_reply("remote evaluation needs agent mode"),
        );
        return;
    }
    if !repl_token_matches(token, &request.token) {
        repl_send(&mut stream, &repl_error_reply("unauthorized"));
        return;
    }
    let _deadline = crate::safety::enter_deadline(REPL_EVAL_LIMIT);
    let reply = match repl_eval(&request.code) {
        Ok(value) => {
            let type_name = value.type_name().to_string();
            serde_json::json!({
                "ok": true,
                "value": value_to_json(value),
                "type": type_name,
            })
        }
        Err(reason) => repl_error_reply(&reason),
    };
    repl_send(&mut stream, &reply);
}

/// Decrements the live-connection count however a connection thread ends.
struct ReplSlot(std::sync::Arc<std::sync::atomic::AtomicUsize>);

impl Drop for ReplSlot {
    fn drop(&mut self) {
        self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
    }
}

/// Accept connections until `stop` is set. The listener is non-blocking, so the
/// flag is seen within one poll interval.
fn repl_accept_loop(
    listener: std::net::TcpListener,
    token: String,
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
) {
    use std::sync::atomic::{AtomicUsize, Ordering};
    let live = std::sync::Arc::new(AtomicUsize::new(0));
    while !stop.load(Ordering::SeqCst) {
        match listener.accept() {
            Ok((mut stream, _peer)) => {
                let _ = stream.set_nonblocking(false);
                if live.fetch_add(1, Ordering::SeqCst) >= REPL_MAX_CONNECTIONS {
                    live.fetch_sub(1, Ordering::SeqCst);
                    repl_send(&mut stream, &repl_error_reply("too many connections"));
                    continue;
                }
                let slot = ReplSlot(live.clone());
                let token = token.clone();
                let _ = std::thread::Builder::new()
                    .name("repl-conn".to_string())
                    .spawn(move || {
                        let _slot = slot;
                        repl_handle_connection(stream, &token);
                    });
            }
            Err(_) => std::thread::sleep(Duration::from_millis(25)),
        }
    }
}

/// A transport failure on a REPL connection (`E_IO`).
fn repl_io_error(builtin: &str, message: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::Io,
        builtin: builtin.into(),
        message: format!("{builtin}: {message}"),
        hint: "the connection was closed or stalled; no remote result was received".into(),
        approval: None,
        did_you_mean: vec![],
        expected: "a complete reply line from the REPL listener".into(),
        got: message.into(),
        extra: serde_json::Map::new(),
    })
}

/// repl_serve(options?) - Serve this process's evaluation on a loopback port.
///
/// Options: `host` (a literal loopback address, default 127.0.0.1), `port`
/// (0..65535; 0 picks a free one), and `stop: true` to stop the running
/// listener. Returns {address, port, token, status}; every request must present
/// the token. Serving needs agent mode, so a peer gets the agent-mode policy.
fn bi_repl_serve(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "repl_serve";
    refuse_piped_subject(NAME, &input)?;
    if args.len() > 1 {
        return Err(crate::safety::bad_arg(
            NAME,
            "at most one options Record",
            "more arguments",
        ));
    }
    let fields = match args.into_iter().next() {
        None | Some(Value::Null) => BTreeMap::new(),
        Some(Value::Record(fields)) => fields,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "options: Record",
                other.type_name(),
            ))
        }
    };
    let mut host: std::net::IpAddr = std::net::Ipv4Addr::LOCALHOST.into();
    let mut port: i64 = 0;
    let mut stop = false;
    for (key, value) in fields {
        match (key.as_str(), value) {
            ("host", Value::Str(text)) => {
                host = text.parse::<std::net::IpAddr>().map_err(|_| {
                    crate::safety::bad_arg(NAME, "host: a literal IP address", &text)
                })?;
            }
            ("port", Value::Int(n)) if (0..=65535i64).contains(&n) => port = n,
            ("stop", Value::Bool(flag)) => stop = flag,
            (other, _) => {
                return Err(crate::safety::bad_arg(
                    NAME,
                    "options: host String, port Int 0..65535, stop Bool",
                    other,
                ))
            }
        }
    }

    let mut slot = REPL_SERVER
        .lock()
        .map_err(|_| crate::safety::lock_poisoned(NAME, "the REPL listener"))?;
    if stop {
        let server = slot.take().ok_or_else(|| {
            crate::safety::bad_state(NAME, "no REPL listener is running", "repl_serve")
        })?;
        server.stop.store(true, std::sync::atomic::Ordering::SeqCst);
        let mut rec = BTreeMap::new();
        rec.insert("address".to_string(), Value::Str(server.addr.to_string()));
        rec.insert("status".to_string(), Value::Str("stopped".to_string()));
        return Ok(Value::Record(rec));
    }

    if crate::tx::is_active() {
        return Err(crate::safety::unimplemented(
            NAME,
            "listeners and network effects cannot be rolled back",
            "finish the transaction first",
        ));
    }
    if !host.is_loopback() {
        return Err(crate::safety::bad_arg(
            NAME,
            "host: a loopback address (127.0.0.1 or ::1)",
            &host.to_string(),
        ));
    }
    if crate::safety::current_mode() != crate::safety::Mode::Agent {
        return Err(crate::safety::policy_deny(
            NAME,
            "remote evaluation needs agent mode, so a peer cannot run code with human-mode permissions",
            "set IRONSHELL_MODE=agent, then serve again",
        ));
    }
    let addr = std::net::SocketAddr::new(host, port as u16);
    guard_network(NAME, &format!("tcp://{addr}"))?;
    if let Some(running) = slot.as_ref() {
        return Err(crate::safety::bad_state(
            NAME,
            &format!("already serving on {}", running.addr),
            "repl_serve({stop: true})",
        ));
    }

    let listener = std::net::TcpListener::bind(addr).map_err(|e| nc_io_error(NAME, e))?;
    let bound = listener.local_addr().map_err(|e| nc_io_error(NAME, e))?;
    listener
        .set_nonblocking(true)
        .map_err(|e| nc_io_error(NAME, e))?;
    // Two v4 UUIDs: 244 random bits, hex-encoded.
    let token = format!(
        "{}{}",
        uuid::Uuid::new_v4().simple(),
        uuid::Uuid::new_v4().simple()
    );
    let stop_flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let (thread_token, thread_stop) = (token.clone(), stop_flag.clone());
    std::thread::Builder::new()
        .name("repl-serve".to_string())
        .spawn(move || repl_accept_loop(listener, thread_token, thread_stop))
        .map_err(|e| nc_io_error(NAME, e))?;

    let mut rec = BTreeMap::new();
    rec.insert("address".to_string(), Value::Str(bound.to_string()));
    rec.insert("port".to_string(), Value::Int(i64::from(bound.port())));
    rec.insert("token".to_string(), Value::Str(token.clone()));
    rec.insert("status".to_string(), Value::Str("listening".to_string()));
    *slot = Some(ReplServer {
        addr: bound,
        token,
        stop: stop_flag,
    });
    Ok(Value::Record(rec))
}

/// repl_connect(target, options) - Send one request to a repl_serve listener and
/// return its value. `target` is a `tcp://ip:port` String or a `{host, port}`
/// Record with a literal IP. `options` is `{token, code}`. A refused token raises
/// E_POLICY_DENY; any other failure from the remote side is returned as
/// {ok: false, error}.
fn bi_repl_connect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "repl_connect";
    refuse_piped_subject(NAME, &input)?;
    let (target, options) = match <[Value; 2]>::try_from(args) {
        Ok([target, options]) => (target, options),
        Err(_) => {
            return Err(crate::safety::bad_arg(
                NAME,
                "a target and an options Record {token, code}",
                "a different number of arguments",
            ))
        }
    };
    let target_hint = "target: a tcp://ip:port String or {host, port} Record";
    let addr: std::net::SocketAddr = match &target {
        Value::Str(text) => text
            .strip_prefix("tcp://")
            .unwrap_or(text.as_str())
            .parse::<std::net::SocketAddr>()
            .map_err(|_| crate::safety::bad_arg(NAME, target_hint, text))?,
        Value::Record(fields) => {
            let host = match fields.get("host") {
                Some(Value::Str(h)) => h
                    .parse::<std::net::IpAddr>()
                    .map_err(|_| crate::safety::bad_arg(NAME, "host: a literal IP address", h))?,
                _ => {
                    return Err(crate::safety::bad_arg(
                        NAME,
                        target_hint,
                        "a Record without a String host",
                    ))
                }
            };
            let port = match fields.get("port") {
                Some(Value::Int(n)) if (1..=65535i64).contains(n) => *n as u16,
                _ => {
                    return Err(crate::safety::bad_arg(
                        NAME,
                        "port: Int 1..65535",
                        "a missing or out-of-range port",
                    ))
                }
            };
            std::net::SocketAddr::new(host, port)
        }
        other => return Err(crate::safety::bad_arg(NAME, target_hint, other.type_name())),
    };
    let fields = match &options {
        Value::Record(fields) => fields,
        other => {
            return Err(crate::safety::bad_arg(
                NAME,
                "options: Record {token, code}",
                other.type_name(),
            ))
        }
    };
    let token = match fields.get("token") {
        Some(Value::Str(t)) if !t.is_empty() => t.clone(),
        _ => {
            return Err(crate::safety::bad_arg(
                NAME,
                "options.token: a non-empty String",
                "a missing or non-String token",
            ))
        }
    };
    let code = match fields.get("code") {
        Some(Value::Str(c)) => c.clone(),
        _ => {
            return Err(crate::safety::bad_arg(
                NAME,
                "options.code: a String",
                "a missing or non-String code",
            ))
        }
    };
    let line = format!("{}\n", serde_json::json!({"token": token, "code": code}));
    if line.len() > REPL_MAX_LINE {
        return Err(crate::safety::bad_arg(
            NAME,
            "code that fits one 1 MiB request line",
            "a longer String",
        ));
    }
    if crate::tx::is_active() {
        return Err(crate::safety::unimplemented(
            NAME,
            "network effects cannot be rolled back",
            "finish the transaction first",
        ));
    }
    guard_network(NAME, &format!("tcp://{addr}"))?;

    let mut stream = std::net::TcpStream::connect_timeout(&addr, REPL_IO_TIMEOUT)
        .map_err(|e| nc_io_error(NAME, e))?;
    stream
        .set_read_timeout(Some(REPL_EVAL_LIMIT + REPL_IO_TIMEOUT))
        .map_err(|e| nc_io_error(NAME, e))?;
    stream
        .set_write_timeout(Some(REPL_IO_TIMEOUT))
        .map_err(|e| nc_io_error(NAME, e))?;
    std::io::Write::write_all(&mut stream, line.as_bytes()).map_err(|e| nc_io_error(NAME, e))?;
    let read_side = stream.try_clone().map_err(|e| nc_io_error(NAME, e))?;
    let mut reader = std::io::BufReader::new(read_side);
    let reply_line = repl_read_line(&mut reader, REPL_MAX_LINE)
        .map_err(|reason| repl_io_error(NAME, &reason))?
        .ok_or_else(|| repl_io_error(NAME, "the listener closed without a reply"))?;
    let reply: serde_json::Value = serde_json::from_slice(&reply_line)
        .map_err(|e| repl_io_error(NAME, &format!("reply is not JSON: {e}")))?;

    let mut rec = BTreeMap::new();
    rec.insert("address".to_string(), Value::Str(addr.to_string()));
    if reply.get("ok").and_then(|v| v.as_bool()) == Some(true) {
        let value = json_to_value(
            reply
                .get("value")
                .cloned()
                .unwrap_or(serde_json::Value::Null),
        );
        let type_name = reply
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown")
            .to_string();
        rec.insert("ok".to_string(), Value::Bool(true));
        rec.insert("value".to_string(), value);
        rec.insert("type".to_string(), Value::Str(type_name));
        return Ok(Value::Record(rec));
    }
    let reason = reply
        .get("error")
        .and_then(|v| v.as_str())
        .unwrap_or("request refused")
        .to_string();
    if reason == "unauthorized" {
        return Err(crate::safety::policy_deny(
            NAME,
            "the listener refused the token",
            "present the token that repl_serve returned",
        ));
    }
    rec.insert("ok".to_string(), Value::Bool(false));
    rec.insert("error".to_string(), Value::Str(reason));
    Ok(Value::Record(rec))
}

/// repl_disconnect(session_id) - Remove a session from the session table.
fn bi_repl_disconnect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("repl_disconnect", &input)?;
    let id = collab_text_arg("repl_disconnect", "session_id", args.first(), 128)?;
    let mut sessions = REPL_SESSIONS
        .write()
        .map_err(|_| crate::safety::lock_poisoned("repl_disconnect", "the REPL session table"))?;
    let session = sessions
        .remove(&id)
        .ok_or_else(|| crate::safety::not_found("repl_disconnect", "repl session", &id))?;
    let mut rec = BTreeMap::new();
    rec.insert("id".to_string(), Value::Str(session.id));
    rec.insert("status".to_string(), Value::Str("disconnected".to_string()));
    rec.insert(
        "disconnected_at".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}

/// repl_broadcast(expression) - Refused: there is no peer set to send to.
fn bi_repl_broadcast(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("repl_broadcast", &input)?;
    collab_text_arg("repl_broadcast", "expression", args.first(), 4096)?;
    Err(crate::safety::unimplemented(
        "repl_broadcast",
        "nothing is sent: repl_connect holds no session open, so there is no peer set to broadcast to",
        "call repl_connect once per peer",
    ))
}

#[cfg(test)]
mod repl_protocol_tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn request_line_yields_token_and_code() {
        let parsed = repl_parse_request(br#"{"token":"t1","code":"1 + 1"}"#).expect("parses");
        assert_eq!(
            parsed,
            ReplRequest {
                token: "t1".into(),
                code: "1 + 1".into(),
            }
        );
        // A CRLF peer is tolerated.
        let crlf = repl_parse_request(b"{\"token\":\"t\",\"code\":\"2\"}\r").expect("parses");
        assert_eq!(crlf.code, "2");
    }

    #[test]
    fn malformed_request_lines_are_refused_with_a_reason() {
        let cases: [(&[u8], &str); 6] = [
            (b"not json", "not JSON"),
            (b"[1,2]", "JSON object"),
            (br#"{"code":"1"}"#, "token"),
            (br#"{"token":"t"}"#, "code"),
            (br#"{"token":5,"code":"1"}"#, "token"),
            (&[0xffu8, 0xfeu8], "UTF-8"),
        ];
        for (line, why) in cases {
            let reason = repl_parse_request(line).expect_err("refused");
            assert!(reason.contains(why), "{reason} should mention {why}");
        }
    }

    #[test]
    fn token_check_requires_an_exact_match() {
        assert!(repl_token_matches("abcd", "abcd"));
        assert!(!repl_token_matches("abcd", "abce"));
        assert!(!repl_token_matches("abcd", "abc"));
        assert!(!repl_token_matches("abcd", "abcde"));
        assert!(!repl_token_matches("abcd", ""));
    }

    #[test]
    fn lines_are_split_on_newline_then_eof() {
        let mut reader = Cursor::new(b"one\ntwo\n".to_vec());
        assert_eq!(repl_read_line(&mut reader, 16), Ok(Some(b"one".to_vec())));
        assert_eq!(repl_read_line(&mut reader, 16), Ok(Some(b"two".to_vec())));
        assert_eq!(repl_read_line(&mut reader, 16), Ok(None));
    }

    #[test]
    fn a_line_over_the_cap_is_refused_and_one_at_the_cap_is_kept() {
        let mut over = vec![b'x'; 5000];
        over.push(b'\n');
        let mut reader = Cursor::new(over);
        assert!(repl_read_line(&mut reader, 1000).is_err());

        let mut exact = vec![b'x'; 1000];
        exact.push(b'\n');
        let mut reader = Cursor::new(exact);
        assert_eq!(
            repl_read_line(&mut reader, 1000).map(|l| l.map(|v| v.len())),
            Ok(Some(1000))
        );
    }

    #[test]
    fn eof_mid_line_is_an_error_not_a_request() {
        let mut reader = Cursor::new(b"partial".to_vec());
        assert!(repl_read_line(&mut reader, 100).is_err());
    }
}

// ===================== Team Workspace Builtins =====================
//
// A workspace is a membership list and a list of shared agent names, held in
// process memory. Membership is keyed by the USER or USERNAME environment
// variable, which the caller sets, so it names whoever set it and is not an
// access control. Nothing leaves the process: workspace_sync refuses.

/// Most workspaces one process holds.
const WORKSPACE_MAX: usize = 256;
/// Most members one workspace holds.
const WORKSPACE_MAX_MEMBERS: usize = 64;
/// Most agent names one workspace shares.
const WORKSPACE_MAX_AGENTS: usize = 64;

/// workspace_create(name, options?) - Create a workspace owned by the caller.
/// The only option is `description` (a String of at most 1024 bytes).
fn bi_workspace_create(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("workspace_create", &input)?;
    let name = collab_text_arg("workspace_create", "name", args.first(), 128)?;
    let mut description = String::new();
    match args.get(1) {
        None => {}
        Some(Value::Record(opts)) => {
            if let Some(key) = opts.keys().find(|k| k.as_str() != "description") {
                return Err(crate::safety::bad_arg(
                    "workspace_create",
                    "options: {description?: String}",
                    &format!("unknown option `{key}`"),
                ));
            }
            match opts.get("description") {
                None => {}
                Some(Value::Str(s)) if s.len() <= 1024 => description = s.clone(),
                Some(other) => {
                    return Err(crate::safety::bad_arg(
                        "workspace_create",
                        "description: a String of at most 1024 bytes",
                        &collab_got(other),
                    ))
                }
            }
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "workspace_create",
                "options: Record",
                other.type_name(),
            ))
        }
    }

    let id = uuid::Uuid::new_v4().to_string();
    let owner = get_current_username("workspace_create")?;
    let created_at = chrono::Local::now().to_rfc3339();
    let mut workspaces = WORKSPACES
        .write()
        .map_err(|_| crate::safety::lock_poisoned("workspace_create", "the workspace registry"))?;
    if workspaces.len() >= WORKSPACE_MAX {
        return Err(crate::safety::budget_exceeded(
            "workspace_create",
            format!("workspace_create: {WORKSPACE_MAX} workspaces already exist in this process"),
            "a process holds a bounded number of workspaces; start another process for more",
        ));
    }
    workspaces.insert(
        id.clone(),
        TeamWorkspace {
            id: id.clone(),
            name: name.clone(),
            owner: owner.clone(),
            members: vec![WorkspaceMember {
                user: owner.clone(),
                role: "owner".to_string(),
                joined_at: created_at.clone(),
            }],
            shared_agents: Vec::new(),
            created_at: created_at.clone(),
            description: description.clone(),
        },
    );

    let mut rec = BTreeMap::new();
    rec.insert("id".to_string(), Value::Str(id));
    rec.insert("name".to_string(), Value::Str(name));
    rec.insert("owner".to_string(), Value::Str(owner));
    rec.insert("description".to_string(), Value::Str(description));
    rec.insert("member_count".to_string(), Value::Int(1));
    rec.insert("created_at".to_string(), Value::Str(created_at));
    Ok(Value::Record(rec))
}

/// workspace_join(workspace_id) - Add the caller to a workspace.
fn bi_workspace_join(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("workspace_join", &input)?;
    let ws_id = collab_text_arg("workspace_join", "workspace_id", args.first(), 64)?;
    let user = get_current_username("workspace_join")?;
    let mut workspaces = WORKSPACES
        .write()
        .map_err(|_| crate::safety::lock_poisoned("workspace_join", "the workspace registry"))?;
    let ws = workspaces
        .get_mut(&ws_id)
        .ok_or_else(|| crate::safety::not_found("workspace_join", "workspace", &ws_id))?;
    if ws.members.iter().any(|m| m.user == user) {
        return Err(crate::safety::bad_state(
            "workspace_join",
            &format!("already a member of '{}'", ws.name),
            "workspace_members",
        ));
    }
    if ws.members.len() >= WORKSPACE_MAX_MEMBERS {
        return Err(crate::safety::budget_exceeded(
            "workspace_join",
            format!(
                "workspace_join: '{}' already has {WORKSPACE_MAX_MEMBERS} members",
                ws.name
            ),
            "a workspace holds a bounded number of members",
        ));
    }
    ws.members.push(WorkspaceMember {
        user: user.clone(),
        role: "member".to_string(),
        joined_at: chrono::Local::now().to_rfc3339(),
    });
    let mut rec = BTreeMap::new();
    rec.insert("workspace_id".to_string(), Value::Str(ws_id));
    rec.insert("workspace_name".to_string(), Value::Str(ws.name.clone()));
    rec.insert("user".to_string(), Value::Str(user));
    rec.insert("role".to_string(), Value::Str("member".to_string()));
    rec.insert("status".to_string(), Value::Str("joined".to_string()));
    Ok(Value::Record(rec))
}

/// workspace_leave(workspace_id) - Remove the caller from a workspace. The
/// owner cannot leave: ownership cannot be transferred yet.
fn bi_workspace_leave(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("workspace_leave", &input)?;
    let ws_id = collab_text_arg("workspace_leave", "workspace_id", args.first(), 64)?;
    let user = get_current_username("workspace_leave")?;
    let mut workspaces = WORKSPACES
        .write()
        .map_err(|_| crate::safety::lock_poisoned("workspace_leave", "the workspace registry"))?;
    let ws = workspaces
        .get_mut(&ws_id)
        .ok_or_else(|| crate::safety::not_found("workspace_leave", "workspace", &ws_id))?;
    if ws.owner == user {
        return Err(crate::safety::policy_deny(
            "workspace_leave",
            format!("the owner of '{}' cannot leave it", ws.name),
            "ownership cannot be transferred yet, so the owner stays",
        ));
    }
    let before = ws.members.len();
    ws.members.retain(|m| m.user != user);
    if ws.members.len() == before {
        return Err(crate::safety::bad_state(
            "workspace_leave",
            &format!("not a member of '{}'", ws.name),
            "workspace_members",
        ));
    }
    let mut rec = BTreeMap::new();
    rec.insert("workspace_id".to_string(), Value::Str(ws_id));
    rec.insert("workspace_name".to_string(), Value::Str(ws.name.clone()));
    rec.insert("user".to_string(), Value::Str(user));
    rec.insert("status".to_string(), Value::Str("left".to_string()));
    Ok(Value::Record(rec))
}

/// workspace_members(workspace_id) - The members of a workspace.
fn bi_workspace_members(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("workspace_members", &input)?;
    let ws_id = collab_text_arg("workspace_members", "workspace_id", args.first(), 64)?;
    let workspaces = WORKSPACES
        .read()
        .map_err(|_| crate::safety::lock_poisoned("workspace_members", "the workspace registry"))?;
    let ws = workspaces
        .get(&ws_id)
        .ok_or_else(|| crate::safety::not_found("workspace_members", "workspace", &ws_id))?;
    let members: Vec<Value> = ws
        .members
        .iter()
        .map(|m| {
            let mut rec = BTreeMap::new();
            rec.insert("user".to_string(), Value::Str(m.user.clone()));
            rec.insert("role".to_string(), Value::Str(m.role.clone()));
            rec.insert("joined_at".to_string(), Value::Str(m.joined_at.clone()));
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(members))
}

/// workspace_share_agent(workspace_id, agent) - Share a registered agent (see
/// a2a_register) into a workspace the caller belongs to.
fn bi_workspace_share_agent(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("workspace_share_agent", &input)?;
    let ws_id = collab_text_arg("workspace_share_agent", "workspace_id", args.first(), 64)?;
    let agent = collab_text_arg("workspace_share_agent", "agent", args.get(1), 128)?;
    let user = get_current_username("workspace_share_agent")?;
    let mut workspaces = WORKSPACES.write().map_err(|_| {
        crate::safety::lock_poisoned("workspace_share_agent", "the workspace registry")
    })?;
    let ws = workspaces
        .get_mut(&ws_id)
        .ok_or_else(|| crate::safety::not_found("workspace_share_agent", "workspace", &ws_id))?;
    if !ws.members.iter().any(|m| m.user == user) {
        return Err(crate::safety::policy_deny(
            "workspace_share_agent",
            format!("{user} is not a member of '{}'", ws.name),
            "join the workspace before sharing an agent into it",
        ));
    }
    let registered = A2A_REGISTRY
        .read()
        .map_err(|_| {
            crate::safety::lock_poisoned("workspace_share_agent", "the A2A agent registry")
        })?
        .contains_key(&agent);
    if !registered {
        return Err(crate::safety::not_found(
            "workspace_share_agent",
            "agent",
            &agent,
        ));
    }
    if ws.shared_agents.contains(&agent) {
        return Err(crate::safety::bad_state(
            "workspace_share_agent",
            &format!("'{agent}' is already shared in '{}'", ws.name),
            "workspace_agents",
        ));
    }
    if ws.shared_agents.len() >= WORKSPACE_MAX_AGENTS {
        return Err(crate::safety::budget_exceeded(
            "workspace_share_agent",
            format!(
                "workspace_share_agent: '{}' already shares {WORKSPACE_MAX_AGENTS} agents",
                ws.name
            ),
            "a workspace shares a bounded number of agents",
        ));
    }
    ws.shared_agents.push(agent.clone());
    let mut rec = BTreeMap::new();
    rec.insert("workspace_id".to_string(), Value::Str(ws_id));
    rec.insert("agent".to_string(), Value::Str(agent));
    rec.insert("status".to_string(), Value::Str("shared".to_string()));
    rec.insert(
        "total_agents".to_string(),
        Value::Int(ws.shared_agents.len() as i64),
    );
    Ok(Value::Record(rec))
}

/// workspace_agents(workspace_id) - The agent names shared in a workspace.
fn bi_workspace_agents(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("workspace_agents", &input)?;
    let ws_id = collab_text_arg("workspace_agents", "workspace_id", args.first(), 64)?;
    let workspaces = WORKSPACES
        .read()
        .map_err(|_| crate::safety::lock_poisoned("workspace_agents", "the workspace registry"))?;
    let ws = workspaces
        .get(&ws_id)
        .ok_or_else(|| crate::safety::not_found("workspace_agents", "workspace", &ws_id))?;
    Ok(Value::Array(
        ws.shared_agents
            .iter()
            .map(|a| Value::Str(a.clone()))
            .collect(),
    ))
}

/// workspace_sync(workspace_id) - Refused: there are no peers to sync with.
fn bi_workspace_sync(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped_subject("workspace_sync", &input)?;
    let ws_id = collab_text_arg("workspace_sync", "workspace_id", args.first(), 64)?;
    let workspaces = WORKSPACES
        .read()
        .map_err(|_| crate::safety::lock_poisoned("workspace_sync", "the workspace registry"))?;
    if !workspaces.contains_key(&ws_id) {
        return Err(crate::safety::not_found(
            "workspace_sync",
            "workspace",
            &ws_id,
        ));
    }
    Err(crate::safety::unimplemented(
        "workspace_sync",
        "there are no remote peers, so nothing is synced; this workspace is local to this process",
        "workspace_members and workspace_agents report its local state",
    ))
}

/// List active REPL sessions.
/// Usage: repl.sessions()
fn bi_repl_sessions(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let sessions = REPL_SESSIONS
        .read()
        .map_err(|_| crate::safety::lock_poisoned("repl_sessions", "the REPL session table"))?;
    let entries: Vec<Value> = sessions
        .values()
        .map(|s| {
            let mut rec = BTreeMap::new();
            rec.insert("id".to_string(), Value::Str(s.id.clone()));
            rec.insert("host".to_string(), Value::Str(s.host.clone()));
            rec.insert("port".to_string(), Value::Int(s.port as i64));
            rec.insert("user".to_string(), Value::Str(s.user.clone()));
            rec.insert("status".to_string(), Value::Str(s.status.clone()));
            rec.insert(
                "connected_at".to_string(),
                Value::Str(s.connected_at.clone()),
            );
            if let Some(ref ws) = s.workspace_id {
                rec.insert("workspace_id".to_string(), Value::Str(ws.clone()));
            }
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(entries))
}

/// List all workspaces the current user belongs to.
/// Usage: workspace.list()
fn bi_workspace_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let workspaces = WORKSPACES
        .read()
        .map_err(|_| crate::safety::lock_poisoned("workspace_list", "the workspace registry"))?;
    let user = get_current_username("workspace_list")?;
    let entries: Vec<Value> = workspaces
        .values()
        .filter(|ws| ws.members.iter().any(|m| m.user == user))
        .map(|ws| {
            let mut rec = BTreeMap::new();
            rec.insert("id".to_string(), Value::Str(ws.id.clone()));
            rec.insert("name".to_string(), Value::Str(ws.name.clone()));
            rec.insert("owner".to_string(), Value::Str(ws.owner.clone()));
            rec.insert(
                "description".to_string(),
                Value::Str(ws.description.clone()),
            );
            rec.insert(
                "member_count".to_string(),
                Value::Int(ws.members.len() as i64),
            );
            rec.insert(
                "agent_count".to_string(),
                Value::Int(ws.shared_agents.len() as i64),
            );
            rec.insert("created_at".to_string(), Value::Str(ws.created_at.clone()));
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(entries))
}

// ===================== Marketplace Builtins =====================

const MARKETPLACE_REGISTRY: &str = "https://packages.nervosys.ai";

/// A package name or version. Both are written into cache paths and registry
/// URLs, so anything that could leave the cache directory or read as an option
/// (a `/`, a `..`, a leading `-`) is refused here, before any request.
fn package_token(builtin: &str, what: &str, s: &str) -> Result<String> {
    let ok = !s.is_empty()
        && s.len() <= 128
        && !s.starts_with(['-', '.'])
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '+'));
    if ok {
        Ok(s.to_string())
    } else {
        Err(crate::safety::bad_arg(
            builtin,
            &format!(
                "{what}: 1 to 128 letters, digits, '.', '_', '-' or '+', not starting with '-' or '.'"
            ),
            &format!("{s:?}"),
        ))
    }
}

/// A string argument, refused with the expected shape when it is not one.
fn str_arg<'a>(builtin: &str, v: Option<&'a Value>, what: &str) -> Result<&'a str> {
    match v {
        Some(Value::Str(s)) => Ok(s.as_str()),
        other => Err(crate::safety::bad_arg(
            builtin,
            what,
            other.map_or("nothing", Value::type_name),
        )),
    }
}

/// A registry request that did not complete. Nothing local has changed when
/// this is returned, so the call can be repeated as it stands.
fn registry_failure(builtin: &str, e: &anyhow::Error) -> anyhow::Error {
    // A coded error from the client (a refused path, a hostile archive, a
    // missing token) keeps its code; it used to become E_POLICY_DENY here,
    // which told the caller the shell's policy had refused when it had not.
    if let Some(coded) = e.downcast_ref::<crate::safety::SafetyError>() {
        let mut coded = coded.clone();
        coded.builtin = builtin.to_string();
        coded.message = format!("{builtin}: {}", coded.message);
        return anyhow::Error::new(coded);
    }
    crate::safety::io_fault(
        builtin,
        &format!("the package registry did not complete the request: {e:#}"),
        "the registry could not be reached or answered badly; check the network, then retry",
    )
}

/// Whether a registry error says the package does not exist, as opposed to
/// the registry being unreachable or refusing the request.
fn registry_says_absent(e: &anyhow::Error) -> bool {
    e.downcast_ref::<crate::safety::SafetyError>()
        .is_some_and(|s| s.code == crate::safety::ErrorCode::NotFound)
}

/// Mark a record with where it came from, so a caller never mistakes a local
/// catalogue entry for the registry's answer.
fn with_source(mut v: Value, source: &str) -> Value {
    if let Value::Record(r) = &mut v {
        r.insert("source".to_string(), Value::Str(source.to_string()));
    }
    v
}

/// Publish a plugin or agent to the marketplace.
/// With `path`, uploads that file to packages.nervosys.ai (network-guarded,
/// inside the workspace, and needs IRONSHELL_REGISTRY_TOKEN); the status is then
/// `published`. Without `path` the package is recorded in the local catalogue
/// only, and the status says so: `recorded_locally`.
/// Usage: marketplace.publish({name, version, description?, category?, keywords?, path?})
fn bi_marketplace_publish(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    const FIELDS: &[&str] = &[
        "name",
        "version",
        "description",
        "category",
        "keywords",
        "path",
    ];
    const MAX_KEYWORDS: usize = 32;
    let opts = match args.first() {
        Some(Value::Record(r)) => r.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "marketplace.publish requires a Record with name, version, description",
            ))
        }
    };
    if let Some(bad) = opts.keys().find(|k| !FIELDS.contains(&k.as_str())) {
        return Err(crate::safety::bad_arg(
            "marketplace_publish",
            "a record with only the fields name, version, description, category, keywords and path",
            &format!("field {bad:?}"),
        ));
    }
    // A field of the wrong type used to fall back to its default, so a number
    // given as a description was published with an empty one.
    let text = |key: &str| -> Result<Option<String>> {
        match opts.get(key) {
            None => Ok(None),
            Some(Value::Str(s)) => Ok(Some(s.clone())),
            Some(other) => Err(crate::safety::bad_arg(
                "marketplace_publish",
                &format!("{key}: a string"),
                other.type_name(),
            )),
        }
    };
    let name = package_token(
        "marketplace_publish",
        "name",
        &text("name")?
            .ok_or_else(|| crate::safety::arg_err("marketplace.publish requires 'name'"))?,
    )?;
    let version = package_token(
        "marketplace_publish",
        "version",
        &text("version")?
            .ok_or_else(|| crate::safety::arg_err("marketplace.publish requires 'version'"))?,
    )?;
    let description = text("description")?.unwrap_or_default();
    if description.len() > 4096 || description.chars().any(char::is_control) {
        return Err(crate::safety::bad_arg(
            "marketplace_publish",
            "description: at most 4096 bytes with no control characters",
            "a description that does not fit",
        ));
    }
    let category = text("category")?.unwrap_or_else(|| "general".to_string());
    let keywords: Vec<String> = match opts.get("keywords") {
        None => Vec::new(),
        Some(Value::Array(arr)) if arr.len() <= MAX_KEYWORDS => arr
            .iter()
            .map(|v| match v {
                Value::Str(s) => Ok(s.clone()),
                other => Err(crate::safety::bad_arg(
                    "marketplace_publish",
                    "keywords: an array of strings",
                    other.type_name(),
                )),
            })
            .collect::<Result<Vec<_>>>()?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "marketplace_publish",
                &format!("keywords: an array of at most {MAX_KEYWORDS} strings"),
                other.type_name(),
            ))
        }
    };
    let path = match text("path")? {
        None => None,
        Some(p) => {
            // The file is read and sent to a server, so only a file the
            // workspace already holds may be published.
            if !crate::safety::within_workspace(&p) {
                return Err(crate::safety::outside_workspace("marketplace_publish", &p));
            }
            let meta = std::fs::metadata(&p)
                .map_err(|e| crate::safety::fs_error("marketplace_publish", &p, &e))?;
            if !meta.is_file() {
                return Err(crate::safety::bad_arg(
                    "marketplace_publish",
                    "path: a file to upload",
                    &format!("{p:?}"),
                ));
            }
            Some(std::path::PathBuf::from(p))
        }
    };

    // Egress is decided at dispatch: `Network` is centrally enforced, so the
    // upload is metered and gated before this body runs.
    // Resolved before the upload, so a missing user cannot leave a published
    // package without an author.
    let user = get_current_username("marketplace_publish")?;
    let target = match &path {
        Some(tarball) => {
            let manifest = crate::packages::PackageManifest {
                package: crate::packages::PackageInfo {
                    name: name.clone(),
                    version: version.clone(),
                    description: description.clone(),
                    authors: vec![user.clone()],
                    license: None,
                    repository: None,
                    main: "main.ish".to_string(),
                },
                dependencies: std::collections::HashMap::new(),
            };
            crate::packages::RegistryClient::default()
                .publish(tarball, &manifest)
                .map_err(|e| registry_failure("marketplace_publish", &e))?;
            "registry"
        }
        None => "local",
    };

    let published_at = chrono::Local::now().to_rfc3339();
    let package = MarketplacePackage {
        name: name.clone(),
        version: version.clone(),
        author: user,
        description: description.clone(),
        category: category.clone(),
        downloads: 0,
        rating: 0.0,
        rating_count: 0,
        published_at: published_at.clone(),
        installed: false,
        keywords,
    };
    MARKETPLACE_PACKAGES
        .write()
        .map_err(|_| {
            crate::safety::lock_poisoned("marketplace_publish", "the marketplace package cache")
        })?
        .insert(name.clone(), package);

    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(name));
    rec.insert("version".to_string(), Value::Str(version));
    rec.insert("description".to_string(), Value::Str(description));
    rec.insert("category".to_string(), Value::Str(category));
    rec.insert(
        "status".to_string(),
        Value::Str(
            if target == "registry" {
                "published"
            } else {
                "recorded_locally"
            }
            .to_string(),
        ),
    );
    rec.insert("target".to_string(), Value::Str(target.to_string()));
    rec.insert("published_at".to_string(), Value::Str(published_at));
    Ok(Value::Record(rec))
}

/// Search the marketplace for packages.
/// Searches the remote registry at packages.nervosys.ai, falls back to local cache.
/// Each record says whether it came from the `registry` or the `local_cache`. If
/// the registry could not be reached and the local cache has nothing to offer,
/// that is an error, not an empty list.
/// Usage: marketplace.search(query) or marketplace.search({q?, category?})
fn bi_marketplace_search(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    fn query_text(builtin: &str, s: &str) -> Result<String> {
        if s.len() > 256 || s.chars().any(char::is_control) {
            return Err(crate::safety::bad_arg(
                builtin,
                "a query of at most 256 bytes with no control characters",
                &format!("{:?}", s.chars().take(40).collect::<String>()),
            ));
        }
        Ok(s.to_lowercase())
    }
    let (query, category) = match args.first() {
        None => (String::new(), None),
        Some(Value::Str(s)) => (query_text("marketplace_search", s)?, None),
        Some(Value::Record(r)) => {
            if let Some(bad) = r
                .keys()
                .find(|k| !matches!(k.as_str(), "q" | "query" | "category"))
            {
                return Err(crate::safety::bad_arg(
                    "marketplace_search",
                    "a record with only the fields q, query and category",
                    &format!("field {bad:?}"),
                ));
            }
            let q = match r.get("q").or_else(|| r.get("query")) {
                None => String::new(),
                Some(Value::Str(s)) => query_text("marketplace_search", s)?,
                Some(other) => {
                    return Err(crate::safety::bad_arg(
                        "marketplace_search",
                        "q: a string",
                        other.type_name(),
                    ))
                }
            };
            let cat = match r.get("category") {
                None => None,
                Some(Value::Str(s)) => Some(s.clone()),
                Some(other) => {
                    return Err(crate::safety::bad_arg(
                        "marketplace_search",
                        "category: a string",
                        other.type_name(),
                    ))
                }
            };
            (q, cat)
        }
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "marketplace_search",
                "a query string or a Record {q?, category?}",
                other.type_name(),
            ))
        }
    };

    guard_network("marketplace_search", MARKETPLACE_REGISTRY)?;

    let client = crate::packages::RegistryClient::default();
    let registry_error = match client.search(&query, category.as_deref()) {
        Ok(remote_pkgs) if !remote_pkgs.is_empty() => {
            let results: Vec<Value> = remote_pkgs
                .iter()
                .map(|p| {
                    with_source(
                        crate::packages::RegistryClient::package_to_value(p),
                        "registry",
                    )
                })
                .collect();
            return Ok(Value::Array(results));
        }
        Ok(_) => None,
        Err(e) => Some(e),
    };

    // Fall back to local cache
    let packages = MARKETPLACE_PACKAGES.read().map_err(|_| {
        crate::safety::lock_poisoned("marketplace_search", "the marketplace package cache")
    })?;
    let results: Vec<Value> = packages
        .values()
        .filter(|pkg| {
            let matches_query = query.is_empty()
                || pkg.name.to_lowercase().contains(&query)
                || pkg.description.to_lowercase().contains(&query)
                || pkg
                    .keywords
                    .iter()
                    .any(|k| k.to_lowercase().contains(&query));
            let matches_category = category
                .as_ref()
                .map(|c| pkg.category.to_lowercase() == c.to_lowercase())
                .unwrap_or(true);
            matches_query && matches_category
        })
        .map(marketplace_package_to_value)
        .collect();

    if let (true, Some(e)) = (results.is_empty(), registry_error.as_ref()) {
        return Err(registry_failure("marketplace_search", e));
    }
    Ok(Value::Array(results))
}

fn marketplace_package_to_value(pkg: &MarketplacePackage) -> Value {
    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(pkg.name.clone()));
    rec.insert("version".to_string(), Value::Str(pkg.version.clone()));
    rec.insert("author".to_string(), Value::Str(pkg.author.clone()));
    rec.insert(
        "description".to_string(),
        Value::Str(pkg.description.clone()),
    );
    rec.insert("category".to_string(), Value::Str(pkg.category.clone()));
    rec.insert("downloads".to_string(), Value::Int(pkg.downloads));
    rec.insert("rating".to_string(), Value::Float(pkg.rating));
    rec.insert("rating_count".to_string(), Value::Int(pkg.rating_count));
    rec.insert(
        "published_at".to_string(),
        Value::Str(pkg.published_at.clone()),
    );
    rec.insert("installed".to_string(), Value::Bool(pkg.installed));
    rec.insert("source".to_string(), Value::Str("local_cache".to_string()));
    if !pkg.keywords.is_empty() {
        rec.insert(
            "keywords".to_string(),
            Value::Array(pkg.keywords.iter().map(|k| Value::Str(k.clone())).collect()),
        );
    }
    Value::Record(rec)
}

/// Install a package from the marketplace: download the registry's archive
/// into the package cache and unpack it. Nothing is run; extraction is the
/// whole of it. A package the registry does not hold is an error. There is no
/// local fallback, because the local catalogue holds records, not archives.
/// Usage: marketplace.install(name) or marketplace.install(name, version)
fn bi_marketplace_install(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    crate::safety::check_egress_unknown(
        "marketplace_install",
        "the marketplace the package is fetched from is set by the configured registry, not the arguments",
    )?;
    let name = package_token(
        "marketplace_install",
        "name",
        str_arg("marketplace_install", args.first(), "a package name string")?,
    )?;
    let version = match args.get(1) {
        None => None,
        Some(v) => Some(package_token(
            "marketplace_install",
            "version",
            str_arg("marketplace_install", Some(v), "a version string")?,
        )?),
    };

    // Not metered against IRONSHELL_MAX_NET: this builtin is gated as `Exec` at
    // dispatch, and calling `guard_network` here would need it listed as
    // self-guarding, which skips that approval. See the report.
    let client = crate::packages::RegistryClient::default();
    let pkg_info = match client.get_package(&name) {
        Ok(p) => p,
        Err(e) if registry_says_absent(&e) => {
            return Err(crate::safety::not_found(
                "marketplace_install",
                "package",
                &name,
            ))
        }
        Err(e) => return Err(registry_failure("marketplace_install", &e)),
    };
    // The registry's own version string names a directory, so it is checked
    // like any other name before it is used.
    let ver = match version {
        Some(v) => v,
        None => package_token("marketplace_install", "version", &pkg_info.version)?,
    };
    let install_path = client
        .download_package(&name, &ver, pkg_info.checksum.as_deref())
        .map_err(|e| registry_failure("marketplace_install", &e))?;

    // Update the local catalogue. A poisoned lock used to skip this and still
    // report "installed"; the download is on disk, so the error names it.
    {
        let mut packages = MARKETPLACE_PACKAGES.write().map_err(|_| {
            crate::safety::lock_poisoned(
                "marketplace_install",
                &format!(
                    "the package catalogue (`{}` was downloaded but not recorded)",
                    install_path.display()
                ),
            )
        })?;
        let existing = packages
            .entry(name.clone())
            .or_insert_with(|| MarketplacePackage {
                name: name.clone(),
                version: ver.clone(),
                author: pkg_info.author.clone(),
                description: pkg_info.description.clone(),
                category: pkg_info
                    .category
                    .clone()
                    .unwrap_or_else(|| "general".to_string()),
                downloads: pkg_info.downloads,
                rating: 0.0,
                rating_count: 0,
                published_at: pkg_info.created_at.clone(),
                installed: false,
                keywords: pkg_info.keywords.clone(),
            });
        existing.installed = true;
        existing.downloads += 1;
    }
    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(name));
    rec.insert("version".to_string(), Value::Str(ver));
    rec.insert("status".to_string(), Value::Str("installed".to_string()));
    rec.insert("source".to_string(), Value::Str("registry".to_string()));
    rec.insert(
        "path".to_string(),
        Value::Str(install_path.display().to_string()),
    );
    rec.insert(
        "installed_at".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}

/// Uninstall a marketplace package: remove its cached archive and unpacked
/// files, and clear the installed flag. Reports whether any files were there.
/// Usage: marketplace.uninstall(name)
fn bi_marketplace_uninstall(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = package_token(
        "marketplace_uninstall",
        "name",
        str_arg(
            "marketplace_uninstall",
            args.first(),
            "a package name string",
        )?,
    )?;
    let mut packages = MARKETPLACE_PACKAGES.write().map_err(|_| {
        crate::safety::lock_poisoned("marketplace_uninstall", "the marketplace package cache")
    })?;
    let Some(pkg) = packages.get_mut(&name) else {
        return Err(crate::safety::not_found(
            "marketplace_uninstall",
            "package",
            &name,
        ));
    };
    if !pkg.installed {
        return Err(crate::safety::bad_state(
            "marketplace_uninstall",
            &format!("package '{name}' is not installed, so there is nothing to remove"),
            "marketplace_install",
        ));
    }
    // The install wrote into the package's own cache directory. The name has
    // been checked to be a single path segment, so this cannot reach beyond it.
    let dir = crate::packages::RegistryClient::default()
        .cache_dir
        .join(&name);
    let files_removed = if dir.exists() {
        std::fs::remove_dir_all(&dir)
            .map_err(|e| crate::safety::fs_error("marketplace_uninstall", &dir, &e))?;
        true
    } else {
        false
    };
    pkg.installed = false;

    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(pkg.name.clone()));
    rec.insert("status".to_string(), Value::Str("uninstalled".to_string()));
    rec.insert("files_removed".to_string(), Value::Bool(files_removed));
    rec.insert(
        "uninstalled_at".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}

/// List installed marketplace packages.
/// Usage: marketplace.list()
fn bi_marketplace_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let packages = MARKETPLACE_PACKAGES.read().map_err(|_| {
        crate::safety::lock_poisoned("marketplace_list", "the marketplace package cache")
    })?;
    let installed: Vec<Value> = packages
        .values()
        .filter(|pkg| pkg.installed)
        .map(marketplace_package_to_value)
        .collect();
    Ok(Value::Array(installed))
}

/// Get detailed info about a marketplace package.
/// Checks remote registry first, falls back to local cache; the `source` field
/// says which answered. A registry that could not be reached, with nothing in
/// the local cache, is an error.
/// Usage: marketplace.info(name)
fn bi_marketplace_info(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = package_token(
        "marketplace_info",
        "name",
        str_arg("marketplace_info", args.first(), "a package name string")?,
    )?;

    guard_network("marketplace_info", MARKETPLACE_REGISTRY)?;
    let client = crate::packages::RegistryClient::default();
    let registry_error = match client.get_package(&name) {
        Ok(pkg) => {
            return Ok(with_source(
                crate::packages::RegistryClient::package_to_value(&pkg),
                "registry",
            ))
        }
        Err(e) if registry_says_absent(&e) => None,
        Err(e) => Some(e),
    };

    let packages = MARKETPLACE_PACKAGES.read().map_err(|_| {
        crate::safety::lock_poisoned("marketplace_info", "the marketplace package cache")
    })?;
    if let Some(pkg) = packages.get(&name) {
        return Ok(marketplace_package_to_value(pkg));
    }
    Err(match registry_error {
        Some(e) => registry_failure("marketplace_info", &e),
        None => crate::safety::not_found("marketplace_info", "package", &name),
    })
}

/// Rate a marketplace package. The rating is kept in the local catalogue
/// (`scope: local_cache`); it is not sent to the registry.
/// Usage: marketplace.rate(name, score) — score 1-5
fn bi_marketplace_rate(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let name = package_token(
        "marketplace_rate",
        "name",
        str_arg("marketplace_rate", args.first(), "a package name string")?,
    )?;
    let score = match args.get(1) {
        Some(Value::Int(n)) => *n as f64,
        Some(Value::Float(f)) => *f,
        other => {
            return Err(crate::safety::bad_arg(
                "marketplace_rate",
                "a score from 1 to 5",
                other.map_or("nothing", Value::type_name),
            ))
        }
    };
    if !(1.0..=5.0).contains(&score) {
        return Err(crate::safety::bad_arg(
            "marketplace_rate",
            "a score from 1 to 5",
            &format!("{score}"),
        ));
    }
    let mut packages = MARKETPLACE_PACKAGES.write().map_err(|_| {
        crate::safety::lock_poisoned("marketplace_rate", "the marketplace package cache")
    })?;
    let Some(pkg) = packages.get_mut(&name) else {
        return Err(crate::safety::not_found(
            "marketplace_rate",
            "package",
            &name,
        ));
    };
    // Compute new weighted average
    let total = pkg.rating * pkg.rating_count as f64 + score;
    pkg.rating_count += 1;
    pkg.rating = total / pkg.rating_count as f64;
    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(pkg.name.clone()));
    rec.insert("rating".to_string(), Value::Float(pkg.rating));
    rec.insert("rating_count".to_string(), Value::Int(pkg.rating_count));
    rec.insert("your_rating".to_string(), Value::Float(score));
    rec.insert("scope".to_string(), Value::Str("local_cache".to_string()));
    Ok(Value::Record(rec))
}

/// Check installed marketplace packages against the registry for a newer
/// version. This reports `update_available` with the `latest` version; it does
/// not install anything. With a name, one package, and a registry failure is an
/// error. Without one, every installed package, and a package that could not be
/// checked says `unreachable` with the reason.
/// Usage: marketplace.update(name) or marketplace.update() for all
fn bi_marketplace_update(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let single = match args.first() {
        None => None,
        Some(v) => Some(package_token(
            "marketplace_update",
            "name",
            str_arg("marketplace_update", Some(v), "a package name string")?,
        )?),
    };

    // What to check, decided from the local catalogue before any request, so a
    // name that is absent or not installed costs no network round trip.
    let targets: Vec<(String, String)> = {
        let packages = MARKETPLACE_PACKAGES.read().map_err(|_| {
            crate::safety::lock_poisoned("marketplace_update", "the marketplace package cache")
        })?;
        match &single {
            Some(name) => match packages.get(name) {
                None => {
                    return Err(crate::safety::not_found(
                        "marketplace_update",
                        "package",
                        name,
                    ))
                }
                Some(p) if !p.installed => {
                    return Err(crate::safety::bad_state(
                        "marketplace_update",
                        &format!("package '{name}' is not installed"),
                        "marketplace_install",
                    ))
                }
                Some(p) => vec![(p.name.clone(), p.version.clone())],
            },
            None => packages
                .values()
                .filter(|p| p.installed)
                .map(|p| (p.name.clone(), p.version.clone()))
                .collect(),
        }
    };

    let client = crate::packages::RegistryClient::default();
    let mut out: Vec<Value> = Vec::with_capacity(targets.len());
    for (name, local_version) in &targets {
        guard_network("marketplace_update", MARKETPLACE_REGISTRY)?;
        let mut rec = BTreeMap::new();
        rec.insert("name".to_string(), Value::Str(name.clone()));
        rec.insert("version".to_string(), Value::Str(local_version.clone()));
        match client.get_package(name) {
            Ok(remote) if remote.version == *local_version => {
                rec.insert("status".to_string(), Value::Str("up_to_date".to_string()));
            }
            Ok(remote) => {
                rec.insert("latest".to_string(), Value::Str(remote.version));
                rec.insert(
                    "status".to_string(),
                    Value::Str("update_available".to_string()),
                );
            }
            Err(e) if registry_says_absent(&e) => {
                rec.insert(
                    "status".to_string(),
                    Value::Str("not_in_registry".to_string()),
                );
            }
            Err(e) => {
                if single.is_some() {
                    return Err(registry_failure("marketplace_update", &e));
                }
                rec.insert("status".to_string(), Value::Str("unreachable".to_string()));
                rec.insert("reason".to_string(), Value::Str(format!("{e:#}")));
            }
        }
        rec.insert(
            "checked_at".to_string(),
            Value::Str(chrono::Local::now().to_rfc3339()),
        );
        out.push(Value::Record(rec));
    }

    match single {
        Some(_) => Ok(out.pop().unwrap_or(Value::Null)),
        None => Ok(Value::Array(out)),
    }
}

// ===================== Telemetry & Analytics Builtins =====================

/// Enable opt-in telemetry.
/// Usage: telemetry.enable()
fn bi_telemetry_enable(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut enabled = TELEMETRY_ENABLED
        .write()
        .map_err(|_| crate::safety::lock_poisoned("telemetry_enable", "the telemetry switch"))?;
    *enabled = true;

    // Record the opt-in event
    let event = TelemetryEvent {
        id: uuid::Uuid::new_v4().to_string(),
        event_type: "telemetry_enabled".to_string(),
        category: "system".to_string(),
        data: HashMap::new(),
        timestamp: chrono::Local::now().to_rfc3339(),
        session_id: uuid::Uuid::new_v4().to_string(),
    };
    if let Ok(mut events) = TELEMETRY_EVENTS.write() {
        events.push(event);
    }

    let mut rec = BTreeMap::new();
    rec.insert("enabled".to_string(), Value::Bool(true));
    rec.insert(
        "status".to_string(),
        Value::Str("telemetry enabled (opt-in)".to_string()),
    );
    rec.insert(
        "note".to_string(),
        Value::Str("Data is stored locally. Use telemetry.report() to view.".to_string()),
    );
    Ok(Value::Record(rec))
}

/// Disable telemetry.
/// Usage: telemetry.disable()
fn bi_telemetry_disable(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut enabled = TELEMETRY_ENABLED
        .write()
        .map_err(|_| crate::safety::lock_poisoned("telemetry_disable", "the telemetry switch"))?;
    *enabled = false;

    let mut rec = BTreeMap::new();
    rec.insert("enabled".to_string(), Value::Bool(false));
    rec.insert(
        "status".to_string(),
        Value::Str("telemetry disabled".to_string()),
    );
    Ok(Value::Record(rec))
}

/// Get current telemetry status.
/// Usage: telemetry.status()
fn bi_telemetry_status(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let enabled = TELEMETRY_ENABLED
        .read()
        .map_err(|_| crate::safety::lock_poisoned("telemetry_status", "the telemetry switch"))?;
    let events = TELEMETRY_EVENTS.read().map_err(|_| {
        crate::safety::lock_poisoned("telemetry_status", "the telemetry event buffer")
    })?;

    let mut rec = BTreeMap::new();
    rec.insert("enabled".to_string(), Value::Bool(*enabled));
    rec.insert("event_count".to_string(), Value::Int(events.len() as i64));
    rec.insert("storage".to_string(), Value::Str("local".to_string()));
    rec.insert(
        "privacy".to_string(),
        Value::Str("All data stored locally. No external transmission.".to_string()),
    );
    Ok(Value::Record(rec))
}

/// Generate a telemetry usage report.
/// Usage: telemetry.report() or telemetry.report({category?})
fn bi_telemetry_report(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let opts = match args.first() {
        Some(Value::Record(r)) => r.clone(),
        None => BTreeMap::new(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "telemetry_report",
                "options: Record",
                other.type_name(),
            ))
        }
    };
    for (key, value) in &opts {
        if key != "category" {
            return Err(crate::safety::arg_err(format!(
                "telemetry_report: unknown option {key}"
            )));
        }
        expect_string("telemetry_report category", value)?;
    }
    let category_filter = opts.get("category").and_then(|v| {
        if let Value::Str(s) = v {
            Some(s.clone())
        } else {
            None
        }
    });

    let events = TELEMETRY_EVENTS.read().map_err(|_| {
        crate::safety::lock_poisoned("telemetry_report", "the telemetry event buffer")
    })?;

    // Group by category
    let mut by_category: BTreeMap<String, i64> = BTreeMap::new();
    let mut by_type: BTreeMap<String, i64> = BTreeMap::new();
    let mut filtered_count = 0i64;

    for event in events.iter() {
        let include = category_filter
            .as_ref()
            .map(|c| event.category == *c)
            .unwrap_or(true);
        if include {
            filtered_count += 1;
            *by_category.entry(event.category.clone()).or_insert(0) += 1;
            *by_type.entry(event.event_type.clone()).or_insert(0) += 1;
        }
    }

    let categories: Vec<Value> = by_category
        .iter()
        .map(|(k, v)| {
            let mut rec = BTreeMap::new();
            rec.insert("category".to_string(), Value::Str(k.clone()));
            rec.insert("count".to_string(), Value::Int(*v));
            Value::Record(rec)
        })
        .collect();

    let types: Vec<Value> = by_type
        .iter()
        .map(|(k, v)| {
            let mut rec = BTreeMap::new();
            rec.insert("event_type".to_string(), Value::Str(k.clone()));
            rec.insert("count".to_string(), Value::Int(*v));
            Value::Record(rec)
        })
        .collect();

    let mut rec = BTreeMap::new();
    rec.insert("total_events".to_string(), Value::Int(filtered_count));
    rec.insert("by_category".to_string(), Value::Array(categories));
    rec.insert("by_type".to_string(), Value::Array(types));
    rec.insert(
        "generated_at".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}

/// Get raw telemetry events.
/// Usage: telemetry.events() or telemetry.events(limit)
fn bi_telemetry_events(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let limit = match args.first() {
        Some(Value::Int(n)) => *n as usize,
        _ => 100,
    };
    let events = TELEMETRY_EVENTS.read().map_err(|_| {
        crate::safety::lock_poisoned("telemetry_events", "the telemetry event buffer")
    })?;
    let entries: Vec<Value> = events
        .iter()
        .rev()
        .take(limit)
        .map(|e| {
            let mut rec = BTreeMap::new();
            rec.insert("id".to_string(), Value::Str(e.id.clone()));
            rec.insert("event_type".to_string(), Value::Str(e.event_type.clone()));
            rec.insert("category".to_string(), Value::Str(e.category.clone()));
            rec.insert("timestamp".to_string(), Value::Str(e.timestamp.clone()));
            rec.insert("session_id".to_string(), Value::Str(e.session_id.clone()));
            if !e.data.is_empty() {
                let data_rec: BTreeMap<String, Value> = e
                    .data
                    .iter()
                    .map(|(k, v)| (k.clone(), Value::Str(v.clone())))
                    .collect();
                rec.insert("data".to_string(), Value::Record(data_rec));
            }
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(entries))
}

/// Reset (clear) all telemetry data.
/// Usage: telemetry.reset()
fn bi_telemetry_reset(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    if !args.is_empty() {
        return Err(crate::safety::bad_arg(
            "telemetry_reset",
            "no arguments",
            &format!("{} argument(s)", args.len()),
        ));
    }
    // Clears the in-process event buffer only. Nothing on disk is read or
    // removed, so the status says exactly that.
    let mut events = TELEMETRY_EVENTS.write().map_err(|_| {
        crate::safety::lock_poisoned("telemetry_reset", "the telemetry event buffer")
    })?;
    let count = events.len();
    events.clear();

    let mut rec = BTreeMap::new();
    rec.insert("cleared".to_string(), Value::Int(count as i64));
    rec.insert(
        "status".to_string(),
        Value::Str("in-process telemetry events cleared".to_string()),
    );
    rec.insert(
        "timestamp".to_string(),
        Value::Str(chrono::Local::now().to_rfc3339()),
    );
    Ok(Value::Record(rec))
}

// ═══════════════════════════════════════════════════════════════════════════
// CLI Tool Wrappers — New cross-platform implementations (965-987)
// ═══════════════════════════════════════════════════════════════════════════

/// wget_download — download one http(s) URL to a file in the workspace.
/// Usage: wget_download(url) or wget_download(url, output). Without an output,
/// the file is the last path segment of the URL. The transfer is curl, limited
/// to http and https for the first request and for every redirect, with at most
/// 5 redirects, a 1 GiB size limit and a 15 s connect limit; wget cannot limit
/// the schemes it follows, so it is not used. An existing output is refused, and
/// a failed transfer removes its partial file. Returns {url, output, size, status, tool}.
fn bi_wget_download(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    net_refuse_in_transaction("wget_download")?;
    k8s_no_input("wget_download", &input)?;
    if args.len() > 2 {
        return Err(crate::safety::arg_err(
            "wget_download takes a URL and an optional output path",
        ));
    }
    let url = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("wget requires a URL string")),
    };
    let parsed = url::Url::parse(&url).map_err(|e| {
        crate::safety::bad_arg("wget_download", "an absolute http(s) URL", &e.to_string())
    })?;
    if !matches!(parsed.scheme(), "http" | "https") {
        return Err(crate::safety::bad_arg(
            "wget_download",
            "an http or https URL",
            &format!("the scheme {}", parsed.scheme()),
        ));
    }
    guard_network("wget_download", &url)?;
    let output = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "wget_download",
                "an output path String",
                other.type_name(),
            ))
        }
        None => parsed
            .path_segments()
            .and_then(|segs| {
                segs.rev()
                    .find(|s| !s.is_empty() && *s != "." && *s != "..")
            })
            .map(str::to_string)
            .ok_or_else(|| {
                crate::safety::arg_err("wget_download: the URL names no file; pass an output path")
            })?,
    };
    crate::safety::reject_option_like("wget_download", std::slice::from_ref(&output))?;
    if output.trim().is_empty() || output.len() > 4096 || output.contains('\0') {
        return Err(crate::safety::arg_err(
            "wget_download: the output path must be 1 to 4096 bytes without NUL",
        ));
    }
    let output = guard_local_write("wget_download", &output)?;
    if std::path::Path::new(&output).exists() {
        return Err(crate::safety::arg_err(format!(
            "wget_download: `{output}` already exists; remove it or choose another output path"
        )));
    }
    let max = WGET_FILE_MAX.to_string();
    let report = format!("{WEB_HOP_MARK}%{{response_code}} %{{redirect_url}}");
    // Redirects are followed here, hop by hop, for the reason `web_curl`
    // gives: curl's own `-L` would take the request past the allowlist.
    let mut hop_url = url.clone();
    let mut hops = 0;
    let fetched = loop {
        let checked = match crate::security::check_http_url("wget_download", &hop_url) {
            Ok(checked) => checked,
            Err(e) => break Err(e),
        };
        let mut argv = vec![
            "-sS",
            "-f",
            "--proto",
            "=http,https",
            "--connect-timeout",
            "15",
            "--max-filesize",
            max.as_str(),
            "-o",
            output.as_str(),
            "-w",
            report.as_str(),
        ];
        let pin = checked.curl_resolve();
        if let Some(pin) = pin.as_deref() {
            argv.extend_from_slice(&["--resolve", pin]);
        }
        argv.push(hop_url.as_str());
        let run = match tool_run(
            "wget_download",
            "curl",
            None,
            &argv,
            Keep::Tail(TOOL_STDERR_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )
        .and_then(|run| finished("wget_download", run))
        {
            Ok(run) => run,
            Err(e) => break Err(e),
        };
        let mut stdout = run.stdout.into_bytes();
        let next = match web_take_hop(&mut stdout) {
            Some((code, next)) if (300..400).contains(&code) && !next.is_empty() => next,
            _ => break Ok(()),
        };
        hops += 1;
        if hops > 5 {
            break Err(crate::safety::budget_exceeded(
                "wget_download",
                "more than 5 redirects".to_string(),
                "request the final URL directly",
            ));
        }
        let next = match crate::safety::guard_redirect("wget_download", &hop_url, &next)
            .and_then(|_| web_http_url("wget_download", &next))
        {
            Ok(next) => next,
            Err(e) => break Err(e),
        };
        hop_url = next;
    };
    if let Err(e) = fetched {
        remove_partial(&output);
        return Err(e);
    }
    let size = std::fs::metadata(&output)
        .map_err(|e| crate::safety::fs_error("wget_download", &output, &e))?
        .len();
    let mut rec = BTreeMap::new();
    rec.insert("url".to_string(), Value::Str(url));
    rec.insert("output".to_string(), Value::Str(output));
    rec.insert("size".to_string(), Value::Int(size as i64));
    rec.insert("status".to_string(), Value::Str("downloaded".to_string()));
    rec.insert("tool".to_string(), Value::Str("curl".to_string()));
    Ok(Value::Record(rec))
}

/// An age recipient: an age1… key or an ssh- public key, and no other text.
fn age_recipient_ok(recipient: &str) -> bool {
    (recipient.starts_with("age1") || recipient.starts_with("ssh-"))
        && recipient.len() <= 1024
        && recipient.chars().all(|c| {
            c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_' | '+' | '/' | '=' | '.' | '@')
        })
}

/// age — Encrypt a file to one recipient (an age1… or ssh- public key).
/// Usage: age_encrypt(input_file, output_file, recipient). The output is
/// required, and is the second argument because the recipient is the third. An
/// existing output is refused, and a failed run removes its partial file.
fn bi_age_encrypt(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("age_encrypt", &input)?;
    let input_file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "age_encrypt requires input_file, output_file, recipient",
            ))
        }
    };
    let output_file = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "age_encrypt requires an output_file as its second argument",
            ))
        }
    };
    let recipient = match args.get(2) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "age_encrypt requires a recipient (an age1… or ssh- public key)",
            ))
        }
    };
    if !age_recipient_ok(&recipient) {
        return Err(crate::safety::bad_arg(
            "age_encrypt",
            "recipient: an age1… or ssh- public key",
            &recipient,
        ));
    }
    refuse_option("age_encrypt", &input_file)?;
    let input_file = crate::safety::resolve_path_str(&input_file);
    regular_file_arg("age_encrypt", &input_file)?;
    let output_file = guard_local_write(
        "age_encrypt",
        &crate::safety::resolve_path_str(&output_file),
    )?;
    refuse_existing("age_encrypt", &output_file)?;
    journal_new_file("age_encrypt", &output_file);
    let mut cmd = crate::safety::child_command("age");
    cmd.args([
        "-r",
        recipient.as_str(),
        "-o",
        output_file.as_str(),
        input_file.as_str(),
    ]);
    if let Err(e) = run_checked("age_encrypt", "age", cmd, LOCAL_DEADLINE_SECS) {
        return Err(fail_removing_partial(e, &output_file));
    }
    let mut rec = BTreeMap::new();
    rec.insert("input".to_string(), Value::Str(input_file));
    rec.insert("output".to_string(), Value::Str(output_file));
    rec.insert("recipient".to_string(), Value::Str(recipient));
    rec.insert("status".to_string(), Value::Str("encrypted".to_string()));
    Ok(Value::Record(rec))
}

/// age — Decrypt a file with an identity file.
/// Usage: age_decrypt(input_file, output_file?, identity_file?). Without an
/// output the input must end in .age. The output is refused if it exists.
fn bi_age_decrypt(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("age_decrypt", &input)?;
    let input_file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("age_decrypt requires input_file")),
    };
    refuse_option("age_decrypt", &input_file)?;
    let output_file = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => match input_file.strip_suffix(".age") {
            Some(stem) => stem.to_string(),
            None => {
                return Err(crate::safety::bad_arg(
                    "age_decrypt",
                    "an input ending in .age, or an output_file",
                    &input_file,
                ))
            }
        },
    };
    let identity = match args.get(2) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            let home = std::env::var("HOME")
                .or_else(|_| std::env::var("USERPROFILE"))
                .unwrap_or_default();
            format!("{}/.age/key.txt", home)
        }
    };
    refuse_option("age_decrypt", &identity)?;
    if output_file == input_file {
        return Err(crate::safety::bad_arg(
            "age_decrypt",
            "an output_file other than the input",
            &output_file,
        ));
    }
    let input_file = crate::safety::resolve_path_str(&input_file);
    regular_file_arg("age_decrypt", &input_file)?;
    let identity = crate::safety::resolve_path_str(&identity);
    regular_file_arg("age_decrypt", &identity)?;
    let output_file = guard_local_write(
        "age_decrypt",
        &crate::safety::resolve_path_str(&output_file),
    )?;
    refuse_existing("age_decrypt", &output_file)?;
    journal_new_file("age_decrypt", &output_file);
    let mut cmd = crate::safety::child_command("age");
    cmd.args([
        "-d",
        "-i",
        identity.as_str(),
        "-o",
        output_file.as_str(),
        input_file.as_str(),
    ]);
    if let Err(e) = run_checked("age_decrypt", "age", cmd, LOCAL_DEADLINE_SECS) {
        return Err(fail_removing_partial(e, &output_file));
    }
    let mut rec = BTreeMap::new();
    rec.insert("input".to_string(), Value::Str(input_file));
    rec.insert("output".to_string(), Value::Str(output_file));
    rec.insert("status".to_string(), Value::Str("decrypted".to_string()));
    Ok(Value::Record(rec))
}

/// age — Generate an age identity into a new file and return its public key.
/// Usage: age_keygen(output_file). The output file is required: the private key
/// is written there and is never returned, so it cannot land in a transcript.
/// An existing file is refused.
fn bi_age_keygen(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("age_keygen", &input)?;
    let output_file = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "age_keygen requires an output_file: the private key is written there and never returned",
            ))
        }
    };
    refuse_option("age_keygen", &output_file)?;
    let output_file =
        guard_local_write("age_keygen", &crate::safety::resolve_path_str(&output_file))?;
    refuse_existing("age_keygen", &output_file)?;
    journal_new_file("age_keygen", &output_file);
    let mut cmd = crate::safety::child_command("age-keygen");
    cmd.args(["-o", output_file.as_str()]);
    // With -o, age-keygen writes the identity to the file and prints the public
    // key on stderr. Its stdout is discarded, so the identity cannot be returned.
    let (_, stderr) = match run_checked("age_keygen", "age-keygen", cmd, LOCAL_DEADLINE_SECS) {
        Ok(done) => done,
        Err(e) => return Err(fail_removing_partial(e, &output_file)),
    };
    let public_key = stderr
        .lines()
        .find_map(|l| l.strip_prefix("Public key:"))
        .map(|k| k.trim().to_string())
        .filter(|k| !k.is_empty());
    let Some(public_key) = public_key else {
        return Err(fail_removing_partial(
            crate::safety::tool_failed("age_keygen", "age-keygen", Some(0), &stderr),
            &output_file,
        ));
    };
    let mut rec = BTreeMap::new();
    rec.insert("public_key".to_string(), Value::Str(public_key));
    rec.insert("identity_file".to_string(), Value::Str(output_file));
    rec.insert("status".to_string(), Value::Str("generated".to_string()));
    Ok(Value::Record(rec))
}

/// ripgrep (rg) — Fast regex-based code search.
/// Usage: rg(pattern) or rg(pattern, path) or rg(pattern, path, flags_record)
/// Runs `rg --json --regexp=PATTERN PATH` with no shell. Exit 1 is "no matches"; any other
/// nonzero exit is E_TOOL_FAILED. A missing rg is E_TOOL_MISSING (no native fallback: a
/// different matcher would answer a different question). Over 1000 matches is E_BUDGET_EXCEEDED.
fn bi_rg_search(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "rg_search";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    let pattern = k8s_need(B, "a search pattern", &args, 0, search_text_check)?;
    let path = pkg_path_arg(B, &args, 1, ".")?;
    let ignore_case =
        match devtool_options(B, &args, 2, &["ignore_case"])?.and_then(|o| o.get("ignore_case")) {
            None => false,
            Some(Value::Bool(b)) => *b,
            Some(other) => {
                return Err(crate::safety::arg_err(format!(
                    "{B}: ignore_case must be a Bool, got {}",
                    other.type_name()
                )))
            }
        };
    let regexp = format!("--regexp={pattern}");
    let mut argv = vec!["--json"];
    if ignore_case {
        argv.push("-i");
    }
    argv.push(regexp.as_str());
    argv.push(path.as_str());
    let run = tool_run(
        B,
        "rg",
        None,
        &argv,
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    let command = run.command.clone();
    let text = stdout_with_exit1(B, run)?;
    let mut matches = Vec::new();
    for line in text.lines().filter(|l| !l.is_empty()) {
        let parsed = serde_json::from_str::<serde_json::Value>(line).map_err(|e| {
            crate::safety::tool_failed(
                B,
                &command,
                Some(0),
                &format!("printed a line that is not JSON ({e})"),
            )
        })?;
        if parsed.get("type").and_then(|t| t.as_str()) != Some("match") {
            continue;
        }
        let Some(data) = parsed.get("data") else {
            continue;
        };
        if matches.len() >= SEARCH_MAX_RESULTS {
            return Err(search_budget(B));
        }
        let mut rec = BTreeMap::new();
        if let Some(p) = data
            .get("path")
            .and_then(|p| p.get("text"))
            .and_then(|t| t.as_str())
        {
            rec.insert("file".to_string(), Value::Str(p.to_string()));
        }
        if let Some(n) = data.get("line_number").and_then(|n| n.as_i64()) {
            rec.insert("line".to_string(), Value::Int(n));
        }
        if let Some(t) = data
            .get("lines")
            .and_then(|l| l.get("text"))
            .and_then(|t| t.as_str())
        {
            rec.insert("text".to_string(), Value::Str(t.trim_end().to_string()));
        }
        matches.push(Value::Record(rec));
    }
    Ok(Value::Array(matches))
}

/// fd — Fast, user-friendly file finder.
/// Usage: fd(pattern) or fd(pattern, path) or fd(pattern, path, {type?, extension?})
/// Runs `fd` with the pattern after `--`, so a leading '-' is never a flag. A missing fd is
/// E_TOOL_MISSING; there is no native fallback, since find's glob is not fd's regex.
fn bi_fd_find(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "fd_find";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 3)?;
    let pattern = k8s_need(B, "a search pattern", &args, 0, search_text_check)?;
    let path = pkg_path_arg(B, &args, 1, ".")?;
    let options = devtool_options(B, &args, 2, &["type", "extension"])?;
    let kind = devtool_opt_str(B, "type", options, "type", fd_kind_check)?;
    let extension = devtool_opt_str(B, "extension", options, "extension", fd_ext_check)?;
    let mut argv: Vec<&str> = Vec::new();
    if let Some(kind) = kind.as_deref() {
        argv.extend(["--type", kind]);
    }
    if let Some(extension) = extension.as_deref() {
        argv.extend(["--extension", extension]);
    }
    // fd's pattern is positional: `--` keeps a pattern that begins with '-' from
    // being read as a flag.
    argv.extend(["--", pattern.as_str(), path.as_str()]);
    let run = tool_run(
        B,
        "fd",
        None,
        &argv,
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let text = tool_text(B, run)?;
    search_list(
        B,
        text.lines()
            .filter(|l| !l.is_empty())
            .map(str::to_string)
            .collect(),
    )
}

/// sed — Stream editor for text substitution (cross-platform, native Rust).
/// Usage: sed(pattern, replacement, input_text) or sed(pattern, replacement, input_text, {global?, file?})
fn bi_sed_replace(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let mut args = args.into_iter();
    let Some(Value::Str(pattern)) = args.next() else {
        return Err(crate::safety::arg_err("sed requires pattern String"));
    };
    let Some(Value::Str(replacement)) = args.next() else {
        return Err(crate::safety::arg_err("sed requires replacement String"));
    };
    let (text, options) = match input {
        Some(Value::Str(text)) => {
            let options = args.next();
            if args.next().is_some() {
                return Err(crate::safety::arg_err(
                    "piped sed accepts pattern, replacement and optional options only",
                ));
            }
            (text, options)
        }
        Some(_) => return Err(crate::safety::arg_err("sed piped input must be String")),
        None => {
            let Some(Value::Str(text)) = args.next() else {
                return Err(crate::safety::arg_err(
                    "sed requires text or file path String",
                ));
            };
            (text, args.next())
        }
    };
    let (mut global, mut file_mode) = (true, false);
    if let Some(options) = options {
        let Value::Record(record) = options else {
            return Err(crate::safety::arg_err("sed options must be Record"));
        };
        for (key, value) in record {
            let slot = match key.as_str() {
                "global" => &mut global,
                "file" => &mut file_mode,
                _ => return Err(crate::safety::arg_err(format!("sed unknown option {key}"))),
            };
            let Value::Bool(flag) = value else {
                return Err(crate::safety::arg_err(format!("sed {key} must be Bool")));
            };
            *slot = flag;
        }
    }
    // In file mode an empty pattern matches at every position and rewrites the
    // whole file; refused before the file is read.
    if file_mode {
        refuse_empty_find("sed", &pattern)?;
    }
    let re = regex::Regex::new(&pattern)
        .map_err(|e| crate::safety::arg_err(format!("sed invalid regex: {e}")))?;
    if file_mode {
        refuse_empty_matching_regex("sed", &pattern, &re)?;
    }
    let file = if file_mode {
        Some((text.clone(), crate::safety::resolve_path_str(&text)))
    } else {
        None
    };
    let source = if let Some((_, path)) = &file {
        crate::safety::guard(crate::safety::GuardCtx {
            builtin: "sed_replace",
            effect: crate::safety::Effect::WriteLocal,
            what: "replace file text",
            targets: vec![path.clone()],
            blast_radius: serde_json::json!({"files":1}),
            reversible: true,
            fs_paths: true,
        })?;
        line_read("sed", path)?
    } else {
        text
    };
    let before = file.as_ref().map(|_| source.clone());
    let result = regex_substitute(&re, &replacement, source, global);
    if let Some((original, path)) = file {
        // The pattern matched nothing, or only text it replaced with itself: the
        // file is left as it is, unwritten and unjournalled.
        let status = if before.as_deref() == Some(result.as_str()) {
            "unchanged"
        } else {
            crate::tx::snapshot(&path);
            write_file_atomically("sed", &path, result.as_bytes())?;
            "modified"
        };
        Ok(Value::Record(BTreeMap::from([
            ("file".into(), Value::Str(original)),
            ("status".into(), Value::Str(status.into())),
        ])))
    } else {
        Ok(Value::Str(result))
    }
}

/// awk — bounded in-process awk subset (see src/awk.rs for the grammar and limits).
/// Usage: awk(program, input_text, options?) or piped: text | awk(program, options?)
/// Options: {fs: String} sets the initial field separator (default one space).
#[path = "awk.rs"]
mod awk;

fn bi_awk_process(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let mut args = args.into_iter();
    let program = match args.next() {
        Some(Value::Str(s)) => s,
        _ => return Err(crate::safety::arg_err("awk requires a program String")),
    };
    let (text, options) = match input {
        Some(Value::Str(text)) => {
            let options = args.next();
            if args.next().is_some() {
                return Err(crate::safety::arg_err(
                    "piped awk accepts program and optional options only",
                ));
            }
            (text, options)
        }
        Some(_) => return Err(crate::safety::arg_err("awk piped input must be String")),
        None => {
            let Some(Value::Str(text)) = args.next() else {
                return Err(crate::safety::arg_err("awk requires input String"));
            };
            (text, args.next())
        }
    };
    let mut separator = " ".to_string();
    if let Some(options) = options {
        let Value::Record(record) = options else {
            return Err(crate::safety::arg_err("awk options must be Record"));
        };
        for (key, value) in record {
            if key != "fs" {
                return Err(crate::safety::arg_err(format!("awk unknown option {key}")));
            }
            let Value::Str(value) = value else {
                return Err(crate::safety::arg_err("awk fs must be String"));
            };
            separator = value;
        }
    }
    let lines = awk::run(&program, &text, &separator)?;
    Ok(Value::Array(lines.into_iter().map(Value::Str).collect()))
}

/// cut — Extract columns/fields from text (cross-platform, native Rust).
/// Usage: cut(delimiter, fields, input_text) or piped: text | cut(delimiter, fields)
/// fields is a string like "1,3" or "1-3" (1-based)
fn bi_cut_columns(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if input.is_some() && args.len() > 2 {
        return Err(crate::safety::arg_err(
            "piped cut accepts delimiter and fields only",
        ));
    }
    let delimiter = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "cut requires delimiter, fields, and input",
            ))
        }
    };
    let fields_spec = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        Some(Value::Int(n)) => n.to_string(),
        _ => {
            return Err(crate::safety::arg_err(
                "cut requires a fields specification (e.g., '1,3' or '1-3')",
            ))
        }
    };
    let text = match args.get(2) {
        Some(Value::Str(s)) => s.clone(),
        None => match &input {
            Some(Value::Str(s)) => s.clone(),
            _ => return Err(crate::safety::arg_err("cut requires input text")),
        },
        _ => return Err(crate::safety::arg_err("cut input must be a string")),
    };
    // Parse field spec: "1,3,5" or "1-3" or "2"
    let field_indices = parse_field_spec(&fields_spec)?;
    let mut results = Vec::new();
    for line in text.lines() {
        let cols: Vec<&str> = line.split(&delimiter).collect();
        let selected: Vec<&str> = field_indices
            .iter()
            .filter_map(|&i| cols.get(i - 1).copied())
            .collect();
        results.push(Value::Str(selected.join(&delimiter)));
    }
    Ok(Value::Array(results))
}

/// Parse a field specification like "1,3,5" or "1-3" into a Vec of 1-based indices.
fn parse_field_spec(spec: &str) -> Result<Vec<usize>> {
    const MAX_FIELDS: usize = 10000;
    let invalid = || {
        crate::safety::arg_err("cut fields must be positive integers or ascending inclusive ranges, separated by commas")
    };
    let parse = |part: &str| -> Result<usize> {
        if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
            return Err(invalid());
        }
        let n = part.parse::<usize>().map_err(|_| invalid())?;
        if n == 0 {
            return Err(invalid());
        }
        Ok(n)
    };
    let mut indices = Vec::new();
    for part in spec.split(',') {
        let part = part.trim();
        let (start, end) = if let Some((left, right)) = part.split_once('-') {
            (parse(left)?, parse(right)?)
        } else {
            let n = parse(part)?;
            (n, n)
        };
        if start > end {
            return Err(invalid());
        }
        let length = end - start + 1;
        if length > MAX_FIELDS - indices.len() {
            return Err(crate::safety::budget_exceeded(
                "cut",
                "field selection exceeds 10000 entries".into(),
                "select fewer fields",
            ));
        }
        indices.extend(start..=end);
    }
    Ok(indices)
}

/// xargs — Run one program once per item, with the item as its last argument.
/// Usage: xargs_exec(command, items) or items | xargs_exec(command). items is an
/// Array of scalars, or a String read as lines. The command is split on whitespace
/// and run directly, with no shell; its program may not begin with '-', and no
/// item may either. At most 256 items, each run has a 120 s deadline, and the call
/// as a whole 600 s. Returns one Record per item: {item, exit_code, stdout, stderr}.
/// A nonzero exit is that item's exit code, which is data here.
fn bi_xargs_exec(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_max_args("xargs_exec", &args, 2)?;
    let command = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("xargs requires a command string")),
    };
    let items = match (args.get(1), &input) {
        (Some(_), Some(_)) => {
            return Err(crate::safety::arg_err(
                "xargs_exec takes its items either as an argument or piped in, not both",
            ))
        }
        (Some(v), None) | (None, Some(v)) => xargs_items("xargs_exec", v)?,
        (None, None) => return Err(crate::safety::arg_err("xargs requires input items")),
    };
    let words = argv_words("xargs_exec", &command)?;
    crate::safety::guard_exec("xargs", &command)?;
    let started = std::time::Instant::now();
    let mut results = Vec::with_capacity(items.len());
    for item in &items {
        if started.elapsed() > std::time::Duration::from_secs(XARGS_TOTAL_SECS) {
            return Err(crate::safety::budget_exceeded(
                "xargs_exec",
                format!(
                    "the items took more than {XARGS_TOTAL_SECS} s; {} of {} ran",
                    results.len(),
                    items.len()
                ),
                "run the remaining items in a separate call",
            ));
        }
        let mut argv: Vec<&str> = words.iter().skip(1).map(String::as_str).collect();
        argv.push(item.as_str());
        let run = tool_run_stderr(
            "xargs_exec",
            &words[0],
            None,
            &argv,
            Keep::Tail(XARGS_ITEM_OUT),
            XARGS_ITEM_OUT,
            TOOL_DEADLINE_SECS,
        )?;
        let mut rec = BTreeMap::new();
        rec.insert("item".to_string(), Value::Str(item.clone()));
        rec.insert("exit_code".to_string(), Value::Int(exit_code_of(&run)));
        rec.insert(
            "stdout".to_string(),
            Value::Str(run.stdout.trim().to_string()),
        );
        rec.insert("stderr".to_string(), Value::Str(run.stderr.clone()));
        results.push(Value::Record(rec));
    }
    Ok(Value::Array(results))
}

/// The JSON text a jq builtin reads: its second argument, or the piped string.
/// Text past JQ_INPUT_CAP is refused rather than parsed.
fn jq_json_arg(builtin: &str, args: &[Value], input: Option<Value>) -> Result<String> {
    let text = match (args.get(1), input) {
        (Some(Value::Str(s)), _) => s.clone(),
        (None, Some(Value::Str(s))) => s,
        (None, _) => {
            return Err(crate::safety::arg_err(format!(
                "{builtin} requires JSON input"
            )))
        }
        _ => {
            return Err(crate::safety::bad_arg(
                builtin,
                "JSON text: String",
                "a non-string",
            ))
        }
    };
    if text.len() > JQ_INPUT_CAP {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!(
                "JSON input is {} bytes; the limit is {JQ_INPUT_CAP}",
                text.len()
            ),
            "pass a smaller document",
        ));
    }
    Ok(text)
}

/// jq — Query and transform JSON data (cross-platform, native Rust).
/// Usage: jq(expression, json_string) or piped: json_str | jq(expression)
/// Evaluates the subset that eval_jq_expr documents. Anything else is refused,
/// never answered with a guess.
fn bi_jq_query(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let expr = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("jq requires a query expression")),
    };
    let json_str = jq_json_arg("jq", &args, input)?;
    let parsed: serde_json::Value = serde_json::from_str(&json_str)
        .map_err(|e| crate::safety::bad_arg("jq", "valid JSON input", &e.to_string()))?;
    let result = eval_jq_expr(&expr, &parsed)?;
    Ok(json_to_value(result))
}

/// jq filter — Apply a real jq filter to JSON, with the jq binary.
/// Usage: jq_filter(filter, json_string) or piped: json_str | jq_filter(filter)
/// A filter that begins with '-' is refused: jq would read it as an option.
/// With no jq on PATH this is E_TOOL_MISSING. It does not fall back to the native subset.
fn bi_jq_filter(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let filter = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "jq_filter requires a filter expression",
            ))
        }
    };
    refuse_option("jq_filter", &filter)?;
    let json_str = jq_json_arg("jq_filter", &args, input)?;
    let mut cmd = crate::safety::child_command("jq");
    cmd.arg(filter.as_str());
    let out = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
    let (status, stderr) = run_tool(
        "jq_filter",
        "jq",
        cmd,
        Some(json_str.into_bytes()),
        std::sync::Arc::clone(&out),
        LOCAL_DEADLINE_SECS,
        TOOL_OUTPUT_CAP,
    )?;
    tool_ok("jq_filter", "jq", status, &stderr)?;
    let bytes = std::mem::take(
        &mut *out
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner),
    );
    let stdout = String::from_utf8_lossy(&bytes).trim().to_string();
    match serde_json::from_str::<serde_json::Value>(&stdout) {
        Ok(parsed) => Ok(json_to_value(parsed)),
        Err(_) => Ok(Value::Str(stdout)),
    }
}

/// Native jq expression evaluator. Supports `.`, `.key`, `.key.sub`, `.[n]`,
/// `.[]` (returns the elements as an array), `keys`, `length` and `|` between
/// them. `length` follows jq: the absolute value of a number, and an error for a
/// boolean. Anything else, and any index that does not fit, is refused.
fn eval_jq_expr(expr: &str, data: &serde_json::Value) -> Result<serde_json::Value> {
    let expr = expr.trim();
    let unsupported = || {
        crate::safety::bad_arg(
            "jq",
            "an expression of . .key .key.sub .[n] .[] keys length, joined by |",
            expr,
        )
    };
    if expr == "." {
        return Ok(data.clone());
    }
    if expr == "keys" {
        if let serde_json::Value::Object(m) = data {
            return Ok(serde_json::Value::Array(
                m.keys()
                    .map(|k| serde_json::Value::String(k.clone()))
                    .collect(),
            ));
        }
        return Err(crate::safety::arg_err("keys requires an object"));
    }
    if expr == "length" {
        return match data {
            serde_json::Value::Null => Ok(serde_json::json!(0)),
            serde_json::Value::Bool(_) => Err(crate::safety::bad_arg(
                "jq",
                "a value with a length (null, number, string, array or object)",
                "a boolean",
            )),
            serde_json::Value::Number(n) => Ok(match n.as_i64() {
                Some(i) => serde_json::json!(i.unsigned_abs()),
                None => serde_json::json!(n.as_f64().map_or(0.0, f64::abs)),
            }),
            // jq counts code points, not bytes.
            serde_json::Value::String(s) => Ok(serde_json::json!(s.chars().count())),
            serde_json::Value::Array(a) => Ok(serde_json::json!(a.len())),
            serde_json::Value::Object(m) => Ok(serde_json::json!(m.len())),
        };
    }
    if expr == ".[]" {
        if let serde_json::Value::Array(a) = data {
            return Ok(serde_json::Value::Array(a.clone()));
        }
        if let serde_json::Value::Object(m) = data {
            return Ok(serde_json::Value::Array(m.values().cloned().collect()));
        }
        return Err(crate::safety::bad_arg(
            "jq",
            "an array or object to iterate",
            "another value",
        ));
    }
    // Handle pipe: .key | .subkey
    if let Some(pipe_pos) = expr.find(" | ") {
        let left = &expr[..pipe_pos];
        let right = &expr[pipe_pos + 3..];
        let intermediate = eval_jq_expr(left, data)?;
        return eval_jq_expr(right, &intermediate);
    }
    // Dot-path: .key.subkey or .key
    if let Some(path) = expr.strip_prefix('.') {
        // Handle array index: .[0]
        if path.starts_with('[') && path.ends_with(']') {
            let idx_str = &path[1..path.len() - 1];
            let idx: usize = idx_str.parse().map_err(|_| {
                crate::safety::bad_arg("jq", "a numeric index in brackets", idx_str)
            })?;
            return match data {
                serde_json::Value::Array(a) => a.get(idx).cloned().ok_or_else(|| {
                    crate::safety::bad_arg(
                        "jq",
                        &format!("an index below {}", a.len()),
                        &idx.to_string(),
                    )
                }),
                _ => Err(crate::safety::bad_arg(
                    "jq",
                    "an array to index",
                    "a non-array",
                )),
            };
        }
        let mut current = data;
        for key in path.split('.') {
            if key.is_empty() {
                continue;
            }
            // Handle key[n] notation. A bracket that is not a number is refused,
            // not dropped.
            if let Some(bracket) = key.find('[').filter(|_| key.ends_with(']')) {
                let obj_key = &key[..bracket];
                let idx_str = &key[bracket + 1..key.len() - 1];
                if !obj_key.is_empty() {
                    current = current
                        .get(obj_key)
                        .ok_or_else(|| crate::safety::not_found("jq", "key", obj_key))?;
                }
                let idx: usize = idx_str.parse().map_err(|_| {
                    crate::safety::bad_arg("jq", "a numeric index in brackets", idx_str)
                })?;
                current = match current {
                    serde_json::Value::Array(a) => a.get(idx).ok_or_else(|| {
                        crate::safety::bad_arg(
                            "jq",
                            &format!("an index below {}", a.len()),
                            &idx.to_string(),
                        )
                    })?,
                    _ => {
                        return Err(crate::safety::bad_arg(
                            "jq",
                            "an array to index",
                            "a non-array",
                        ))
                    }
                };
            } else {
                current = current
                    .get(key)
                    .ok_or_else(|| crate::safety::not_found("jq", "key", key))?;
            }
        }
        return Ok(current.clone());
    }
    Err(unsupported())
}

/// yq — Query/transform YAML, TOML, XML data.
/// Usage: yq(expression, input_string) or piped input.
/// Runs `yq EXPRESSION FILE`, where FILE holds the document (a temporary file, since the
/// runner gives a child no stdin). A missing yq is E_TOOL_MISSING; nothing is parsed natively.
fn bi_yq_query(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "yq_query";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let expr = k8s_need(B, "an expression", &args, 0, pkg_plain)?;
    let document = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{B}: the document must be a String, got {}",
                other.type_name()
            )))
        }
        None => {
            return Err(crate::safety::arg_err(format!(
                "{B} requires the document text"
            )))
        }
    };
    if document.len() > TOOL_MAX_TEXT {
        return Err(crate::safety::budget_exceeded(
            B,
            format!("the document is larger than {TOOL_MAX_TEXT} bytes"),
            "pass a smaller document",
        ));
    }
    // yq reads its document from a file here, because the runner gives a child
    // no stdin. The file lives in a directory of its own, removed afterwards.
    let file = scratch_file(B, "document.yaml", document.as_bytes())?;
    let path = file.display().to_string();
    let run = tool_run(
        B,
        "yq",
        None,
        &[expr.as_str(), path.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    );
    scratch_remove(&file);
    let text = tool_text(B, run?)?;
    Ok(Value::Str(text.trim().to_string()))
}

/// pager/less — Display text with pagination (cross-platform).
/// Usage: less(text) or less(file_path, {file: true})
fn bi_pager(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let mut args = args.into_iter();
    let (text, options) = match input {
        Some(Value::Str(text)) => {
            let options = args.next();
            if args.next().is_some() {
                return Err(crate::safety::arg_err(
                    "piped pager accepts optional options only",
                ));
            }
            (text, options)
        }
        Some(_) => return Err(crate::safety::arg_err("pager piped input must be String")),
        None => {
            let Some(Value::Str(text)) = args.next() else {
                return Err(crate::safety::arg_err(
                    "pager requires text or file path String",
                ));
            };
            (text, args.next())
        }
    };
    let mut file = false;
    if let Some(options) = options {
        let Value::Record(record) = options else {
            return Err(crate::safety::arg_err("pager options must be Record"));
        };
        for (key, value) in record {
            if key != "file" {
                return Err(crate::safety::arg_err(format!(
                    "pager unknown option {key}"
                )));
            }
            let Value::Bool(flag) = value else {
                return Err(crate::safety::arg_err("pager file must be Bool"));
            };
            file = flag;
        }
    }
    let content = if file {
        let path = crate::safety::resolve_path_str(&text);
        crate::safety::guard(crate::safety::GuardCtx {
            builtin: "pager",
            effect: crate::safety::Effect::ReadLocal,
            what: "read paged file text",
            targets: vec![path.clone()],
            blast_radius: serde_json::json!({"files":1}),
            reversible: true,
            fs_paths: true,
        })?;
        line_read("pager", &path)?
    } else {
        text
    };
    const PAGE_SIZE: usize = 40;
    let mut lines = content.lines();
    let first: Vec<_> = lines.by_ref().take(PAGE_SIZE).collect();
    let total = first.len() + lines.count();
    if total <= PAGE_SIZE {
        return Ok(Value::Str(content));
    }
    Ok(Value::Record(BTreeMap::from([
        ("content".into(), Value::Str(first.join("\n"))),
        ("total_lines".into(), Value::Int(total as i64)),
        ("page_size".into(), Value::Int(PAGE_SIZE as i64)),
        ("pages".into(), Value::Int(total.div_ceil(PAGE_SIZE) as i64)),
        (
            "hint".into(),
            Value::Str("Use head/tail for specific line ranges".into()),
        ),
    ])))
}

/// The one option tee takes, in the two call forms, for the errors that refuse
/// any other.
const TEE_OPTIONS_HINT: &str = "tee takes one option, append (a Bool): tee(path, data, {append: true}), or piped: data | tee(path, {append: true})";

/// tee — Write input to both a file and return it (cross-platform, native Rust).
/// Usage: tee(file_path, text) or piped: text | tee(file_path)
fn bi_tee_output(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let path = crate::safety::resolve_path_str(&expect_string(
        "tee",
        args.first()
            .ok_or_else(|| crate::safety::arg_err("tee requires path"))?,
    )?);
    let (value, options) = match input {
        Some(value) => {
            if args.len() > 2 {
                return Err(crate::safety::arg_err(
                    "piped tee accepts path and optional options only",
                ));
            }
            (value, args.get(1))
        }
        None => (
            args.get(1)
                .cloned()
                .ok_or_else(|| crate::safety::arg_err("tee requires data"))?,
            args.get(2),
        ),
    };
    let mut append = false;
    if let Some(options) = options {
        let Value::Record(record) = options else {
            return Err(crate::safety::bad_arg_in(
                "tee",
                "tee options must be Record",
                TEE_OPTIONS_HINT,
            ));
        };
        for (key, value) in record {
            if key != "append" {
                return Err(crate::safety::bad_arg_in(
                    "tee",
                    format!("tee unknown option {key}"),
                    TEE_OPTIONS_HINT,
                ));
            }
            let Value::Bool(flag) = value else {
                return Err(crate::safety::arg_err("tee append must be Bool"));
            };
            append = *flag;
        }
    }
    // Plain text, never the coloured terminal rendering: the file is data.
    let text = match value {
        Value::Str(text) => text,
        other => other.to_display_string(),
    };
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "tee_output",
        effect: crate::safety::Effect::WriteLocal,
        what: if append { "append" } else { "write" },
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({"bytes":text.len()}),
        reversible: true,
        fs_paths: true,
    })?;
    crate::tx::snapshot(&path);
    if append {
        use std::io::Write;
        crate::safety::refuse_hard_linked_write("tee", &path)?;
        let mut file = crate::safety::open_in_place("tee", std::path::Path::new(&path), true)
            .map_err(|e| crate::safety::in_place_error("tee", &path, e))?;
        file.write_all(text.as_bytes())
            .map_err(|e| crate::safety::fs_error("tee", &path, &e))?;
    } else {
        write_file_atomically("tee", &path, text.as_bytes())?;
    }
    Ok(Value::Str(text))
}

/// Longest tmux or screen session name.
const DEVTOOL_MAX_NAME: usize = 64;
/// Longest tmux target: a session, or session:window.pane.
const DEVTOOL_MAX_TARGET: usize = 256;
/// Longest key text sent to a session in one call.
const DEVTOOL_MAX_KEYS: usize = 4096;
/// Longest single argument passed through to a dev tool.
const DEVTOOL_MAX_ARG: usize = 4096;
/// Most items in any list an options Record or a call takes (cmake defines,
/// gdb commands, recipe arguments).
const DEVTOOL_MAX_ITEMS: usize = 256;
/// Longest single gdb command line.
const DEVTOOL_MAX_GDB_LINE: usize = 512;
/// Most parallel jobs a build may ask for.
const DEVTOOL_MAX_JOBS: i64 = 1024;

/// The process's working directory, as a dev tool would inherit it.
fn devtool_cwd(builtin: &str) -> Result<std::path::PathBuf> {
    std::env::current_dir().map_err(|e| crate::safety::fs_error(builtin, ".", &e))
}

/// A directory a dev tool runs in: `value` (default: the process's directory)
/// resolved against the process's directory, required to lie inside the
/// workspace, and required to exist as a directory.
fn devtool_dir(builtin: &str, value: Option<&str>) -> Result<std::path::PathBuf> {
    let cwd = devtool_cwd(builtin)?;
    let dir = workspace_path(builtin, value.unwrap_or("."), &cwd)?;
    if !dir.is_dir() {
        return Err(crate::safety::not_found(
            builtin,
            "directory",
            &dir.display().to_string(),
        ));
    }
    Ok(dir)
}

/// The options Record at `index`, when one is given. Only the keys in
/// `allowed` are accepted; any other key is refused by name, so no option is
/// silently ignored.
fn devtool_options<'a>(
    builtin: &str,
    args: &'a [Value],
    index: usize,
    allowed: &[&str],
) -> Result<Option<&'a BTreeMap<String, Value>>> {
    match args.get(index) {
        None => Ok(None),
        Some(Value::Record(map)) => {
            if let Some(key) = map.keys().find(|k| !allowed.contains(&k.as_str())) {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: unknown option '{key}'; the options are {}",
                    allowed.join(", ")
                )));
            }
            Ok(Some(map))
        }
        Some(other) => Err(crate::safety::arg_err(format!(
            "{builtin}: options must be a Record, got {}",
            other.type_name()
        ))),
    }
}

/// A String option, checked, when it is present.
fn devtool_opt_str(
    builtin: &str,
    what: &str,
    options: Option<&BTreeMap<String, Value>>,
    key: &str,
    check: K8sCheck,
) -> Result<Option<String>> {
    match options.and_then(|o| o.get(key)) {
        None => Ok(None),
        Some(Value::Str(s)) => check(builtin, what, s).map(Some),
        Some(other) => Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be a String, got {}",
            other.type_name()
        ))),
    }
}

/// An Int option, range-checked, when it is present.
fn devtool_opt_int(
    builtin: &str,
    what: &str,
    options: Option<&BTreeMap<String, Value>>,
    key: &str,
    lo: i64,
    hi: i64,
) -> Result<Option<i64>> {
    match options.and_then(|o| o.get(key)) {
        None => Ok(None),
        Some(Value::Int(n)) if (lo..=hi).contains(n) => Ok(Some(*n)),
        Some(Value::Int(n)) => Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be {lo}..={hi}, got {n}"
        ))),
        Some(other) => Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be an Int, got {}",
            other.type_name()
        ))),
    }
}

/// A tmux or screen session name: 1-64 letters, digits, '-' or '_'. Colons and
/// dots are refused because tmux reads them as target separators, and a
/// leading '-' is refused as an option.
fn devtool_session(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    let well_formed = !value.is_empty()
        && value.len() <= DEVTOOL_MAX_NAME
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if !well_formed {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is 1-{DEVTOOL_MAX_NAME} letters, digits, '-' or '_' (got {value:?})"
        )));
    }
    Ok(value.to_string())
}

/// A tmux target: a session, or session:window.pane. One word, not option-like.
fn devtool_target(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    let well_formed = !value.is_empty()
        && value.len() <= DEVTOOL_MAX_TARGET
        && !value.chars().any(|c| c.is_whitespace() || c.is_control());
    if !well_formed {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is one word of at most {DEVTOOL_MAX_TARGET} characters (got {value:?})"
        )));
    }
    Ok(value.to_string())
}

/// Keys typed into a session: one line, no control characters (each newline
/// would be a second command), not option-like.
fn devtool_keys(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    if value.is_empty() || value.len() > DEVTOOL_MAX_KEYS || value.chars().any(char::is_control) {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is one line of 1-{DEVTOOL_MAX_KEYS} bytes with no control characters"
        )));
    }
    Ok(value.to_string())
}

/// A tool-and-version spec such as `node@20`: one word, not option-like.
fn devtool_tool_spec(builtin: &str, what: &str, value: &str) -> Result<String> {
    if value.chars().any(char::is_whitespace) {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is one word such as node@20 (got {value:?})"
        )));
    }
    tf_plain(builtin, what, value)
}

/// A string argument that goes to a tool as data: no NUL byte.
fn devtool_text_arg(builtin: &str, what: &str, value: &str) -> Result<String> {
    if value.contains('\0') {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must not contain a NUL byte"
        )));
    }
    Ok(value.to_string())
}

/// A word passed to a dev tool as one recipe or program argument. A leading
/// '-' is refused, because the tool would read it as an option.
fn devtool_word(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    if value.len() > DEVTOOL_MAX_ARG || value.contains('\0') {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is at most {DEVTOOL_MAX_ARG} bytes with no NUL byte"
        )));
    }
    Ok(value.to_string())
}

/// A gdb command script, one command per line. Each line becomes one `-ex`
/// argument. gdb can run shell commands, so the call is approval-gated as an
/// exec by the central gate.
fn devtool_gdb_commands(builtin: &str, text: &str) -> Result<Vec<String>> {
    let lines: Vec<String> = text
        .lines()
        .map(|l| l.trim().to_string())
        .filter(|l| !l.is_empty())
        .collect();
    if lines.is_empty() {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: commands must contain at least one gdb command"
        )));
    }
    if lines.len() > DEVTOOL_MAX_ITEMS {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: at most {DEVTOOL_MAX_ITEMS} gdb commands, got {}",
            lines.len()
        )));
    }
    if let Some(long) = lines.iter().find(|l| l.len() > DEVTOOL_MAX_GDB_LINE) {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: a gdb command is at most {DEVTOOL_MAX_GDB_LINE} bytes, got {}",
            long.len()
        )));
    }
    Ok(lines)
}

/// `-Dname=value` for each define in a cmake defines Record. Names are letters,
/// digits and `_.-`; values are String, Int or Bool (ON/OFF).
fn devtool_defines(builtin: &str, value: &Value) -> Result<Vec<String>> {
    let defs = match value {
        Value::Record(map) => map,
        other => {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: defines must be a Record, got {}",
                other.type_name()
            )))
        }
    };
    if defs.len() > DEVTOOL_MAX_ITEMS {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: at most {DEVTOOL_MAX_ITEMS} defines, got {}",
            defs.len()
        )));
    }
    let mut out = Vec::with_capacity(defs.len());
    for (key, val) in defs {
        let well_formed = !key.is_empty()
            && key.len() <= 128
            && !key.starts_with('-')
            && key
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c));
        if !well_formed {
            return Err(crate::safety::arg_err(format!(
                "{builtin}: a define name is letters, digits and _.- and does not start with '-' (got {key:?})"
            )));
        }
        let text = match val {
            Value::Str(s) => s.clone(),
            Value::Int(n) => n.to_string(),
            Value::Bool(b) => (if *b { "ON" } else { "OFF" }).to_string(),
            other => {
                return Err(crate::safety::arg_err(format!(
                    "{builtin}: define {key} must be a String, Int or Bool, got {}",
                    other.type_name()
                )))
            }
        };
        devtool_text_arg(builtin, "a define value", &text)?;
        out.push(format!("-D{key}={text}"));
    }
    Ok(out)
}

/// A file read whole, at most `TOOL_MAX_TEXT` bytes. A larger file is refused
/// rather than read in part, and a missing one is E_NOT_FOUND.
fn devtool_read_text(builtin: &str, kind: &str, path: &str) -> Result<String> {
    use std::io::Read;
    let file = std::fs::File::open(path).map_err(|e| devtool_io(builtin, kind, path, &e))?;
    let mut bytes = Vec::new();
    file.take(TOOL_MAX_TEXT as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| devtool_io(builtin, kind, path, &e))?;
    if bytes.len() > TOOL_MAX_TEXT {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{path}` is larger than {TOOL_MAX_TEXT} bytes"),
            "point this at a smaller file",
        ));
    }
    Ok(String::from_utf8_lossy(&bytes).into_owned())
}

/// An I/O failure on a named file: NotFound is E_NOT_FOUND, anything else is
/// the file system's own coded error.
fn devtool_io(builtin: &str, kind: &str, path: &str, e: &std::io::Error) -> anyhow::Error {
    if e.kind() == std::io::ErrorKind::NotFound {
        crate::safety::not_found(builtin, kind, path)
    } else {
        crate::safety::fs_error(builtin, path, e)
    }
}

/// A finished call that must have succeeded. A nonzero exit is E_TOOL_FAILED
/// with the tail of its stderr.
fn finished(builtin: &str, run: ToolRun) -> Result<ToolRun> {
    if run.success {
        return Ok(run);
    }
    let tail = tail_text(&run.stderr, TOOL_STDERR_TAIL);
    Err(crate::safety::tool_failed(
        builtin,
        &run.command,
        run.code,
        &tail,
    ))
}

/// The last `max` bytes of `text`, cut on a character boundary.
fn tail_text(text: &str, max: usize) -> String {
    if text.len() <= max {
        return text.to_string();
    }
    let mut start = text.len() - max;
    while !text.is_char_boundary(start) {
        start += 1;
    }
    text[start..].to_string()
}

/// The fields every successful dev-tool record carries. The output keys are
/// named by the caller, because each builtin has always named them its own
/// way; `output_truncated` says when the stdout kept was only its tail.
fn run_fields(run: ToolRun, out_key: &str, err_key: &str) -> BTreeMap<String, Value> {
    let mut rec = BTreeMap::new();
    // No code means the process was killed by a signal (the deadline is
    // refused before this). It was `0`, which read as a clean exit.
    rec.insert(
        "exit_code".to_string(),
        match run.code {
            Some(code) => Value::Int(code as i64),
            None => Value::Null,
        },
    );
    rec.insert("success".to_string(), Value::Bool(run.success));
    if run.stdout_truncated {
        rec.insert("output_truncated".to_string(), Value::Bool(true));
    }
    rec.insert(out_key.to_string(), Value::Str(run.stdout));
    rec.insert(err_key.to_string(), Value::Str(run.stderr));
    rec
}

/// An interactive attach needs a terminal on both ends. Agent mode has no
/// human to attach, and without a terminal the attach could only hang or fail,
/// so both are refused as E_NO_UI before anything is spawned.
fn devtool_terminal(builtin: &str) -> Result<()> {
    crate::safety::refuse_if_headless(builtin)?;
    use std::io::IsTerminal;
    if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() {
        Ok(())
    } else {
        Err(crate::safety::no_ui(builtin))
    }
}

/// Run an attach with the terminal's streams inherited, so the user is the one
/// talking to the session. Only called after [`devtool_terminal`].
fn devtool_attach(builtin: &str, program: &str, args: &[&str], label: &str) -> Result<()> {
    let mut cmd = crate::safety::child_command(program);
    crate::safety::strip_ironshell_env(&mut cmd);
    let status = cmd
        .args(args)
        .status()
        .map_err(|e| crate::safety::spawn_error(builtin, program, &e))?;
    if status.success() {
        Ok(())
    } else {
        Err(crate::safety::tool_failed(
            builtin,
            label,
            status.code(),
            "its messages went to this terminal",
        ))
    }
}

/// The lines of a list-style tool output: trimmed, non-empty, kept in order.
fn devtool_lines(text: &str) -> Vec<Value> {
    text.lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(|l| Value::Str(l.to_string()))
        .collect()
}

/// valgrind under memcheck with the given flags. Its report is on stderr, so
/// that is the stream kept at the larger size; a nonzero exit is E_TOOL_FAILED
/// with the tail of that report.
fn devtool_valgrind(
    builtin: &str,
    flags: &[&str],
    args: &[Value],
    input: Option<Value>,
) -> Result<Value> {
    k8s_no_input(builtin, &input)?;
    let command = k8s_need(builtin, "program", args, 0, tf_plain)?;
    let mut argv: Vec<&str> = flags.to_vec();
    argv.push(command.as_str());
    let run = tool_run_stderr(
        builtin,
        "valgrind",
        None,
        &argv,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_KEEP_TAIL,
        TOOL_LONG_DEADLINE_SECS,
    )?;
    let mut rec = run_fields(finished(builtin, run)?, "stdout", "report");
    rec.insert("command".to_string(), Value::Str(command));
    Ok(Value::Record(rec))
}
/// make — Run one make target, or the default goal.
/// Usage: make_run() or make_run(target) or make_run(target, {dir?, file?, jobs?})
/// The target is one argv element, never a shell line, and it may not start
/// with '-'. `dir` and `file` must lie inside the workspace. Output keeps its
/// last 256 KiB. A nonzero exit is E_TOOL_FAILED. Effect Exec: a Makefile runs
/// its recipes.
fn bi_make_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("make_run", &input)?;
    let target = k8s_arg("make_run", "target", &args, 0, tf_plain)?;
    let options = devtool_options("make_run", &args, 1, &["dir", "file", "jobs"])?;
    let dir_opt = devtool_opt_str("make_run", "dir", options, "dir", tf_plain)?;
    let file_opt = devtool_opt_str("make_run", "file", options, "file", tf_plain)?;
    let jobs = devtool_opt_int("make_run", "jobs", options, "jobs", 1, DEVTOOL_MAX_JOBS)?;
    let dir = devtool_dir("make_run", dir_opt.as_deref())?;
    let file = match &file_opt {
        Some(f) => Some(workspace_path("make_run", f, &dir)?),
        None => None,
    };
    if let Some(f) = &file {
        if !f.is_file() {
            return Err(crate::safety::not_found(
                "make_run",
                "makefile",
                &f.display().to_string(),
            ));
        }
    }
    let mut argv: Vec<String> = Vec::new();
    if let Some(f) = &file {
        argv.push("-f".to_string());
        argv.push(f.display().to_string());
    }
    if let Some(j) = jobs {
        argv.push(format!("-j{j}"));
    }
    if let Some(t) = &target {
        argv.push(t.clone());
    }
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = finished(
        "make_run",
        tool_run(
            "make_run",
            "make",
            Some(dir.as_path()),
            &refs,
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    if let Some(t) = target {
        rec.insert("target".to_string(), Value::Str(t));
    }
    Ok(Value::Record(rec))
}

/// make — List the targets a Makefile names, read natively without running make.
/// Usage: make_targets() or make_targets(makefile_path)
/// A missing file is E_NOT_FOUND; a file over 4 MiB is refused.
fn bi_make_targets(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("make_targets", &input)?;
    let makefile = k8s_arg("make_targets", "makefile path", &args, 0, tf_plain)?
        .unwrap_or_else(|| "Makefile".to_string());
    let content = devtool_read_text("make_targets", "makefile", &makefile)?;
    let re = regex::Regex::new(r"^([a-zA-Z_][a-zA-Z0-9_.-]*)\s*:").unwrap();
    let targets: Vec<Value> = content
        .lines()
        .filter_map(|line| re.captures(line).map(|cap| Value::Str(cap[1].to_string())))
        .collect();
    Ok(Value::Array(targets))
}

/// cmake — Configure a build directory from a source directory.
/// Usage: cmake_configure(source_dir) or cmake_configure(source_dir, build_dir, {generator?, defines?})
/// Both directories default to "." and "build" and must lie inside the
/// workspace; the build directory is created when missing. A define is
/// `-Dname=value`, one argument each. Configure runs the project's CMakeLists
/// code, yet the effect table classes cmake_configure as write_local, so the
/// central gate does not ask for approval; that classification is reported,
/// not changed here. A nonzero exit is
/// E_TOOL_FAILED. Takes no pipeline input.
fn bi_cmake_configure(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("cmake_configure", &input)?;
    let source = k8s_arg("cmake_configure", "source directory", &args, 0, tf_plain)?;
    let build = k8s_arg("cmake_configure", "build directory", &args, 1, tf_plain)?
        .unwrap_or_else(|| "build".to_string());
    let options = devtool_options("cmake_configure", &args, 2, &["generator", "defines"])?;
    let generator = devtool_opt_str(
        "cmake_configure",
        "generator",
        options,
        "generator",
        tf_plain,
    )?;
    let defines = match options.and_then(|o| o.get("defines")) {
        Some(v) => devtool_defines("cmake_configure", v)?,
        None => Vec::new(),
    };
    let source_dir = devtool_dir("cmake_configure", source.as_deref())?;
    let cwd = devtool_cwd("cmake_configure")?;
    let build_dir = workspace_path("cmake_configure", &build, &cwd)?;
    let mut argv: Vec<String> = vec![
        "-S".to_string(),
        source_dir.display().to_string(),
        "-B".to_string(),
        build_dir.display().to_string(),
    ];
    if let Some(g) = generator {
        argv.push("-G".to_string());
        argv.push(g);
    }
    argv.extend(defines);
    std::fs::create_dir_all(&build_dir)
        .map_err(|e| crate::safety::fs_error("cmake_configure", &build_dir, &e))?;
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = finished(
        "cmake_configure",
        tool_run(
            "cmake_configure",
            "cmake",
            None,
            &refs,
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert(
        "source_dir".to_string(),
        Value::Str(source_dir.display().to_string()),
    );
    rec.insert(
        "build_dir".to_string(),
        Value::Str(build_dir.display().to_string()),
    );
    Ok(Value::Record(rec))
}

/// cmake — Build a configured CMake build directory.
/// Usage: cmake_build(build_dir) or cmake_build(build_dir, {target?, config?, jobs?})
/// The build directory must exist and lie inside the workspace. Options are
/// one argument each and may not start with '-'. Runs the project's build
/// steps, so its effect is Exec. A nonzero exit is E_TOOL_FAILED.
fn bi_cmake_build(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("cmake_build", &input)?;
    let build = k8s_arg("cmake_build", "build directory", &args, 0, tf_plain)?
        .unwrap_or_else(|| "build".to_string());
    let options = devtool_options("cmake_build", &args, 1, &["target", "config", "jobs"])?;
    let target = devtool_opt_str("cmake_build", "target", options, "target", tf_plain)?;
    let config = devtool_opt_str("cmake_build", "config", options, "config", tf_plain)?;
    let jobs = devtool_opt_int("cmake_build", "jobs", options, "jobs", 1, DEVTOOL_MAX_JOBS)?;
    let dir = devtool_dir("cmake_build", Some(build.as_str()))?;
    let mut argv: Vec<String> = vec!["--build".to_string(), dir.display().to_string()];
    if let Some(t) = &target {
        argv.push("--target".to_string());
        argv.push(t.clone());
    }
    if let Some(c) = &config {
        argv.push("--config".to_string());
        argv.push(c.clone());
    }
    if let Some(j) = jobs {
        argv.push("-j".to_string());
        argv.push(j.to_string());
    }
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = finished(
        "cmake_build",
        tool_run(
            "cmake_build",
            "cmake",
            None,
            &refs,
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert(
        "build_dir".to_string(),
        Value::Str(dir.display().to_string()),
    );
    Ok(Value::Record(rec))
}

// ---------------------------------------------------------------------------
// Lint, format and search builtins: the checks and bounded results they share
// ---------------------------------------------------------------------------

/// The most results one search returns. A search with more is refused with
/// E_BUDGET_EXCEEDED, because a list cut at a cap reads as the whole answer.
const SEARCH_MAX_RESULTS: usize = 1000;
/// The most bytes of one text file a content search reads.
const SEARCH_MAX_FILE: u64 = 64 * 1024 * 1024;
/// The leading bytes a content search inspects for a NUL, as `grep -I` does.
const SEARCH_BINARY_PROBE: u64 = 8000;

/// A search pattern or other search text: non-empty, no NUL byte. It reaches
/// the tool as `--regexp=` or as a value, so a leading '-' is data, not a flag.
fn search_text_check(builtin: &str, what: &str, value: &str) -> Result<String> {
    if value.is_empty() || value.contains('\0') {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must be a non-empty string with no NUL byte"
        )));
    }
    Ok(value.to_string())
}

/// The refusal for a search whose results would pass the cap.
fn search_budget(builtin: &str) -> anyhow::Error {
    crate::safety::budget_exceeded(
        builtin,
        format!("more than {SEARCH_MAX_RESULTS} results"),
        "narrow the pattern or the path so that fewer results match",
    )
}

/// Found paths or lines as the Array a search returns, refused past the cap.
fn search_list(builtin: &str, found: Vec<String>) -> Result<Value> {
    if found.len() > SEARCH_MAX_RESULTS {
        return Err(search_budget(builtin));
    }
    Ok(Value::Array(found.into_iter().map(Value::Str).collect()))
}

/// The stdout of a tool whose exit 1 is an answer rather than a failure: ripgrep
/// (and rga, which runs it) exit 1 for "no matches", mypy for "type errors".
/// Any other nonzero exit is E_TOOL_FAILED with the stderr tail.
fn stdout_with_exit1(builtin: &str, mut run: ToolRun) -> Result<String> {
    if run.code == Some(1) {
        run.success = true;
    }
    tool_text(builtin, run)
}

/// A tool whose exit 0 and exit `answer` both print a JSON report, which is the
/// answer. Any other exit is E_TOOL_FAILED, and output that is not JSON is too.
fn findings_json(builtin: &str, mut run: ToolRun, answer: i32) -> Result<Value> {
    if run.code == Some(answer) {
        run.success = true;
    }
    let command = run.command.clone();
    let code = run.code;
    let stderr = run.stderr.clone();
    let text = tool_text(builtin, run)?;
    serde_json::from_str::<serde_json::Value>(&text)
        .map(json_to_value)
        .map_err(|e| {
            let detail = if stderr.is_empty() {
                format!("printed output that is not JSON ({e})")
            } else {
                stderr
            };
            crate::safety::tool_failed(builtin, &command, code, &detail)
        })
}

/// Writes `bytes` to a new file, in a new directory under the system temporary
/// directory, for a tool that reads its input from a file rather than a pipe.
/// The caller removes the directory with [`scratch_remove`].
fn scratch_file(builtin: &str, file_name: &str, bytes: &[u8]) -> Result<std::path::PathBuf> {
    let dir = std::env::temp_dir().join(format!("ae_{builtin}_{}", uuid::Uuid::new_v4().simple()));
    std::fs::create_dir(&dir).map_err(|e| crate::safety::fs_error(builtin, &dir, &e))?;
    let file = dir.join(file_name);
    if let Err(e) = std::fs::write(&file, bytes) {
        scratch_remove(&file);
        return Err(crate::safety::fs_error(builtin, &file, &e));
    }
    Ok(file)
}

/// Removes the directory that [`scratch_file`] made for `file`.
fn scratch_remove(file: &std::path::Path) {
    if let Some(dir) = file.parent() {
        let _ = std::fs::remove_dir_all(dir);
    }
}

/// An fd entry kind: one of fd's type letters.
fn fd_kind_check(builtin: &str, what: &str, value: &str) -> Result<String> {
    match value {
        "f" | "d" | "l" | "x" | "e" | "s" | "p" => Ok(value.to_string()),
        _ => Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is one of f, d, l, x, e, s, p (got {value:?})"
        ))),
    }
}

/// A file extension for fd: letters, digits and `_+-`, not starting with '-'.
fn fd_ext_check(builtin: &str, what: &str, value: &str) -> Result<String> {
    let well_formed = !value.is_empty()
        && value.len() <= 32
        && !value.starts_with('-')
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "_+-".contains(c));
    if well_formed {
        Ok(value.to_string())
    } else {
        Err(crate::safety::arg_err(format!(
            "{builtin}: {what} is an extension such as rs (letters, digits and _+- only), got {value:?}"
        )))
    }
}

/// The text of one file that a content search reads. A file with a NUL in its
/// first bytes is binary and is skipped, as `grep -I` skips it. A text file past
/// the size limit is refused rather than read in part.
fn search_read_text(builtin: &str, path: &std::path::Path, shown: &str) -> Result<Option<String>> {
    use std::io::Read;
    let mut file =
        std::fs::File::open(path).map_err(|e| crate::safety::fs_error(builtin, shown, &e))?;
    let mut bytes = Vec::new();
    (&mut file)
        .take(SEARCH_BINARY_PROBE)
        .read_to_end(&mut bytes)
        .map_err(|e| crate::safety::fs_error(builtin, shown, &e))?;
    if bytes.contains(&0) {
        return Ok(None);
    }
    (&mut file)
        .take(SEARCH_MAX_FILE + 1 - bytes.len() as u64)
        .read_to_end(&mut bytes)
        .map_err(|e| crate::safety::fs_error(builtin, shown, &e))?;
    if bytes.len() as u64 > SEARCH_MAX_FILE {
        return Err(crate::safety::budget_exceeded(
            builtin,
            format!("`{shown}` is larger than {} MiB", SEARCH_MAX_FILE >> 20),
            "search a narrower directory",
        ));
    }
    Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
}

fn search_pattern_builtin(builtin: &str, args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input(builtin, &input)?;
    k8s_max_args(builtin, &args, 1)?;
    let pattern = k8s_need(builtin, "a regular expression", &args, 0, search_text_check)?;
    let found = search_grep(builtin, &pattern)?;
    search_list(builtin, found)
}

/// ninja — Fast build system.
/// Usage: ninja_build() or ninja_build({dir?, target?, jobs?})
fn bi_ninja_build(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ninja_build";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    let mut dir = None;
    let mut options = None;
    match args.first() {
        None => {}
        Some(Value::Str(d)) => dir = Some(pkg_plain(B, "dir", d)?),
        Some(_) => options = devtool_options(B, &args, 0, &["dir", "target", "jobs"])?,
    }
    if dir.is_none() {
        dir = devtool_opt_str(B, "dir", options, "dir", pkg_plain)?;
    }
    let target = devtool_opt_str(B, "target", options, "target", pkg_plain)?;
    let jobs = devtool_opt_int(B, "jobs", options, "jobs", 1, DEVTOOL_MAX_JOBS)?;
    let workdir = devtool_dir(B, dir.as_deref())?;
    let mut argv: Vec<String> = Vec::new();
    if let Some(j) = jobs {
        argv.push(format!("-j{j}"));
    }
    if let Some(t) = target {
        argv.push(t);
    }
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = tool_run(
        B,
        "ninja",
        Some(workdir.as_path()),
        &refs,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    pkg_done(B, run, Vec::new())
}

/// netstat — Display network connections and socket information (cross-platform).
/// Usage: netstat() or netstat({proto?, state?, port?})
fn bi_netstat_info(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let flags = if cfg!(target_os = "windows") {
        vec!["-an".to_string()]
    } else {
        vec!["-tuln".to_string()]
    };
    let mut cmd = crate::safety::child_command("netstat");
    cmd.args(&flags);
    let out = bounded_cmd_output("netstat", "netstat", cmd, PROBE_DEADLINE_SECS)?;
    if !out.status.success() {
        return Err(crate::safety::tool_failed(
            "netstat",
            "netstat",
            out.status.code(),
            &String::from_utf8_lossy(&out.stderr),
        ));
    }
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    // Parse netstat output into structured records
    let filter_proto = match args.first() {
        Some(Value::Record(r)) => r.get("proto").and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.clone())
            } else {
                None
            }
        }),
        _ => None,
    };
    let filter_state = match args.first() {
        Some(Value::Record(r)) => r.get("state").and_then(|v| {
            if let Value::Str(s) = v {
                Some(s.to_uppercase())
            } else {
                None
            }
        }),
        _ => None,
    };
    let filter_port = match args.first() {
        Some(Value::Record(r)) => r.get("port").and_then(|v| {
            if let Value::Int(n) = v {
                Some(*n)
            } else {
                None
            }
        }),
        _ => None,
    };
    let mut connections = Vec::new();
    for line in stdout.lines().skip(2) {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 4 {
            continue;
        }
        let proto = parts[0].to_string();
        let local_addr = if parts.len() > 3 {
            parts[3].to_string()
        } else {
            parts[1].to_string()
        };
        let foreign_addr = if parts.len() > 4 {
            parts[4].to_string()
        } else {
            parts[2].to_string()
        };
        let state = if parts.len() > 5 {
            parts[5].to_string()
        } else {
            String::new()
        };
        // Apply filters
        if let Some(ref fp) = filter_proto {
            if !proto.to_lowercase().contains(&fp.to_lowercase()) {
                continue;
            }
        }
        if let Some(ref fs) = filter_state {
            if !state.to_uppercase().contains(fs) {
                continue;
            }
        }
        if let Some(fp) = filter_port {
            let port_str = format!(":{}", fp);
            if !local_addr.contains(&port_str) && !foreign_addr.contains(&port_str) {
                continue;
            }
        }
        let mut rec = BTreeMap::new();
        rec.insert("proto".to_string(), Value::Str(proto));
        rec.insert("local_address".to_string(), Value::Str(local_addr));
        rec.insert("foreign_address".to_string(), Value::Str(foreign_addr));
        if !state.is_empty() {
            rec.insert("state".to_string(), Value::Str(state));
        }
        connections.push(Value::Record(rec));
    }
    Ok(Value::Array(connections))
}

/// nmap — Network port scanning.
/// Usage: nmap_scan(host) or nmap_scan(host, {ports?, flags?}). ports is a list
/// such as "22,80,1000-1100" with every port in 1..=65535. flags is a
/// whitespace-separated list drawn from NMAP_FLAGS; any other flag is refused by
/// policy, because nmap's other options run scripts or write files. The host may
/// not begin with '-'. Returns {host, ports}, one Record per port, with its
/// state and service. A nonzero exit is E_TOOL_FAILED; a missing nmap is E_TOOL_MISSING.
fn bi_nmap_scan(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    net_refuse_in_transaction("nmap_scan")?;
    k8s_no_input("nmap_scan", &input)?;
    k8s_max_args("nmap_scan", &args, 2)?;
    let host = k8s_need("nmap_scan", "a host", &args, 0, net_target_host)?;
    let options = devtool_options("nmap_scan", &args, 1, &["ports", "flags"])?;
    let ports = devtool_opt_str("nmap_scan", "ports", options, "ports", nmap_ports)?;
    let flags = devtool_opt_str("nmap_scan", "flags", options, "flags", nmap_flags)?;
    let mut argv: Vec<String> = vec!["-oX".to_string(), "-".to_string()];
    if let Some(p) = ports {
        argv.push("-p".to_string());
        argv.push(p);
    }
    if let Some(f) = flags {
        argv.extend(f.split_whitespace().map(str::to_string));
    }
    argv.push(host.clone());
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = tool_run(
        "nmap_scan",
        "nmap",
        None,
        &refs,
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    let xml = tool_text("nmap_scan", run)?;
    let mut port_rows: Vec<Value> = Vec::new();
    for line in xml.lines() {
        let line = line.trim();
        if line.starts_with("<port ") {
            let mut rec = BTreeMap::new();
            if let Some(portid) = extract_xml_attr(line, "portid") {
                rec.insert(
                    "port".to_string(),
                    portid.parse::<i64>().map_or(Value::Null, Value::Int),
                );
            }
            if let Some(proto) = extract_xml_attr(line, "protocol") {
                rec.insert("protocol".to_string(), Value::Str(proto));
            }
            port_rows.push(Value::Record(rec));
        }
        if line.starts_with("<state ") {
            if let Some(Value::Record(rec)) = port_rows.last_mut() {
                if let Some(state) = extract_xml_attr(line, "state") {
                    rec.insert("state".to_string(), Value::Str(state));
                }
                if let Some(reason) = extract_xml_attr(line, "reason") {
                    rec.insert("reason".to_string(), Value::Str(reason));
                }
            }
        }
        if line.starts_with("<service ") {
            if let Some(Value::Record(rec)) = port_rows.last_mut() {
                if let Some(name) = extract_xml_attr(line, "name") {
                    rec.insert("service".to_string(), Value::Str(name));
                }
            }
        }
    }
    let mut result = BTreeMap::new();
    result.insert("host".to_string(), Value::Str(host));
    result.insert("ports".to_string(), Value::Array(port_rows));
    Ok(Value::Record(result))
}

/// nmap — Quick scan of the common ports, open ones only.
/// Usage: nmap_quick(host). The host may not begin with '-'. Returns {host,
/// ports, scan_type}. A nonzero exit is E_TOOL_FAILED; a missing nmap is E_TOOL_MISSING.
fn bi_nmap_quick(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    net_refuse_in_transaction("nmap_quick")?;
    k8s_no_input("nmap_quick", &input)?;
    k8s_max_args("nmap_quick", &args, 1)?;
    let host = k8s_need("nmap_quick", "a host", &args, 0, net_target_host)?;
    let run = tool_run(
        "nmap_quick",
        "nmap",
        None,
        &["-F", "--open", host.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    let stdout = tool_text("nmap_quick", run)?;
    let mut ports = Vec::new();
    for line in stdout.lines() {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 3 && parts[0].contains('/') {
            let port_proto: Vec<&str> = parts[0].split('/').collect();
            let mut rec = BTreeMap::new();
            rec.insert(
                "port".to_string(),
                port_proto[0].parse::<i64>().map_or(Value::Null, Value::Int),
            );
            rec.insert(
                "protocol".to_string(),
                Value::Str(port_proto.get(1).unwrap_or(&"").to_string()),
            );
            rec.insert("state".to_string(), Value::Str(parts[1].to_string()));
            rec.insert("service".to_string(), Value::Str(parts[2].to_string()));
            ports.push(Value::Record(rec));
        }
    }
    let mut result = BTreeMap::new();
    result.insert("host".to_string(), Value::Str(host));
    result.insert("ports".to_string(), Value::Array(ports));
    result.insert(
        "scan_type".to_string(),
        Value::Str("quick (-F --open)".to_string()),
    );
    Ok(Value::Record(result))
}

/// Helper: extract an XML attribute value from a tag line.
fn extract_xml_attr(line: &str, attr: &str) -> Option<String> {
    let pattern = format!("{}=\"", attr);
    if let Some(start) = line.find(&pattern) {
        let val_start = start + pattern.len();
        if let Some(end) = line[val_start..].find('"') {
            return Some(line[val_start..val_start + end].to_string());
        }
    }
    None
}
// ============================================================
// CLI Tool Wrappers — Tools 51-150 (indices 988-1103)
// ============================================================

// --- Dead-code activations (988-994) ---
// bi_file_type (988) — already defined at ~L32793
// bi_dd_copy (989) — already defined at ~L33373
// bi_lsblk (990) — already defined at ~L32948
// bi_blkid (991) — already defined at ~L32983
// bi_strace_cmd (992) — already defined at ~L33146
// bi_mount_info (993) — already defined at ~L33569
// bi_top_snapshot (994) — already defined at ~L33270

// --- tmux (995-998) ---

/// tmux new-session — Create a detached tmux session with a shell in it.
/// Usage: tmux_new(session_name)
/// The name is 1-64 letters, digits, '-' or '_'. The session runs the default
/// shell and nothing else: tmux takes a command as one string for its shell,
/// which is `sh -c` by another name, so to start a program use tmux_send.
/// A name already in use is E_TOOL_FAILED.
fn bi_tmux_new(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("tmux_new", &input)?;
    if args.len() > 1 {
        return Err(crate::safety::arg_err(format!(
            "tmux_new takes a session name only; {} more argument(s) given. Start the program inside the session with tmux_send, which is approval-gated.",
            args.len() - 1
        )));
    }
    let name = k8s_need("tmux_new", "session name", &args, 0, devtool_session)?;
    // tmux_new is listed as self-guarded, so the central gate does not run for
    // it. This is the guard it relies on instead: creating a session is a
    // process effect and asks for approval in agent mode.
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "tmux_new",
        effect: crate::safety::Effect::Process,
        what: "process",
        targets: vec![name.clone()],
        blast_radius: serde_json::json!({ "sessions": 1 }),
        reversible: true,
        fs_paths: false,
    })?;
    let run = finished(
        "tmux_new",
        tool_run(
            "tmux_new",
            "tmux",
            None,
            &["new-session", "-d", "-s", name.as_str()],
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("session".to_string(), Value::Str(name));
    Ok(Value::Record(rec))
}

/// tmux list-sessions — List active tmux sessions.
/// Whether tmux's failure text means there is no server, and so no sessions.
/// "no server running" is the answer. "error connecting to <socket> (No such
/// file or directory)" is the same state when the socket file is absent. Any
/// other connect error, such as a permission denial on the socket, is not.
fn tmux_no_server(stderr: &str) -> bool {
    stderr.contains("no server running")
        || (stderr.contains("error connecting to") && stderr.contains("No such file or directory"))
}

/// One `name:windows:attached` line of `tmux list-sessions -F`. A line that
/// does not have that shape is refused, not read with a zero window count.
fn tmux_session_record(line: &str) -> Result<Value> {
    let parts: Vec<&str> = line.splitn(3, ':').collect();
    let (Some(name), Some(windows), Some(attached)) = (parts.first(), parts.get(1), parts.get(2))
    else {
        return Err(tmux_unparsed());
    };
    let windows: i64 = windows.parse().map_err(|_| tmux_unparsed())?;
    let attached = match *attached {
        "0" => false,
        "1" => true,
        _ => return Err(tmux_unparsed()),
    };
    let mut rec = BTreeMap::new();
    rec.insert("name".to_string(), Value::Str(name.to_string()));
    rec.insert("windows".to_string(), Value::Int(windows));
    rec.insert("attached".to_string(), Value::Bool(attached));
    Ok(Value::Record(rec))
}

fn tmux_unparsed() -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::ToolFailed,
        message:
            "tmux_list: the output of `tmux list-sessions` is not in a form this builtin reads"
                .to_string(),
        builtin: "tmux_list".to_string(),
        hint: "`tmux` ran, but its session list does not match the format this builtin asks for"
            .to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: "`tmux list-sessions` output this builtin reads".to_string(),
        got: "unreadable output".to_string(),
        extra: serde_json::Map::new(),
    })
}

fn bi_tmux_list(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("tmux");
    cmd.args([
        "list-sessions",
        "-F",
        "#{session_name}:#{session_windows}:#{session_attached}",
    ]);
    let output = bounded_cmd_output("tmux_list", "tmux", cmd, TOOL_DEADLINE_SECS);
    match output {
        Ok(o) if o.status.success() => {
            let stdout = String::from_utf8_lossy(&o.stdout);
            let sessions: Vec<Value> = stdout
                .lines()
                .filter(|l| !l.is_empty())
                .map(tmux_session_record)
                .collect::<Result<_>>()?;
            Ok(Value::Array(sessions))
        }
        // tmux's stderr used to come back as the successful result: with no
        // server running, `tmux_list()` answered the String "error connecting
        // to /tmp/tmux-1001/default (No such file or directory)" at exit 0.
        // No server means no sessions; anything else is a failure. Any
        // "error connecting to" used to be read as no server, which also hid a
        // permission error on the socket.
        Ok(o) => {
            let err = String::from_utf8_lossy(&o.stderr);
            if tmux_no_server(&err) {
                return Ok(Value::Array(vec![]));
            }
            Err(crate::safety::tool_failed(
                "tmux_list",
                "tmux list-sessions",
                o.status.code(),
                &err,
            ))
        }
        Err(e) => Err(crate::safety::tool_missing(
            "tmux_list",
            "tmux",
            &e.to_string(),
        )),
    }
}

/// tmux attach — Attach this terminal to a tmux session until the user detaches.
/// Usage: tmux_attach(session_name)
/// Needs a terminal on stdin and stdout and is refused as E_NO_UI without one,
/// and in agent mode. Its effect is Process, so agent mode would ask first.
fn bi_tmux_attach(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("tmux_attach", &input)?;
    let name = k8s_need("tmux_attach", "session name", &args, 0, devtool_session)?;
    devtool_terminal("tmux_attach")?;
    devtool_attach(
        "tmux_attach",
        "tmux",
        &["attach-session", "-t", &exact_tmux_target(&name)],
        "tmux attach-session",
    )?;
    let mut rec = BTreeMap::new();
    rec.insert("session".to_string(), Value::Str(name));
    rec.insert("success".to_string(), Value::Bool(true));
    Ok(Value::Record(rec))
}

/// tmux send-keys — Type a line into a session the caller named, then press Enter.
/// Usage: tmux_send(target, keys)
/// This is execution in another process's shell, so it is approval-gated. The
/// keys are one line with no control characters and may not start with '-'.
/// A session that does not exist is E_TOOL_FAILED.
fn bi_tmux_send(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("tmux_send", &input)?;
    let target = k8s_need("tmux_send", "target session", &args, 0, devtool_target)?;
    let keys = k8s_need("tmux_send", "keys to send", &args, 1, devtool_keys)?;
    crate::safety::guard_exec("tmux_send", &keys)?;
    let run = finished(
        "tmux_send",
        tool_run(
            "tmux_send",
            "tmux",
            None,
            &[
                "send-keys",
                "-t",
                &exact_tmux_pane(&target),
                keys.as_str(),
                "Enter",
            ],
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("target".to_string(), Value::Str(target));
    rec.insert("keys".to_string(), Value::Str(keys));
    Ok(Value::Record(rec))
}

/// A tmux session target matched exactly. tmux otherwise resolves `-t work`
/// to a session whose name starts with "work" when none is called "work", so
/// a kill or attach would reach another session.
fn exact_tmux_target(name: &str) -> String {
    format!("={name}")
}

/// The pane-target form of [`exact_tmux_target`], for send-keys: tmux reads
/// a bare `=work` there as a pane name and finds none, so a session alone is
/// written `=work:` (its current window), and `work:1` becomes `=work:1`.
fn exact_tmux_pane(target: &str) -> String {
    if target.contains(':') {
        format!("={target}")
    } else {
        format!("={target}:")
    }
}

/// tmux kill-session — End a session that tmux_new started, and what runs in it.
/// Usage: tmux_kill(session_name)
/// The name is 1-64 letters, digits, '-' or '_', as tmux_new takes it. It runs
/// no command, so it is process control, not exec. A session that does not
/// exist is E_TOOL_FAILED.
fn bi_tmux_kill(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("tmux_kill", &input)?;
    if args.len() > 1 {
        return Err(crate::safety::arg_err(format!(
            "tmux_kill takes a session name only; {} more argument(s) given.",
            args.len() - 1
        )));
    }
    let name = k8s_need("tmux_kill", "session name", &args, 0, devtool_session)?;
    let run = finished(
        "tmux_kill",
        tool_run(
            "tmux_kill",
            "tmux",
            None,
            &["kill-session", "-t", &exact_tmux_target(&name)],
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("session".to_string(), Value::Str(name));
    Ok(Value::Record(rec))
}

// --- screen (999-1001) ---

/// screen — Start a detached GNU screen session with a shell in it.
/// Usage: screen_new(session_name)
/// The name is 1-64 letters, digits, '-' or '_'. A failure is E_TOOL_FAILED.
fn bi_screen_new(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("screen_new", &input)?;
    let name = k8s_need("screen_new", "session name", &args, 0, devtool_session)?;
    let run = finished(
        "screen_new",
        tool_run(
            "screen_new",
            "screen",
            None,
            &["-dmS", name.as_str()],
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("session".to_string(), Value::Str(name));
    Ok(Value::Record(rec))
}

/// screen list — List screen sessions.
fn bi_screen_list(_args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("screen");
    cmd.args(["-ls"]);
    let output = bounded_cmd_output("screen_list", "screen", cmd, PROBE_DEADLINE_SECS)?;
    screen_sessions(
        output.status.success(),
        output.status.code(),
        &String::from_utf8_lossy(&output.stdout),
        &String::from_utf8_lossy(&output.stderr),
    )
}

/// What `screen -ls` answers, from its exit status and both streams.
///
/// GNU screen exits non-zero for two things that are answers, not failures:
/// no sessions at all ("No Sockets found in <dir>."), and a listing whose
/// sessions are all dead. Both are answered from what it printed: the session
/// lines, or none. Any other non-zero exit is a failure, such as a socket
/// directory it cannot read. That used to come back as an empty list, which
/// reads as "no sessions". I have not confirmed the exact exit codes on a
/// host, so the code keys on the output rather than on a number.
fn screen_sessions(success: bool, code: Option<i32>, stdout: &str, stderr: &str) -> Result<Value> {
    let sessions: Vec<Value> = stdout
        .lines()
        .filter(|l| l.contains('('))
        .map(|line| {
            let trimmed = line.trim();
            let mut rec = BTreeMap::new();
            rec.insert("line".to_string(), Value::Str(trimmed.to_string()));
            if let Some(name_part) = trimmed.split_whitespace().next() {
                rec.insert("id".to_string(), Value::Str(name_part.to_string()));
            }
            Value::Record(rec)
        })
        .collect();
    let says_none = stdout.contains("No Sockets found") || stderr.contains("No Sockets found");
    if success || !sessions.is_empty() || says_none {
        return Ok(Value::Array(sessions));
    }
    Err(crate::safety::tool_failed(
        "screen_list",
        "screen",
        code,
        stderr,
    ))
}

/// screen — Attach this terminal to a screen session until the user detaches.
/// Usage: screen_attach(session_name)
/// Needs a terminal on stdin and stdout and is refused as E_NO_UI without one,
/// and in agent mode. Its effect is Process, so agent mode would ask first.
fn bi_screen_attach(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("screen_attach", &input)?;
    let name = k8s_need("screen_attach", "session name", &args, 0, devtool_session)?;
    devtool_terminal("screen_attach")?;
    devtool_attach(
        "screen_attach",
        "screen",
        &["-r", name.as_str()],
        "screen -r",
    )?;
    let mut rec = BTreeMap::new();
    rec.insert("session".to_string(), Value::Str(name));
    rec.insert("success".to_string(), Value::Bool(true));
    Ok(Value::Record(rec))
}

// --- timeout (1002) ---

/// timeout — Run one program with a time limit, and return its result.
/// Usage: timeout_cmd(seconds, command). seconds is 1..=3600. The command is split
/// on whitespace into a program and its arguments and run directly, with no shell;
/// the program may not begin with '-'. Returns {command, exit_code, stdout,
/// stderr, stdout_truncated}. The exit code is the program's and is data. A
/// program still running at the limit is killed and the call is E_BUDGET_EXCEEDED.
fn bi_timeout_cmd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("timeout_cmd", &input)?;
    k8s_max_args("timeout_cmd", &args, 2)?;
    let seconds = match args.first() {
        Some(Value::Int(n)) if (1..=3600).contains(n) => *n as u64,
        _ => {
            return Err(crate::safety::arg_err(
                "timeout_cmd requires seconds as an Int 1..=3600 first",
            ))
        }
    };
    let command = match args.get(1) {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "timeout_cmd requires a command string second",
            ))
        }
    };
    let words = argv_words("timeout_cmd", &command)?;
    crate::safety::guard_exec("timeout", &command)?;
    let argv: Vec<&str> = words.iter().skip(1).map(String::as_str).collect();
    let run = tool_run_stderr(
        "timeout_cmd",
        &words[0],
        None,
        &argv,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_KEEP_TAIL,
        seconds,
    )?;
    let mut rec = BTreeMap::new();
    rec.insert("command".to_string(), Value::Str(command));
    rec.insert("exit_code".to_string(), Value::Int(exit_code_of(&run)));
    rec.insert("stdout".to_string(), Value::Str(run.stdout.clone()));
    rec.insert("stderr".to_string(), Value::Str(run.stderr.clone()));
    rec.insert(
        "stdout_truncated".to_string(),
        Value::Bool(run.stdout_truncated),
    );
    Ok(Value::Record(rec))
}

// --- pkill (1003) ---

/// The process-name pattern `pkill` and `pgrep` take: a literal name prefix.
///
/// Both used to hand the pattern to an OS tool with different rules. On Unix it
/// was a pkill regex matched anywhere in the name, so `.` matched every process;
/// on Windows it became `taskkill /IM pattern*`, so an empty pattern was `*`.
/// Wildcards are refused rather than escaped, because a caller writing one
/// meant it, and a literal match would quietly do something else.
fn proc_name_pattern(builtin: &str, args: &[Value], input: &Option<Value>) -> Result<String> {
    refuse_piped(builtin, input)?;
    k8s_max_args(builtin, args, 1)?;
    match args.first() {
        Some(Value::Str(s))
            if !s.trim().is_empty() && !s.chars().any(|c| c.is_control() || "*?[]".contains(c)) =>
        {
            Ok(s.clone())
        }
        other => Err(crate::safety::bad_arg(
            builtin,
            "a process name prefix: a non-empty String with no wildcard or control character",
            other.map(|v| v.type_name()).unwrap_or("nothing"),
        )),
    }
}

/// Processes whose name begins with `pattern`, sorted by pid. Names compare
/// without regard to case on Windows, where the file system does the same.
fn proc_name_matches(pattern: &str) -> Vec<(u32, String, String)> {
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
    let fold = |s: &str| {
        if cfg!(windows) {
            s.to_lowercase()
        } else {
            s.to_string()
        }
    };
    let want = fold(pattern);
    let mut found: Vec<(u32, String, String)> = sys
        .processes()
        .iter()
        // On Linux each thread is listed too, under its process name; a
        // thread is not a process to report or to kill.
        .filter(|(_, p)| p.thread_kind().is_none())
        .filter_map(|(pid, p)| {
            let name = p.name().to_string_lossy().to_string();
            if !fold(&name).starts_with(&want) {
                return None;
            }
            let command = p
                .cmd()
                .iter()
                .map(|a| a.to_string_lossy().to_string())
                .collect::<Vec<_>>()
                .join(" ");
            Some((pid.as_u32(), name, command))
        })
        .collect();
    found.sort_by_key(|(pid, _, _)| *pid);
    found
}

/// pkill — Kill every process whose name begins with a prefix.
/// Usage: pkill(prefix). The prefix is literal; wildcards are refused. This shell
/// and pid 0 and 1 are never killed. Each match is killed forcibly (SIGKILL,
/// or TerminateProcess on Windows). The result is {pattern, killed: [pid]};
/// no match is an empty list. A match that could not be killed is
/// E_TOOL_FAILED, naming the pids that were killed before it.
///
/// It used to report `success: false` as a value when nothing was killed or the
/// kill was refused, and it ran a different matcher on each OS.
fn bi_pkill(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let pattern = proc_name_pattern("pkill", &args, &input)?;
    let me = std::process::id();
    let targets: Vec<(u32, String)> = proc_name_matches(&pattern)
        .into_iter()
        .filter(|(pid, _, _)| *pid > 1 && *pid != me)
        .map(|(pid, name, _)| (pid, name))
        .collect();
    let mut sys = System::new();
    let mut killed = Vec::new();
    let mut failed = Vec::new();
    for (pid, name) in targets {
        let spid = sysinfo::Pid::from_u32(pid);
        sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[spid]), true);
        match sys.process(spid) {
            // Exited between the listing and now: nothing left to kill.
            None => {}
            Some(p) if p.kill() => killed.push(pid),
            Some(_) => failed.push(format!("{pid} ({name})")),
        }
    }
    if !failed.is_empty() {
        let done: Vec<String> = killed.iter().map(u32::to_string).collect();
        return Err(crate::safety::tool_failed(
            "pkill",
            &format!("kill processes named {pattern}*"),
            None,
            &format!(
                "could not kill {}; killed [{}]",
                failed.join(", "),
                done.join(", ")
            ),
        ));
    }
    let mut rec = BTreeMap::new();
    rec.insert("pattern".to_string(), Value::Str(pattern));
    rec.insert(
        "killed".to_string(),
        Value::Array(
            killed
                .into_iter()
                .map(|p| Value::Int(i64::from(p)))
                .collect(),
        ),
    );
    Ok(Value::Record(rec))
}

// --- pgrep (1004) ---

/// pgrep — Find processes whose name begins with a prefix.
/// Usage: pgrep(prefix). The prefix is literal; wildcards are refused. The
/// result is [{pid, name, command}] sorted by pid, empty when nothing matches.
///
/// The pid used to be a String on Windows and an Int elsewhere, and a failed
/// listing came back as an empty list.
fn bi_pgrep(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let pattern = proc_name_pattern("pgrep", &args, &input)?;
    let procs = proc_name_matches(&pattern)
        .into_iter()
        .map(|(pid, name, command)| {
            let mut rec = BTreeMap::new();
            rec.insert("pid".to_string(), Value::Int(i64::from(pid)));
            rec.insert("name".to_string(), Value::Str(name));
            rec.insert("command".to_string(), Value::Str(command));
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(procs))
}

// --- lnav (1005) ---

/// lnav — Open one log file in the lnav viewer.
/// Usage: lnav_open(path). The file must exist, and its path may not begin with
/// '-'. lnav is interactive, so it needs a terminal on stdin and stdout and a
/// person at it. Without both, or in agent mode, the call is E_NO_UI before
/// anything is started. With a terminal the viewer runs until the person quits,
/// and the result is {path}.
fn bi_lnav_open(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("lnav_open", &input)?;
    k8s_max_args("lnav_open", &args, 1)?;
    let path = k8s_need("lnav_open", "a log file path", &args, 0, tf_plain)?;
    if !std::path::Path::new(&path).is_file() {
        return Err(crate::safety::not_found("lnav_open", "log file", &path));
    }
    devtool_terminal("lnav_open")?;
    devtool_attach("lnav_open", "lnav", &[path.as_str()], "lnav")?;
    let mut rec = BTreeMap::new();
    rec.insert("path".to_string(), Value::Str(path));
    Ok(Value::Record(rec))
}

// --- multitail (1006) ---

/// multitail — Tail several files at once in the multitail viewer.
/// Usage: multitail_open(file, ...), one to 16 existing files, none beginning
/// with '-'. multitail is interactive, so it needs a terminal on stdin and stdout
/// and a person at it. Without both, or in agent mode, the call is E_NO_UI before
/// anything is started. With a terminal the viewer runs until the person quits,
/// and the result is {files}.
fn bi_multitail_open(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("multitail_open", &input)?;
    if args.is_empty() {
        return Err(crate::safety::arg_err(
            "multitail_open requires at least one file path",
        ));
    }
    if args.len() > MULTITAIL_MAX_FILES {
        return Err(crate::safety::budget_exceeded(
            "multitail_open",
            format!("{} files; the limit is {MULTITAIL_MAX_FILES}", args.len()),
            "open fewer files at once",
        ));
    }
    let mut files: Vec<String> = Vec::with_capacity(args.len());
    for a in &args {
        let Value::Str(s) = a else {
            return Err(crate::safety::bad_arg(
                "multitail_open",
                "a file path String",
                a.type_name(),
            ));
        };
        let f = tf_plain("multitail_open", "a file path", s)?;
        if !std::path::Path::new(&f).is_file() {
            return Err(crate::safety::not_found("multitail_open", "log file", &f));
        }
        files.push(f);
    }
    devtool_terminal("multitail_open")?;
    let refs: Vec<&str> = files.iter().map(String::as_str).collect();
    devtool_attach("multitail_open", "multitail", &refs, "multitail")?;
    let mut rec = BTreeMap::new();
    rec.insert(
        "files".to_string(),
        Value::Array(files.iter().map(|f| Value::Str(f.clone())).collect()),
    );
    Ok(Value::Record(rec))
}

// --- logrotate (1007) ---

/// logrotate — Run logrotate with a configuration file inside the workspace.
/// Usage: logrotate_run(config) or logrotate_run(config, force). The configuration
/// must be an existing file inside the workspace, and its path may not begin with
/// '-'. Its paths must be relative and without '..', and it may not contain a
/// directive that runs a program or sends mail (prerotate, postrotate, firstaction,
/// lastaction, preremove, mail, mailfirst, maillast); each is refused by policy.
/// The state file is <config>.state beside it, so no system state is written.
/// force is a Bool. A nonzero exit is E_TOOL_FAILED.
fn bi_logrotate_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("logrotate_run", &input)?;
    k8s_max_args("logrotate_run", &args, 2)?;
    let config = k8s_need(
        "logrotate_run",
        "a configuration file path",
        &args,
        0,
        tf_plain,
    )?;
    let force = match args.get(1) {
        None => false,
        Some(Value::Bool(b)) => *b,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "logrotate_run",
                "force: Bool",
                other.type_name(),
            ))
        }
    };
    let config_path = workspace_path("logrotate_run", &config, &workspace_root_abs())?;
    if !config_path.is_file() {
        return Err(crate::safety::not_found(
            "logrotate_run",
            "configuration file",
            &config,
        ));
    }
    let size = std::fs::metadata(&config_path)
        .map_err(|e| crate::safety::fs_error("logrotate_run", &config_path, &e))?
        .len();
    if size > LOGROTATE_CONFIG_MAX {
        return Err(crate::safety::budget_exceeded(
            "logrotate_run",
            format!("the configuration is {size} bytes; the limit is {LOGROTATE_CONFIG_MAX}"),
            "split the configuration or shorten it",
        ));
    }
    let text = read_text_capped("logrotate_run", &config_path)?;
    logrotate_config_check("logrotate_run", &text)?;
    let dir = config_path
        .parent()
        .map(std::path::Path::to_path_buf)
        .unwrap_or_else(workspace_root_abs);
    let mut state_os = config_path.clone().into_os_string();
    state_os.push(".state");
    let state_arg = std::path::PathBuf::from(state_os).display().to_string();
    let config_arg = config_path.display().to_string();
    let mut argv: Vec<&str> = vec!["-s", state_arg.as_str()];
    if force {
        argv.push("-f");
    }
    argv.push(config_arg.as_str());
    let run = tool_run(
        "logrotate_run",
        "logrotate",
        Some(dir.as_path()),
        &argv,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_DEADLINE_SECS,
    )?;
    let run = finished("logrotate_run", run)?;
    let mut rec = BTreeMap::new();
    rec.insert("config".to_string(), Value::Str(config));
    rec.insert("state".to_string(), Value::Str(state_arg));
    rec.insert("forced".to_string(), Value::Bool(force));
    rec.insert(
        "stdout".to_string(),
        Value::Str(run.stdout.trim().to_string()),
    );
    rec.insert("stderr".to_string(), Value::Str(run.stderr.clone()));
    Ok(Value::Record(rec))
}

// --- ltrace (1008) ---

/// ltrace — Trace library calls of one program, counted with ltrace -c.
/// Usage: ltrace_cmd(command). The command is split on whitespace and run
/// directly, with no shell; the program may not begin with '-'. Returns
/// {command, exit_code, stdout, trace, stdout_truncated}. The exit code is the
/// traced program's and is data. A missing ltrace is E_TOOL_MISSING.
fn bi_ltrace_cmd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("ltrace_cmd", &input)?;
    k8s_max_args("ltrace_cmd", &args, 1)?;
    let command = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("ltrace requires a command to trace")),
    };
    let words = argv_words("ltrace_cmd", &command)?;
    crate::safety::guard_exec("ltrace", &command)?;
    let mut argv: Vec<&str> = vec!["-c", "--"];
    argv.extend(words.iter().map(String::as_str));
    let run = tool_run_stderr(
        "ltrace_cmd",
        "ltrace",
        None,
        &argv,
        Keep::Tail(TOOL_MAX_TEXT),
        TOOL_MAX_TEXT,
        TOOL_DEADLINE_SECS,
    )?;
    let mut rec = BTreeMap::new();
    rec.insert("command".to_string(), Value::Str(command));
    rec.insert("exit_code".to_string(), Value::Int(exit_code_of(&run)));
    rec.insert("stdout".to_string(), Value::Str(run.stdout.clone()));
    rec.insert("trace".to_string(), Value::Str(run.stderr.clone()));
    rec.insert(
        "stdout_truncated".to_string(),
        Value::Bool(run.stdout_truncated),
    );
    Ok(Value::Record(rec))
}

// --- valgrind (1009-1010) ---

/// valgrind — Run a program under memcheck.
/// Usage: valgrind_run(program)
/// The program is one argument, not option-like, and runs with no arguments of
/// its own. Its effect is Exec. A nonzero exit is E_TOOL_FAILED with the tail of
/// the valgrind report.
fn bi_valgrind_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    devtool_valgrind("valgrind_run", &["--tool=memcheck"], &args, input)
}

/// valgrind memcheck — Run a program under memcheck with full leak checking.
/// Usage: valgrind_memcheck(program)
/// The same argument rules as valgrind_run; adds --leak-check=full and
/// --show-leak-kinds=all. Its effect is Exec.
fn bi_valgrind_memcheck(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    devtool_valgrind(
        "valgrind_memcheck",
        &[
            "--tool=memcheck",
            "--leak-check=full",
            "--show-leak-kinds=all",
        ],
        &args,
        input,
    )
}

// --- gdb (1011-1012) ---

/// gdb run — Run a program under gdb in batch mode.
/// Usage: gdb_run(program) or gdb_run(program, commands)
/// `commands` is one gdb command per line (default "run", "bt", "quit"); each
/// becomes one -ex argument. gdb can run shell commands, so the call is
/// approval-gated as an exec. A nonzero exit is E_TOOL_FAILED.
fn bi_gdb_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("gdb_run", &input)?;
    let program = k8s_need("gdb_run", "program path", &args, 0, tf_plain)?;
    let commands = match k8s_arg("gdb_run", "gdb commands", &args, 1, devtool_text_arg)? {
        Some(text) => devtool_gdb_commands("gdb_run", &text)?,
        None => vec!["run".to_string(), "bt".to_string(), "quit".to_string()],
    };
    let mut argv: Vec<String> = vec!["--batch".to_string()];
    for cmd in commands {
        argv.push("-ex".to_string());
        argv.push(cmd);
    }
    argv.push(program.clone());
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = finished(
        "gdb_run",
        tool_run(
            "gdb_run",
            "gdb",
            None,
            &refs,
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "output", "stderr");
    rec.insert("program".to_string(), Value::Str(program));
    Ok(Value::Record(rec))
}

/// gdb backtrace — Print the full backtrace from a core file.
/// Usage: gdb_bt(program, core_file)
/// Both paths are required, not option-like, and the core file must exist. The
/// backtrace keeps its last 4 MiB. A nonzero exit is E_TOOL_FAILED.
fn bi_gdb_bt(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("gdb_bt", &input)?;
    let program = k8s_need("gdb_bt", "program path", &args, 0, tf_plain)?;
    let corefile = k8s_need("gdb_bt", "core file path", &args, 1, tf_plain)?;
    if !std::path::Path::new(&corefile).is_file() {
        return Err(crate::safety::not_found("gdb_bt", "core file", &corefile));
    }
    let run = finished(
        "gdb_bt",
        tool_run(
            "gdb_bt",
            "gdb",
            None,
            &[
                "--batch",
                "-ex",
                "bt full",
                program.as_str(),
                corefile.as_str(),
            ],
            Keep::Tail(TOOL_MAX_TEXT),
            TOOL_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "backtrace", "stderr");
    rec.insert("program".to_string(), Value::Str(program));
    rec.insert("core".to_string(), Value::Str(corefile));
    Ok(Value::Record(rec))
}

// --- lldb (1013) ---

/// lldb — Run a program under LLDB in batch mode and return LLDB's report.
/// Usage: lldb_run(program). The program must be an existing file, and its path
/// may not begin with '-'. LLDB runs the program, prints a backtrace if it stops,
/// and quits. Stdin is closed, and the call has a 120 s deadline. A nonzero exit
/// is E_TOOL_FAILED with the tail of stderr; a missing lldb is E_TOOL_MISSING.
fn bi_lldb_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("lldb_run", &input)?;
    k8s_max_args("lldb_run", &args, 1)?;
    let program = k8s_need("lldb_run", "a program path", &args, 0, tf_plain)?;
    if !std::path::Path::new(&program).is_file() {
        return Err(crate::safety::not_found("lldb_run", "program", &program));
    }
    let argv = [
        "--batch",
        "-o",
        "run",
        "-o",
        "bt",
        "-o",
        "quit",
        program.as_str(),
    ];
    let run = tool_run(
        "lldb_run",
        "lldb",
        None,
        &argv,
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_DEADLINE_SECS,
    )?;
    let output = tool_text("lldb_run", run)?;
    let mut rec = BTreeMap::new();
    rec.insert("program".to_string(), Value::Str(program));
    rec.insert("output".to_string(), Value::Str(output.trim().to_string()));
    Ok(Value::Record(rec))
}

// --- objdump (1014-1015) ---

/// objdump disassemble — Disassemble a binary.
fn bi_objdump_disasm(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "objdump_disasm requires a binary path",
            ))
        }
    };
    // The path goes to objdump positionally; a leading `-` would be an option.
    crate::safety::reject_option_like("objdump_disasm", std::slice::from_ref(&path))?;
    let mut cmd = crate::safety::child_command("objdump");
    cmd.args(["-d", &path]);
    let output = bounded_cmd_output("objdump_disasm", "objdump", cmd, TOOL_DEADLINE_SECS);
    match output {
        // A failed run answered {success: false, ...} at exit 0: a missing or
        // non-binary file read as an inspection result.
        Ok(o) if !o.status.success() => Err(crate::safety::tool_failed(
            "objdump_disasm",
            "objdump",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        Ok(o) => {
            let mut rec = BTreeMap::new();
            rec.insert("path".to_string(), Value::Str(path));
            rec.insert(
                "disassembly".to_string(),
                Value::Str(String::from_utf8_lossy(&o.stdout).to_string()),
            );
            Ok(Value::Record(rec))
        }
        Err(e) => Err(crate::safety::tool_missing(
            "objdump",
            "objdump",
            &e.to_string(),
        )),
    }
}

/// objdump headers — Show binary headers.
fn bi_objdump_headers(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "objdump_headers requires a binary path",
            ))
        }
    };
    // The path goes to objdump positionally; a leading `-` would be an option.
    crate::safety::reject_option_like("objdump_headers", std::slice::from_ref(&path))?;
    let mut cmd = crate::safety::child_command("objdump");
    cmd.args(["-h", &path]);
    let output = bounded_cmd_output("objdump_headers", "objdump", cmd, TOOL_DEADLINE_SECS);
    match output {
        // A failed run answered {success: false, ...} at exit 0: a missing or
        // non-binary file read as an inspection result.
        Ok(o) if !o.status.success() => Err(crate::safety::tool_failed(
            "objdump_headers",
            "objdump",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        Ok(o) => {
            let mut rec = BTreeMap::new();
            rec.insert("path".to_string(), Value::Str(path));
            rec.insert(
                "headers".to_string(),
                Value::Str(String::from_utf8_lossy(&o.stdout).trim().to_string()),
            );
            Ok(Value::Record(rec))
        }
        Err(e) => Err(crate::safety::tool_missing(
            "objdump",
            "objdump",
            &e.to_string(),
        )),
    }
}

// --- nm (1016) ---

/// nm — list the symbols of an object file or executable.
/// Usage: nm_symbols(path). Returns an Array of {address, type, name}, with the
/// demangled name. An undefined symbol has no address, so its address is null.
/// The path must be an existing file and may not begin with '-'. Output past
/// 4 MiB is E_BUDGET_EXCEEDED; a missing nm is E_TOOL_MISSING.
fn bi_nm_symbols(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("nm_symbols", &input)?;
    k8s_max_args("nm_symbols", &args, 1)?;
    let path = k8s_need("nm_symbols", "an object file path", &args, 0, tf_plain)?;
    if !std::path::Path::new(&path).is_file() {
        return Err(crate::safety::not_found("nm_symbols", "object file", &path));
    }
    let run = tool_run(
        "nm_symbols",
        "nm",
        None,
        &["--demangle", path.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let text = tool_text("nm_symbols", run)?;
    Ok(Value::Array(
        text.lines()
            .filter(|l| !l.trim().is_empty())
            .map(nm_record)
            .collect(),
    ))
}

// --- readelf (1017-1018) ---

/// readelf headers — Show ELF file headers.
fn bi_readelf_headers(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "readelf_headers requires an ELF file path",
            ))
        }
    };
    // The path goes to readelf positionally; a leading `-` would be an option.
    crate::safety::reject_option_like("readelf_headers", std::slice::from_ref(&path))?;
    let mut cmd = crate::safety::child_command("readelf");
    cmd.args(["-h", &path]);
    let output = bounded_cmd_output("readelf_headers", "readelf", cmd, TOOL_DEADLINE_SECS);
    match output {
        // A failed run answered {success: false, ...} at exit 0: a missing or
        // non-binary file read as an inspection result.
        Ok(o) if !o.status.success() => Err(crate::safety::tool_failed(
            "readelf_headers",
            "readelf",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        Ok(o) => {
            let mut rec = BTreeMap::new();
            rec.insert("path".to_string(), Value::Str(path));
            rec.insert(
                "headers".to_string(),
                Value::Str(String::from_utf8_lossy(&o.stdout).trim().to_string()),
            );
            Ok(Value::Record(rec))
        }
        Err(e) => Err(crate::safety::tool_missing(
            "readelf",
            "readelf",
            &e.to_string(),
        )),
    }
}

/// readelf sections — Show ELF section headers.
fn bi_readelf_sections(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "readelf_sections requires an ELF file path",
            ))
        }
    };
    // The path goes to readelf positionally; a leading `-` would be an option.
    crate::safety::reject_option_like("readelf_sections", std::slice::from_ref(&path))?;
    let mut cmd = crate::safety::child_command("readelf");
    cmd.args(["-S", &path]);
    let output = bounded_cmd_output("readelf_sections", "readelf", cmd, TOOL_DEADLINE_SECS);
    match output {
        // A failed run answered {success: false, ...} at exit 0: a missing or
        // non-binary file read as an inspection result.
        Ok(o) if !o.status.success() => Err(crate::safety::tool_failed(
            "readelf_sections",
            "readelf",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        Ok(o) => {
            let mut rec = BTreeMap::new();
            rec.insert("path".to_string(), Value::Str(path));
            rec.insert(
                "sections".to_string(),
                Value::Str(String::from_utf8_lossy(&o.stdout).trim().to_string()),
            );
            Ok(Value::Record(rec))
        }
        Err(e) => Err(crate::safety::tool_missing(
            "readelf",
            "readelf",
            &e.to_string(),
        )),
    }
}

// --- strings (1019) ---

/// strings — Extract printable strings from a binary file.
fn bi_strings_extract(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    // In-process on every OS, reading the file through the read checks. This
    // ran the `strings` program (absent on Windows, and handed the path
    // positionally) and fell back to this scan on any failure; the fallback's
    // errors were labelled `bat`; and a negative minimum became a huge usize,
    // so nothing matched.
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "strings",
                "path: String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    let min_len = match args.get(1) {
        None => 4,
        Some(Value::Int(n)) if (1..=4096).contains(n) => *n as usize,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "strings",
                "a minimum length from 1 to 4096",
                &other.to_display_string(),
            ))
        }
    };
    let validated = validate_read_path(&path)?;
    let data = read_bytes_capped("strings", &validated)?;
    let mut result = Vec::new();
    let mut current = String::new();
    for &byte in &data {
        // Printable ASCII and tab, as GNU strings counts them.
        if (0x20..0x7f).contains(&byte) || byte == 0x09 {
            current.push(byte as char);
        } else {
            if current.len() >= min_len {
                result.push(Value::Str(std::mem::take(&mut current)));
            }
            current.clear();
        }
    }
    if current.len() >= min_len {
        result.push(Value::Str(current));
    }
    Ok(Value::Array(result))
}

// --- chgrp (1020) ---

/// chgrp — Change the group of one file.
/// Usage: chgrp(group, path). The group is a name or numeric id and may not begin
/// with '-'; the path must exist and is passed after `--`. The result is
/// {group, path}. A refusal by chgrp (unknown group, not permitted) is
/// E_TOOL_FAILED. On Windows the group is an account name set as the file's
/// primary group through the security API (see chgrp_windows).
///
/// It used to answer `success: false` as a value when chgrp refused, ignore
/// surplus arguments and pipeline input, and run with no deadline.
fn bi_chgrp(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("chgrp", &input)?;
    k8s_max_args("chgrp", &args, 2)?;
    let group = k8s_need("chgrp", "a group name", &args, 0, tf_plain)?;
    let path = match args.get(1) {
        Some(Value::Str(s)) if !s.is_empty() && !s.contains('\0') => s.clone(),
        other => {
            return Err(crate::safety::bad_arg(
                "chgrp",
                "path: a non-empty String",
                other.map(|v| v.type_name()).unwrap_or("nothing"),
            ))
        }
    };
    #[cfg(windows)]
    {
        chgrp_windows(group, path)
    }
    #[cfg(not(windows))]
    {
        chgrp_unix(group, path)
    }
}

#[cfg(not(windows))]
fn chgrp_unix(group: String, path: String) -> Result<Value> {
    // Jailed as the Windows branch is; this one had no guard.
    let target = guard_local_write("chgrp", &path)?;
    if std::fs::symlink_metadata(&target).is_err() {
        return Err(crate::safety::not_found("chgrp", "file", &path));
    }
    let run = tool_run(
        "chgrp",
        "chgrp",
        None,
        &["--", &group, &target],
        Keep::Tail(TOOL_STDERR_TAIL),
        TOOL_DEADLINE_SECS,
    )?;
    if !run.success {
        return Err(crate::safety::tool_failed(
            "chgrp",
            &run.command,
            run.code,
            &run.stderr,
        ));
    }
    let mut rec = BTreeMap::new();
    rec.insert("group".to_string(), Value::Str(group));
    rec.insert("path".to_string(), Value::Str(path));
    Ok(Value::Record(rec))
}

// --- mtr (1021) ---

/// mtr — Network diagnostic tool combining traceroute and ping.
/// Usage: mtr_trace(host) or mtr_trace(host, cycles). The host is a name or IP
/// literal and may not begin with '-'. cycles is 1..=100 and defaults to 5. The
/// result is {host, report}. A nonzero exit is E_TOOL_FAILED; a missing mtr is
/// E_TOOL_MISSING. The run has a 120 s deadline.
fn bi_mtr_trace(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    net_refuse_in_transaction("mtr_trace")?;
    k8s_no_input("mtr_trace", &input)?;
    k8s_max_args("mtr_trace", &args, 2)?;
    let host = k8s_need("mtr_trace", "a hostname", &args, 0, net_target_host)?;
    let cycles = match args.get(1) {
        None => 5,
        Some(Value::Int(n)) if (1..=100).contains(n) => *n,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "mtr_trace",
                "cycles: Int 1..=100",
                other.type_name(),
            ))
        }
    };
    let cycles_s = cycles.to_string();
    let run = tool_run(
        "mtr_trace",
        "mtr",
        None,
        &[
            "--report",
            "--report-cycles",
            cycles_s.as_str(),
            host.as_str(),
        ],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let report = tool_text("mtr_trace", run)?;
    let mut rec = BTreeMap::new();
    rec.insert("host".to_string(), Value::Str(host));
    rec.insert("report".to_string(), Value::Str(report.trim().to_string()));
    Ok(Value::Record(rec))
}

// --- host (1022) ---

/// host — DNS lookup utility.
/// Usage: host_lookup(hostname). The name is a host name or IP literal and may
/// not begin with '-'. Returns {hostname, result}, where result is the resolver
/// tool's text. A lookup the resolver reports as failed is E_TOOL_FAILED; a
/// missing resolver tool is E_TOOL_MISSING.
fn bi_host_lookup(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    net_refuse_in_transaction("host_lookup")?;
    k8s_no_input("host_lookup", &input)?;
    k8s_max_args("host_lookup", &args, 1)?;
    let hostname = k8s_need("host_lookup", "a hostname", &args, 0, net_target_host)?;
    let tool = if cfg!(windows) { "nslookup" } else { "host" };
    let run = tool_run(
        "host_lookup",
        tool,
        None,
        &[hostname.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let result = tool_text("host_lookup", run)?;
    let mut rec = BTreeMap::new();
    rec.insert("hostname".to_string(), Value::Str(hostname));
    rec.insert("result".to_string(), Value::Str(result.trim().to_string()));
    Ok(Value::Record(rec))
}

// --- nc/netcat (1023-1024) ---

/// nc connect — Test whether a TCP port accepts a connection, using netcat.
/// Usage: nc_connect(host, port). The port is an Int 1..=65535 and the host is a
/// name or IP literal that may not begin with '-'. Returns {host, port, open,
/// output}. A refused or unanswered connection is open false: that is the answer.
/// Any other netcat failure is E_TOOL_FAILED, and a missing netcat is E_TOOL_MISSING.
fn bi_nc_connect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    net_refuse_in_transaction("nc_connect")?;
    k8s_no_input("nc_connect", &input)?;
    k8s_max_args("nc_connect", &args, 2)?;
    let host = k8s_need("nc_connect", "a host", &args, 0, net_target_host)?;
    let port = match args.get(1) {
        Some(Value::Int(n)) => net_port("nc_connect", *n)?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "nc_connect",
                "port: Int 1..=65535",
                other.type_name(),
            ))
        }
        None => return Err(crate::safety::arg_err("nc_connect requires a port")),
    };
    let port_s = port.to_string();
    let run = tool_run_stderr(
        "nc_connect",
        "nc",
        None,
        &["-z", "-v", "-w", "5", host.as_str(), port_s.as_str()],
        Keep::Tail(NET_ERR_MAX),
        NET_ERR_MAX,
        TOOL_DEADLINE_SECS,
    )?;
    let text = format!("{}{}", run.stdout, run.stderr).trim().to_string();
    let open = if run.success {
        true
    } else if nc_refusal(&text) {
        false
    } else {
        return Err(crate::safety::tool_failed(
            "nc_connect",
            &run.command,
            run.code,
            &run.stderr,
        ));
    };
    let mut rec = BTreeMap::new();
    rec.insert("host".to_string(), Value::Str(host));
    rec.insert("port".to_string(), Value::Int(port));
    rec.insert("open".to_string(), Value::Bool(open));
    rec.insert("output".to_string(), Value::Str(text));
    Ok(Value::Record(rec))
}

/// nc_listen — accept one TCP connection on a port, read it to EOF or a byte
/// limit, then close both. Binds 127.0.0.1 unless `host` is given. The bind
/// address and the accepted peer pass the same network policy as net_listen,
/// and `timeout_ms` bounds the whole call (accept and read), so a stalled peer
/// is an E_IO error rather than a silent short read.
fn bi_nc_listen(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const NAME: &str = "nc_listen";
    if input.is_some() || !(1..=2).contains(&args.len()) {
        return Err(crate::safety::arg_err(
            "nc_listen requires a port and optional options Record, without pipeline input",
        ));
    }
    let mut args = args.into_iter();
    let port = match args.next() {
        Some(Value::Int(n)) if (1..=65535).contains(&n) => n as u16,
        _ => {
            return Err(crate::safety::arg_err(
                "nc_listen port must be an Int 1..65535",
            ))
        }
    };
    let mut host: std::net::IpAddr = std::net::Ipv4Addr::LOCALHOST.into();
    let mut timeout_ms: i64 = 1000;
    let mut max_bytes: i64 = 65536;
    if let Some(options) = args.next() {
        let Value::Record(fields) = options else {
            return Err(crate::safety::arg_err("nc_listen options must be a Record"));
        };
        for (key, value) in fields {
            match (key.as_str(), value) {
                ("host", Value::Str(text)) => {
                    host = text.parse().map_err(|_| {
                        crate::safety::arg_err(
                            "nc_listen host must be a literal IPv4 or IPv6 address; resolve hostnames separately",
                        )
                    })?;
                }
                ("timeout_ms", Value::Int(n)) if (1..=10000).contains(&n) => timeout_ms = n,
                ("max_bytes", Value::Int(n)) if (1..=1048576).contains(&n) => max_bytes = n,
                (other, _) => {
                    return Err(crate::safety::arg_err(format!(
                        "nc_listen unknown option or out-of-range value: {other} (options: host String, timeout_ms 1..10000, max_bytes 1..1048576)"
                    )))
                }
            }
        }
    }
    if crate::tx::is_active() {
        return Err(crate::safety::unimplemented(
            NAME,
            "network effects and reads cannot be rolled back",
            "finish the transaction first",
        ));
    }
    let addr = std::net::SocketAddr::new(host, port);
    crate::safety::refuse_remote_bind(NAME, host)?;
    guard_network(NAME, &format!("tcp://{addr}"))?;
    let io_timeout = crate::safety::bounded_io_timeout(
        NAME,
        std::time::Duration::from_millis(timeout_ms as u64),
    )?;
    let deadline = std::time::Instant::now() + io_timeout;
    let limit = max_bytes as usize;

    let listener = std::net::TcpListener::bind(addr).map_err(|e| nc_io_error(NAME, e))?;
    listener
        .set_nonblocking(true)
        .map_err(|e| nc_io_error(NAME, e))?;
    let (mut stream, peer) = loop {
        crate::safety::check_deadline()?;
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        if remaining.is_zero() {
            return Err(nc_io_error(
                NAME,
                std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "no connection accepted before timeout",
                ),
            ));
        }
        match listener.accept() {
            Ok(pair) => break pair,
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                std::thread::sleep(remaining.min(std::time::Duration::from_millis(5)));
            }
            Err(e) => return Err(nc_io_error(NAME, e)),
        }
    };
    drop(listener);
    // The bind address does not authorize an arbitrary incoming peer.
    guard_network(NAME, &format!("tcp://{peer}"))?;
    stream
        .set_nonblocking(false)
        .map_err(|e| nc_io_error(NAME, e))?;

    let mut data: Vec<u8> = Vec::new();
    let mut chunk = [0u8; 8192];
    let mut truncated = false;
    loop {
        crate::safety::check_deadline()?;
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        if remaining.is_zero() {
            return Err(nc_io_error(
                NAME,
                std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "read deadline exceeded before EOF",
                ),
            ));
        }
        stream
            .set_read_timeout(Some(remaining.min(std::time::Duration::from_millis(50))))
            .map_err(|e| nc_io_error(NAME, e))?;
        match std::io::Read::read(&mut stream, &mut chunk) {
            Ok(0) => break,
            Ok(n) => {
                // One byte past the limit proves more data existed, so truncated is exact.
                let room = limit + 1 - data.len();
                data.extend_from_slice(&chunk[..n.min(room)]);
                if data.len() > limit {
                    data.truncate(limit);
                    truncated = true;
                    break;
                }
            }
            Err(e)
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::Interrupted
                        | std::io::ErrorKind::TimedOut
                        | std::io::ErrorKind::WouldBlock
                ) => {}
            Err(e) => return Err(nc_io_error(NAME, e)),
        }
    }
    drop(stream);

    let mut rec = BTreeMap::new();
    rec.insert("peer".to_string(), Value::Str(format!("tcp://{peer}")));
    rec.insert(
        "data".to_string(),
        Value::Str(String::from_utf8_lossy(&data).into_owned()),
    );
    rec.insert("bytes".to_string(), Value::Int(data.len() as i64));
    rec.insert("truncated".to_string(), Value::Bool(truncated));
    Ok(Value::Record(rec))
}

fn nc_io_error(name: &str, error: std::io::Error) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code: crate::safety::ErrorCode::Io,
        builtin: name.into(),
        message: format!("{name}: {error}"),
        hint: "A timeout before EOF is an error, not a short read; the partial data was discarded."
            .into(),
        approval: None,
        did_you_mean: vec![],
        expected: "one complete TCP connection".into(),
        got: format!("{:?}", error.kind()),
        extra: serde_json::Map::new(),
    })
}

// --- socat (1025) ---

/// socat — Multipurpose relay between two outbound connections.
/// Usage: socat_relay(address1, address2), with addresses such as "TCP:host:port"
/// or "UDP4:host:port". Only TCP, TCP4, UDP and UDP4 connections to a host and
/// port are accepted, with no options; EXEC, SYSTEM and SHELL run programs, OPEN
/// and CREATE write files, and LISTEN forms open listeners, so they are refused.
/// The relay has a 120 s deadline and is killed at it, so no relay outlives the
/// call. Returns {addr1, addr2, stdout, stdout_truncated}.
fn bi_socat_relay(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    net_refuse_in_transaction("socat_relay")?;
    k8s_no_input("socat_relay", &input)?;
    if args.len() != 2 {
        return Err(crate::safety::arg_err(
            "socat_relay takes exactly two addresses",
        ));
    }
    let (Some(Value::Str(a)), Some(Value::Str(b))) = (args.first(), args.get(1)) else {
        return Err(crate::safety::arg_err(
            "socat_relay addresses must be Strings",
        ));
    };
    let first = socat_address("socat_relay", a)?;
    let second = socat_address("socat_relay", b)?;
    let run = tool_run_stderr(
        "socat_relay",
        "socat",
        None,
        &[first.as_str(), second.as_str()],
        Keep::Tail(TOOL_MAX_TEXT),
        NET_ERR_MAX,
        TOOL_DEADLINE_SECS,
    )?;
    let run = finished("socat_relay", run)?;
    let mut rec = BTreeMap::new();
    rec.insert("addr1".to_string(), Value::Str(first));
    rec.insert("addr2".to_string(), Value::Str(second));
    rec.insert(
        "stdout".to_string(),
        Value::Str(run.stdout.trim().to_string()),
    );
    rec.insert(
        "stdout_truncated".to_string(),
        Value::Bool(run.stdout_truncated),
    );
    Ok(Value::Record(rec))
}

// --- iperf3 (1026-1027) ---

/// Bounded runs of long-running tools (iperf3 server, entr, watchexec, nodemon).
#[path = "tool_runs.rs"]
mod tool_runs;

/// PE file version from the VS_FIXEDFILEINFO of a Windows image (platform_libcpp).
#[cfg(any(windows, test))]
#[path = "pe_version.rs"]
mod pe_version;

/// iperf3 server — run one iperf3 test as a server, bounded by timeout_ms.
fn bi_iperf3_server(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tool_runs::iperf3_server(args, input)
}

/// iperf3_client — run one iperf3 bandwidth test against a server, as a client.
/// Usage: iperf3_client(host) or iperf3_client(host, port). The port is 1..=65535
/// and defaults to 5201. The host may not begin with '-'. The test runs with
/// JSON output, and its report is returned as a Record. A failed test is
/// E_TOOL_FAILED; a missing iperf3 is E_TOOL_MISSING; the run has a 120 s deadline.
fn bi_iperf3_client(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    net_refuse_in_transaction("iperf3_client")?;
    k8s_no_input("iperf3_client", &input)?;
    k8s_max_args("iperf3_client", &args, 2)?;
    let host = k8s_need("iperf3_client", "a server host", &args, 0, net_target_host)?;
    let port = match args.get(1) {
        None => IPERF3_PORT,
        Some(Value::Int(n)) => net_port("iperf3_client", *n)?,
        Some(other) => {
            return Err(crate::safety::bad_arg(
                "iperf3_client",
                "port: Int 1..=65535",
                other.type_name(),
            ))
        }
    };
    let port_s = port.to_string();
    let run = tool_run_stderr(
        "iperf3_client",
        "iperf3",
        None,
        &["-c", host.as_str(), "-p", port_s.as_str(), "-J"],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_STDERR_TAIL,
        TOOL_DEADLINE_SECS,
    )?;
    tool_json("iperf3_client", run)
}

// --- bat (1028) ---

/// bat — Cat clone with syntax highlighting.
fn bi_bat_view(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if input.is_some() || args.len() != 1 {
        return Err(crate::safety::arg_err(
            "bat requires one direct file path and no pipeline input",
        ));
    }
    let Some(Value::Str(path)) = args.into_iter().next() else {
        return Err(crate::safety::arg_err("bat path must be String"));
    };
    let path = crate::safety::resolve_path_str(&path);
    crate::safety::guard(crate::safety::GuardCtx {
        builtin: "bat_view",
        effect: crate::safety::Effect::ReadLocal,
        what: "read plain file text",
        targets: vec![path.clone()],
        blast_radius: serde_json::json!({"files":1}),
        reversible: true,
        fs_paths: true,
    })?;
    Ok(Value::Str(line_read("bat", &path)?))
}

// --- eza (1029) ---

/// eza — Modern replacement for ls.
fn bi_eza_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "eza_list";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, ".")?;
    let run = tool_run(
        B,
        "eza",
        None,
        &[
            "-la",
            "--git",
            "--no-user",
            "--time-style=long-iso",
            path.as_str(),
        ],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let text = tool_text(B, run)?;
    search_list(
        B,
        text.lines()
            .filter(|l| !l.is_empty())
            .map(str::to_string)
            .collect(),
    )
}

// --- zoxide (1030-1031) ---

/// zoxide add — Record a directory in the user's zoxide database.
/// Usage: zoxide_add() or zoxide_add(path)
/// The path defaults to ".", must exist as a directory, and is one word that is
/// not option-like. This writes the user's zoxide database, which lies outside
/// the workspace; it does not touch the directory itself.
fn bi_zoxide_add(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("zoxide_add", &input)?;
    let path =
        k8s_arg("zoxide_add", "directory", &args, 0, tf_plain)?.unwrap_or_else(|| ".".to_string());
    if !std::path::Path::new(&path).is_dir() {
        return Err(crate::safety::not_found("zoxide_add", "directory", &path));
    }
    let run = finished(
        "zoxide_add",
        tool_run(
            "zoxide_add",
            "zoxide",
            None,
            &["add", path.as_str()],
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("path".to_string(), Value::Str(path));
    Ok(Value::Record(rec))
}

/// zoxide query — The best directory in zoxide's database for a search term.
/// Usage: zoxide_query(term)
/// Answers a path string. No match is E_NOT_FOUND: zoxide exits nonzero with
/// nothing on stderr when it has no match, and anything else it says on
/// failure is E_TOOL_FAILED. The term is one word, not option-like.
fn bi_zoxide_query(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("zoxide_query", &input)?;
    let term = k8s_need("zoxide_query", "search term", &args, 0, tf_plain)?;
    let run = tool_run(
        "zoxide_query",
        "zoxide",
        None,
        &["query", term.as_str()],
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_DEADLINE_SECS,
    )?;
    if !run.success && run.stderr.trim().is_empty() {
        return Err(crate::safety::not_found(
            "zoxide_query",
            "directory matching",
            &term,
        ));
    }
    let run = finished("zoxide_query", run)?;
    let path = run.stdout.trim().to_string();
    if path.is_empty() {
        return Err(crate::safety::not_found(
            "zoxide_query",
            "directory matching",
            &term,
        ));
    }
    Ok(Value::Str(path))
}

// --- delta (1032) ---

/// delta — Syntax-highlighting diff viewer.
fn bi_delta_diff(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "delta_diff";
    pkg_shape(B, &args, &input, 2)?;
    let file_a = k8s_need(B, "two file paths", &args, 0, pkg_plain)?;
    let file_b = k8s_need(B, "two file paths", &args, 1, pkg_plain)?;
    for file in [&file_a, &file_b] {
        pkg_inside(B, file)?;
        let meta = std::fs::metadata(file).map_err(|e| devtool_io(B, "file", file, &e))?;
        if !meta.is_file() {
            return Err(crate::safety::not_found(B, "file", file));
        }
    }
    let run = tool_run(
        B,
        "delta",
        None,
        &[file_a.as_str(), file_b.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let diff = tool_text(B, run)?;
    let mut rec = BTreeMap::new();
    rec.insert("file_a".to_string(), Value::Str(file_a));
    rec.insert("file_b".to_string(), Value::Str(file_b));
    rec.insert("diff".to_string(), Value::Str(diff));
    rec.insert("success".to_string(), Value::Bool(true));
    Ok(Value::Record(rec))
}

// --- lazygit (1033) ---

/// `lazygit_open(path?)`: runs `lazygit -p <path>` with the terminal inherited
/// and waits for it to exit. Needs stdin and stdout to be terminals; otherwise
/// it refuses with E_NO_UI. The path is validated first, so a bad path is
/// refused the same way with or without a terminal.
fn bi_lazygit_open(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const BUILTIN: &str = "lazygit_open";
    if input.is_some() {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "no pipeline input",
            "a piped value",
        ));
    }
    let path = match args.as_slice() {
        [] => ".".to_string(),
        [Value::Str(s)] => s.clone(),
        [other] => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "lazygit_open(path?: String)",
                &format!("{other:?}"),
            ))
        }
        more => {
            return Err(crate::safety::bad_arg(
                BUILTIN,
                "lazygit_open(path?: String)",
                &format!("{} arguments", more.len()),
            ))
        }
    };
    crate::safety::reject_option_like(BUILTIN, std::slice::from_ref(&path))?;
    let meta = match std::fs::metadata(&path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(crate::safety::not_found(BUILTIN, "directory", &path))
        }
        Err(e) => return Err(crate::safety::fs_error(BUILTIN, &path, &e)),
    };
    if !meta.is_dir() {
        return Err(crate::safety::bad_arg(
            BUILTIN,
            "a directory path",
            &format!("{path}, which is not a directory"),
        ));
    }
    use std::io::IsTerminal;
    if !(std::io::stdin().is_terminal() && std::io::stdout().is_terminal()) {
        return Err(crate::safety::no_ui(BUILTIN));
    }
    // stdio is inherited, so lazygit draws on the user's terminal. Its stderr
    // therefore cannot be captured for a tail; the failure carries only the
    // exit status.
    let mut cmd = crate::safety::child_command("lazygit");
    crate::safety::strip_ironshell_env(&mut cmd);
    let status = cmd
        .arg("-p")
        .arg(&path)
        .status()
        .map_err(|e| crate::safety::spawn_error(BUILTIN, "lazygit", &e))?;
    if !status.success() {
        return Err(crate::safety::tool_failed(
            BUILTIN,
            "lazygit",
            status.code(),
            "",
        ));
    }
    let mut rec = std::collections::BTreeMap::new();
    rec.insert("path".to_string(), Value::Str(path));
    rec.insert("exit_code".to_string(), Value::Int(0));
    Ok(Value::Record(rec))
}

// --- fzf (1034) ---

/// fzf — Filters piped items by a case-insensitive substring of the query. No fzf process
/// is started, so this is not fuzzy matching and offers no interactive picker: it never
/// needs a terminal and never blocks. Items must be piped in (E_BAD_ARG otherwise).
fn bi_fzf_select(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "fzf_select";
    k8s_max_args(B, &args, 1)?;
    let query = match args.first() {
        None => None,
        Some(Value::Str(q)) => {
            devtool_text_arg(B, "the query", q)?;
            Some(q.to_lowercase())
        }
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{B}: the query must be a String, got {}",
                other.type_name()
            )))
        }
    };
    let items: Vec<String> = match &input {
        // Display colours and quotes its output; a string item is its own text.
        Some(Value::Array(arr)) => arr
            .iter()
            .map(|v| match v {
                Value::Str(s) => s.clone(),
                other => other.to_json().to_string(),
            })
            .collect(),
        Some(Value::Str(s)) => s.lines().map(str::to_string).collect(),
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{B}: piped input must be an Array or a String, got {}",
                other.type_name()
            )))
        }
        None => {
            return Err(crate::safety::arg_err(format!(
                "{B} needs piped items, as in `items | {B}(query)`; it does not start an interactive picker"
            )))
        }
    };
    // A case-insensitive substring filter over the piped items. No process is
    // started, so no terminal is needed and nothing can block.
    let mut out = Vec::new();
    for item in items {
        let keep = match &query {
            Some(q) => item.to_lowercase().contains(q.as_str()),
            None => true,
        };
        if keep {
            out.push(Value::Str(item));
        }
    }
    Ok(Value::Array(out))
}

// --- rga (1035) ---

/// rga — ripgrep-all: search in PDFs, archives, etc.
fn bi_rga_search(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "rga_search";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let pattern = k8s_need(B, "a search pattern", &args, 0, search_text_check)?;
    let path = pkg_path_arg(B, &args, 1, ".")?;
    let regexp = format!("--regexp={pattern}");
    let run = tool_run(
        B,
        "rga",
        None,
        &["--json", regexp.as_str(), path.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    let command = run.command.clone();
    let text = stdout_with_exit1(B, run)?;
    let mut out = Vec::new();
    let mut matches = 0usize;
    for line in text.lines().filter(|l| !l.is_empty()) {
        let value = serde_json::from_str::<serde_json::Value>(line).map_err(|e| {
            crate::safety::tool_failed(
                B,
                &command,
                Some(0),
                &format!("printed a line that is not JSON ({e})"),
            )
        })?;
        if value.get("type").and_then(|t| t.as_str()) == Some("match") {
            matches += 1;
            if matches > SEARCH_MAX_RESULTS {
                return Err(search_budget(B));
            }
        }
        out.push(json_to_value(value));
    }
    Ok(Value::Array(out))
}

// --- sd (1036) ---

/// Native regex replacement independent of an installed sd executable.
fn bi_sd_replace(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    if (input.is_some() && args.len() != 2) || (input.is_none() && args.len() != 3) {
        return Err(crate::safety::arg_err(
            "sd requires pattern, replacement and direct or piped text, without conflicting input",
        ));
    }
    let mut args = args.into_iter();
    let Some(Value::Str(pattern)) = args.next() else {
        return Err(crate::safety::arg_err("sd requires pattern String"));
    };
    let Some(Value::Str(replacement)) = args.next() else {
        return Err(crate::safety::arg_err("sd requires replacement String"));
    };
    let Some(Value::Str(text)) = input.or_else(|| args.next()) else {
        return Err(crate::safety::arg_err("sd requires input String"));
    };
    let re = regex::Regex::new(&pattern)
        .map_err(|e| crate::safety::arg_err(format!("sd invalid regex: {e}")))?;
    Ok(Value::Str(regex_substitute(&re, &replacement, text, true)))
}

/// Reuse owned source text when a regex has no match.
fn regex_substitute(re: &regex::Regex, replacement: &str, source: String, global: bool) -> String {
    let replaced = if global {
        re.replace_all(&source, replacement)
    } else {
        re.replace(&source, replacement)
    };
    match replaced {
        std::borrow::Cow::Owned(result) => result,
        std::borrow::Cow::Borrowed(_) => source,
    }
}

// --- hyperfine (1037) ---

/// hyperfine — Command-line benchmarking tool.
fn bi_hyperfine_bench(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "hyperfine_bench";
    k8s_no_input(B, &input)?;
    let commands = pkg_each(B, "a command", &args, pkg_plain)?;
    if commands.is_empty() {
        return Err(crate::safety::arg_err(
            "hyperfine_bench requires at least one command to benchmark",
        ));
    }
    // --shell=none runs each command without a shell: hyperfine splits it into
    // words and runs the first, so no shell syntax is interpreted. The results
    // come back through a file, since a Windows host has no /dev/stdout.
    let export = scratch_file(B, "export.json", &[])?;
    let export_path = export.display().to_string();
    let mut argv: Vec<&str> = vec!["--shell=none", "--export-json", export_path.as_str()];
    argv.extend(commands.iter().map(String::as_str));
    let outcome = (|| -> Result<Value> {
        let run = pkg_run(B, "hyperfine", &argv, PKG_RUN_DEADLINE_SECS)?;
        pkg_output(B, run)?;
        let text = devtool_read_text(B, "export file", &export_path)?;
        serde_json::from_str::<serde_json::Value>(&text)
            .map(json_to_value)
            .map_err(|e| {
                crate::safety::tool_failed(
                    B,
                    "hyperfine",
                    Some(0),
                    &format!("exported output that is not JSON ({e})"),
                )
            })
    })();
    scratch_remove(&export);
    outcome
}

// --- tokei (1038) ---

/// tokei — Count lines of code by language.
fn bi_tokei_count(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "tokei_count";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, ".")?;
    let run = tool_run(
        B,
        "tokei",
        None,
        &["--output", "json", path.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    tool_json(B, run)
}

// --- entr (1039) ---

/// entr — Run a command at start and again on each change to the watched paths,
/// bounded by timeout_ms.
fn bi_entr_watch(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tool_runs::entr_watch(args, input)
}

// --- watchexec (1040) ---

/// watchexec — Run a command at start and on each change under the watched
/// paths (no shell), bounded by timeout_ms.
fn bi_watchexec_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tool_runs::watchexec_run(args, input)
}

// --- just (1041-1042) ---

/// just — Run a recipe from the justfile in the process's directory.
/// Usage: just_run(recipe) or just_run(recipe, arg...)
/// The recipe and each argument are one word, not option-like, and at most 256
/// arguments are passed. A recipe runs project code, so its effect is Exec. A
/// nonzero exit is E_TOOL_FAILED.
fn bi_just_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("just_run", &input)?;
    let recipe = k8s_need("just_run", "recipe name", &args, 0, devtool_word)?;
    let mut argv: Vec<String> = vec![recipe.clone()];
    for value in args.iter().skip(1) {
        match value {
            Value::Str(s) => argv.push(devtool_word("just_run", "a recipe argument", s)?),
            other => {
                return Err(crate::safety::arg_err(format!(
                    "just_run: recipe arguments must be Strings, got {}",
                    other.type_name()
                )))
            }
        }
    }
    if argv.len() - 1 > DEVTOOL_MAX_ITEMS {
        return Err(crate::safety::arg_err(format!(
            "just_run: at most {DEVTOOL_MAX_ITEMS} recipe arguments, got {}",
            argv.len() - 1
        )));
    }
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = finished(
        "just_run",
        tool_run(
            "just_run",
            "just",
            None,
            &refs,
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("recipe".to_string(), Value::Str(recipe));
    Ok(Value::Record(rec))
}

/// just list — The recipes in the justfile in the process's directory.
/// Usage: just_list()
/// Answers an Array of {name, description?} Records. A failure, such as no
/// justfile, is E_TOOL_FAILED; it is never returned as a string.
fn bi_just_list(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("just_list", &input)?;
    let run = tool_run(
        "just_list",
        "just",
        None,
        &["--list"],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let text = tool_text("just_list", run)?;
    let recipes: Vec<Value> = text
        .lines()
        .filter(|l| l.starts_with(char::is_whitespace) && !l.trim().is_empty())
        .map(|line| {
            let mut rec = BTreeMap::new();
            let mut parts = line.trim().splitn(2, '#');
            let name = parts.next().unwrap_or("").trim().to_string();
            rec.insert("name".to_string(), Value::Str(name));
            if let Some(desc) = parts.next() {
                rec.insert(
                    "description".to_string(),
                    Value::Str(desc.trim().to_string()),
                );
            }
            Value::Record(rec)
        })
        .collect();
    Ok(Value::Array(recipes))
}

// --- task (1043-1044) ---

/// task — Run a Taskfile task.
//
// The Taskfile's commands run inside `task`, under its own interpreter, so this
// is an exec of the task definition and is gated as Exec. The name goes to
// `task` positionally, so it is refused when it could be read as an option. The
// run is bounded in output and time, and stdin is closed, so a prompt cannot
// hang it. A nonzero exit is a coded failure with the stderr tail, not a record.
fn bi_task_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("task_run", &input)?;
    if args.len() != 1 {
        return Err(crate::safety::bad_arg(
            "task_run",
            "one task name",
            &format!("{} arguments", args.len()),
        ));
    }
    let task_name = match &args[0] {
        Value::Str(s) if !s.is_empty() && !s.chars().any(|c| c.is_whitespace() || c == '\0') => {
            s.clone()
        }
        other => {
            return Err(crate::safety::bad_arg(
                "task_run",
                "a task name: a non-empty string with no whitespace",
                other.type_name(),
            ))
        }
    };
    refuse_option("task_run", &task_name)?;

    let mut cmd = crate::safety::child_command("task");
    cmd.arg(&task_name);
    let (stdout, stderr) = run_checked("task_run", "task", cmd, LOCAL_DEADLINE_SECS)?;
    let mut rec = BTreeMap::new();
    rec.insert("task".to_string(), Value::Str(task_name));
    rec.insert("stdout".to_string(), Value::Str(stdout.trim().to_string()));
    rec.insert("stderr".to_string(), Value::Str(stderr.trim().to_string()));
    Ok(Value::Record(rec))
}

/// task list — List available tasks.
fn bi_task_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    refuse_piped("task_list", &input)?;
    if !args.is_empty() {
        return Err(crate::safety::bad_arg(
            "task_list",
            "no arguments",
            &format!("{} argument(s)", args.len()),
        ));
    }
    let mut cmd = crate::safety::child_command("task");
    cmd.arg("--list");
    let (stdout, _stderr) = run_checked("task_list", "task", cmd, LOCAL_DEADLINE_SECS)?;
    Ok(Value::Str(stdout.trim().to_string()))
}

// --- direnv (1045-1046) ---

/// direnv allow — Authorise an .envrc file so direnv loads it.
/// Usage: direnv_allow() or direnv_allow(path)
/// The path defaults to ".", is one word that is not option-like, must exist,
/// and must lie inside the workspace. Allowing an .envrc lets its code run on
/// every cd into that directory. The effect table classes direnv_allow as
/// write_local, so nothing asks for approval; that is reported, not changed.
fn bi_direnv_allow(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("direnv_allow", &input)?;
    let given =
        k8s_arg("direnv_allow", "path", &args, 0, tf_plain)?.unwrap_or_else(|| ".".to_string());
    let cwd = devtool_cwd("direnv_allow")?;
    let path = workspace_path("direnv_allow", &given, &cwd)?;
    if !path.exists() {
        return Err(crate::safety::not_found(
            "direnv_allow",
            "path",
            &path.display().to_string(),
        ));
    }
    let shown = path.display().to_string();
    let run = finished(
        "direnv_allow",
        tool_run(
            "direnv_allow",
            "direnv",
            None,
            &["allow", shown.as_str()],
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("path".to_string(), Value::Str(shown));
    Ok(Value::Record(rec))
}

/// direnv status — direnv's report on the current directory and its .envrc.
/// Usage: direnv_status()
/// Answers {status, success} with the report text. A failure is E_TOOL_FAILED.
fn bi_direnv_status(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("direnv_status", &input)?;
    let run = tool_run(
        "direnv_status",
        "direnv",
        None,
        &["status"],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    let text = tool_text("direnv_status", run)?;
    let mut rec = BTreeMap::new();
    rec.insert("status".to_string(), Value::Str(text.trim().to_string()));
    rec.insert("success".to_string(), Value::Bool(true));
    Ok(Value::Record(rec))
}

// --- asdf (1047-1048) ---

/// asdf list — Installed versions of a tool, or of every plugin.
/// Usage: asdf_list() or asdf_list(plugin)
/// Answers an Array of version Strings. A failure, such as an unknown plugin,
/// is E_TOOL_FAILED; it is never returned as a string.
fn bi_asdf_list(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("asdf_list", &input)?;
    let plugin = k8s_arg("asdf_list", "plugin", &args, 0, tf_plain)?;
    let mut argv: Vec<&str> = vec!["list"];
    if let Some(p) = &plugin {
        argv.push(p.as_str());
    }
    let run = tool_run(
        "asdf_list",
        "asdf",
        None,
        &argv,
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    Ok(Value::Array(devtool_lines(&tool_text("asdf_list", run)?)))
}

/// asdf install — Install one version of a plugin's tool.
/// Usage: asdf_install(plugin) or asdf_install(plugin, version)
/// The version defaults to "latest". Both are one word, not option-like. The
/// install goes into asdf's own directory, outside the workspace, and fetches
/// and runs the plugin's code, so the effect is Exec and agent mode asks first.
fn bi_asdf_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("asdf_install", &input)?;
    crate::safety::check_egress_unknown(
        "asdf_install",
        "the download comes from the plugin's own source, which is not named in the arguments",
    )?;
    let plugin = k8s_need("asdf_install", "plugin", &args, 0, tf_plain)?;
    let version = k8s_arg("asdf_install", "version", &args, 1, tf_plain)?
        .unwrap_or_else(|| "latest".to_string());
    let run = finished(
        "asdf_install",
        tool_run(
            "asdf_install",
            "asdf",
            None,
            &["install", plugin.as_str(), version.as_str()],
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("plugin".to_string(), Value::Str(plugin));
    rec.insert("version".to_string(), Value::Str(version));
    Ok(Value::Record(rec))
}

// --- mise (1049-1050) ---

/// mise use — Pin a tool version in the .mise.toml of the process's directory.
/// Usage: mise_use(tool@version)
/// The spec is one word such as node@20 and not option-like, so it cannot
/// select `--global`. The directory mise writes must lie inside the workspace.
/// mise installs the version and writes the config, yet the effect table
/// classes mise_use as write_local, so nothing asks for approval; reported,
/// not changed here.
fn bi_mise_use(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("mise_use", &input)?;
    // `mise use` installs the tool version, which is fetched from a source the
    // mise configuration or the tool's plugin names, not the argument.
    crate::safety::check_egress_unknown(
        "mise_use",
        "mise installs the tool from a source set by its plugins and configuration, not the arguments",
    )?;
    let tool = k8s_need("mise_use", "tool@version", &args, 0, devtool_tool_spec)?;
    let cwd = devtool_cwd("mise_use")?;
    workspace_path("mise_use", ".", &cwd)?;
    let run = finished(
        "mise_use",
        tool_run(
            "mise_use",
            "mise",
            None,
            &["use", tool.as_str()],
            Keep::Tail(TOOL_KEEP_TAIL),
            TOOL_LONG_DEADLINE_SECS,
        )?,
    )?;
    let mut rec = run_fields(run, "stdout", "stderr");
    rec.insert("tool".to_string(), Value::Str(tool));
    Ok(Value::Record(rec))
}

/// mise list — Installed tool versions known to mise.
/// Usage: mise_list()
/// Answers an Array of Strings, one per line of mise's report. A failure is
/// E_TOOL_FAILED.
fn bi_mise_list(_args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    k8s_no_input("mise_list", &input)?;
    let run = tool_run(
        "mise_list",
        "mise",
        None,
        &["list"],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    Ok(Value::Array(devtool_lines(&tool_text("mise_list", run)?)))
}

// ---------------------------------------------------------------------------
// Package and build tools: argument checks and the bounded runner they share
// ---------------------------------------------------------------------------

/// Deadline for a script, task, hook or formatter run. Installs, builds, tests
/// and compile-and-run calls use TOOL_LONG_DEADLINE_SECS.
const PKG_RUN_DEADLINE_SECS: u64 = 600;
/// The most arguments one call passes to its tool.
const PKG_MAX_ITEMS: usize = 256;
/// The `uv pip` subcommands offered. `compile` and `sync` rewrite lock or
/// requirement files and are not offered.
const UV_PIP_VERBS: &[&str] = &[
    "install",
    "uninstall",
    "list",
    "freeze",
    "show",
    "check",
    "tree",
];

/// A value passed to a tool as one argument: not empty, no NUL, and never
/// option-like. A leading `-` would be read by the tool as one of its flags.
fn pkg_plain(builtin: &str, what: &str, value: &str) -> Result<String> {
    crate::safety::reject_option_like(builtin, &[value.to_string()])?;
    if value.trim().is_empty() || value.contains('\0') {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} must not be empty"
        )));
    }
    Ok(value.to_string())
}

/// Whether a value names a path rather than a name: it has a separator or a
/// drive letter, or it starts with '.'.
fn pkg_is_pathlike(value: &str) -> bool {
    value.contains('/')
        || value.contains('\\')
        || value.starts_with('.')
        || value.as_bytes().get(1) == Some(&b':')
}

/// `value` as a path, resolved the way the tool resolves it (against the
/// process directory it runs in), must lie inside the workspace.
fn pkg_inside(builtin: &str, value: &str) -> Result<()> {
    let base = std::env::current_dir().unwrap_or_else(|_| workspace_root_abs());
    workspace_path(builtin, value, &base).map(|_| ())
}

/// The path argument at `index`, or `default` when it is omitted. Both are
/// refused when option-like or outside the workspace.
fn pkg_path_arg(builtin: &str, args: &[Value], index: usize, default: &str) -> Result<String> {
    let path =
        k8s_arg(builtin, "path", args, index, pkg_plain)?.unwrap_or_else(|| default.to_string());
    pkg_inside(builtin, &path)?;
    Ok(path)
}

/// A script, task, hook or command name that a tool runs. When it names a path
/// it must lie inside the workspace.
fn pkg_name(builtin: &str, what: &str, value: &str) -> Result<String> {
    let name = pkg_plain(builtin, what, value)?;
    if pkg_is_pathlike(&name) {
        pkg_inside(builtin, &name)?;
    }
    Ok(name)
}

/// A package spec an installer receives. `file:` and `link:` specs install from
/// a local directory, so they are refused. A spec that names a path must lie
/// inside the workspace.
fn pkg_spec(builtin: &str, what: &str, value: &str) -> Result<String> {
    let spec = pkg_plain(builtin, what, value)?;
    let lower = spec.to_ascii_lowercase();
    if lower.contains("file:") || lower.contains("link:") {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} {spec:?} is a local path (file: or link:); install from a registry or a remote URL"
        )));
    }
    if pkg_is_pathlike(&spec) {
        pkg_inside(builtin, &spec)?;
    }
    Ok(spec)
}

/// A Go package pattern: plain, and inside the workspace.
fn pkg_go_target(builtin: &str, what: &str, value: &str) -> Result<String> {
    let target = pkg_plain(builtin, what, value)?;
    pkg_inside(builtin, &target)?;
    Ok(target)
}

/// A Deno script: a path inside the workspace. Remote modules are refused,
/// because deno would fetch and run code that the workspace does not hold.
fn pkg_deno_script(builtin: &str, what: &str, value: &str) -> Result<String> {
    let script = pkg_plain(builtin, what, value)?;
    // A colon past the second character is a module specifier (https://, npm:,
    // jsr:, data:), not a path. A drive letter sits at index 1 and is a path.
    if script.find(':').is_some_and(|at| at > 1) {
        return Err(crate::safety::arg_err(format!(
            "{builtin}: {what} {script:?} is a module specifier, not a local path; fetch it into the workspace first"
        )));
    }
    pkg_inside(builtin, &script)?;
    Ok(script)
}

/// Every argument, each checked with `check`. A non-String or an option-like
/// argument is refused; none is dropped.
fn pkg_each(builtin: &str, what: &str, args: &[Value], check: K8sCheck) -> Result<Vec<String>> {
    k8s_max_args(builtin, args, PKG_MAX_ITEMS)?;
    let mut out = Vec::with_capacity(args.len());
    for index in 0..args.len() {
        if let Some(value) = k8s_arg(builtin, what, args, index, check)? {
            out.push(value);
        }
    }
    Ok(out)
}

/// Arguments that a script or program receives after its name. They pass
/// through as given and need only be Strings: after the name a leading '-'
/// belongs to the script, not to the tool. A non-String is refused.
fn pkg_trailing(builtin: &str, args: &[Value]) -> Result<Vec<String>> {
    k8s_max_args(builtin, args, PKG_MAX_ITEMS)?;
    args.iter()
        .enumerate()
        .map(|(index, value)| match value {
            Value::Str(s) if !s.contains('\0') => Ok(s.clone()),
            Value::Str(_) => Err(crate::safety::arg_err(format!(
                "{builtin}: argument {} contains a NUL byte",
                index + 2
            ))),
            other => Err(crate::safety::arg_err(format!(
                "{builtin}: argument {} must be a String, got {}",
                index + 2,
                other.type_name()
            ))),
        })
        .collect()
}

/// Splits the optional leading "--release", the one cargo option these
/// builtins take, from the arguments that follow it.
fn pkg_release(args: &[Value]) -> (bool, &[Value]) {
    match args.first() {
        Some(Value::Str(s)) if s == "--release" => (true, &args[1..]),
        _ => (false, args),
    }
}

/// Refuse pipeline input and more arguments than `max`.
fn pkg_shape(builtin: &str, args: &[Value], input: &Option<Value>, max: usize) -> Result<()> {
    k8s_no_input(builtin, input)?;
    k8s_max_args(builtin, args, max)
}

/// The last `max` bytes of `text`, cut on a character boundary.
fn pkg_tail(text: &str, max: usize) -> &str {
    if text.len() <= max {
        return text;
    }
    let mut start = text.len() - max;
    while !text.is_char_boundary(start) {
        start += 1;
    }
    &text[start..]
}

/// The output of a finished call, or its coded failure. A nonzero exit is
/// E_TOOL_FAILED, never a value.
fn pkg_output(builtin: &str, run: ToolRun) -> Result<(String, String)> {
    if !run.success {
        return Err(pkg_failure(builtin, run));
    }
    let stderr = run.stderr.clone();
    let stdout = tool_text(builtin, run)?;
    Ok((stdout.trim().to_string(), stderr))
}

/// The coded failure for a call that exited nonzero. A test runner prints its
/// failures on stdout and a compiler prints its errors on stderr, so the
/// message carries the end of both.
fn pkg_failure(builtin: &str, run: ToolRun) -> anyhow::Error {
    let out_tail = pkg_tail(run.stdout.trim(), TOOL_STDERR_TAIL);
    let detail = match (out_tail.is_empty(), run.stderr.is_empty()) {
        (true, _) => run.stderr.clone(),
        (false, true) => out_tail.to_string(),
        (false, false) => format!("{out_tail}\n{}", run.stderr),
    };
    crate::safety::tool_failed(builtin, &run.command, run.code, &detail)
}

/// A successful call as the record these builtins return: the given fields,
/// then exit_code 0, success, stdout and stderr. A nonzero exit never gets here.
fn pkg_done(builtin: &str, run: ToolRun, fields: Vec<(&str, Value)>) -> Result<Value> {
    let (stdout, stderr) = pkg_output(builtin, run)?;
    let mut rec = BTreeMap::new();
    for (key, value) in fields {
        rec.insert(key.to_string(), value);
    }
    rec.insert("exit_code".to_string(), Value::Int(0));
    rec.insert("success".to_string(), Value::Bool(true));
    rec.insert("stdout".to_string(), Value::Str(stdout));
    rec.insert("stderr".to_string(), Value::Str(stderr));
    Ok(Value::Record(rec))
}

/// Runs `program` with `args` under `deadline_secs`, keeping the end of its output.
fn pkg_run(builtin: &str, program: &str, args: &[&str], deadline_secs: u64) -> Result<ToolRun> {
    tool_run(
        builtin,
        program,
        None,
        args,
        Keep::Tail(TOOL_KEEP_TAIL),
        deadline_secs,
    )
}

/// The Node package managers are `.cmd` shims on Windows, which a bare program
/// name does not find.
fn node_tool(name: &'static str) -> &'static str {
    match name {
        "npm" if cfg!(windows) => "npm.cmd",
        "pnpm" if cfg!(windows) => "pnpm.cmd",
        "yarn" if cfg!(windows) => "yarn.cmd",
        "prettier" if cfg!(windows) => "prettier.cmd",
        "eslint" if cfg!(windows) => "eslint.cmd",
        _ => name,
    }
}

/// `program verb <packages>` for an installer, with every package spec checked.
fn pkg_install(
    builtin: &str,
    program: &str,
    verb: &[&str],
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    k8s_no_input(builtin, input)?;
    crate::safety::check_egress_unknown(
        builtin,
        "the package registry is set by the project's package-manager configuration, not the arguments",
    )?;
    let packages = pkg_each(builtin, "package", args, pkg_spec)?;
    let mut argv: Vec<&str> = verb.to_vec();
    argv.extend(packages.iter().map(String::as_str));
    let run = pkg_run(builtin, program, &argv, TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(builtin, run, Vec::new())
}

/// `program verb <script>` for a script runner: one checked name, nothing else.
fn pkg_named(
    builtin: &str,
    program: &str,
    verb: &str,
    args: &[Value],
    input: &Option<Value>,
) -> Result<Value> {
    pkg_shape(builtin, args, input, 1)?;
    let script = k8s_need(builtin, "a script name", args, 0, pkg_name)?;
    let run = pkg_run(
        builtin,
        program,
        &[verb, script.as_str()],
        PKG_RUN_DEADLINE_SECS,
    )?;
    pkg_done(builtin, run, vec![("script", Value::Str(script))])
}

// --- uv (1051-1053) ---

// --- uv (1051-1053) ---

/// uv run — Run a Python script with uv.
fn bi_uv_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "uv_run";
    k8s_no_input(B, &input)?;
    // `uv run` syncs the project's dependencies first, from the index uv's own
    // configuration names (a uv.toml or UV_INDEX_URL can redirect it).
    crate::safety::check_egress_unknown(
        B,
        "uv run installs the project's dependencies from an index set by uv's configuration, not the arguments",
    )?;
    let script = k8s_need(B, "a script or command", &args, 0, pkg_name)?;
    let mut argv = vec!["run".to_string(), script];
    argv.extend(pkg_trailing(B, args.get(1..).unwrap_or(&[]))?);
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = pkg_run(B, "uv", &refs, PKG_RUN_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

/// uv pip — Install packages with uv pip.
fn bi_uv_pip(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "uv_pip";
    k8s_no_input(B, &input)?;
    let verb =
        k8s_arg(B, "subcommand", &args, 0, pkg_plain)?.unwrap_or_else(|| "install".to_string());
    if !UV_PIP_VERBS.contains(&verb.as_str()) {
        return Err(crate::safety::arg_err(format!(
            "{B}: subcommand must be one of {}, got {verb:?}",
            UV_PIP_VERBS.join(", ")
        )));
    }
    crate::safety::check_egress_unknown(
        B,
        "the index is set by uv's configuration, not the arguments, and a source build runs its backend",
    )?;
    let packages = pkg_each(B, "package", args.get(1..).unwrap_or(&[]), pkg_spec)?;
    let deadline = if matches!(verb.as_str(), "install" | "uninstall") {
        TOOL_LONG_DEADLINE_SECS
    } else {
        TOOL_DEADLINE_SECS
    };
    let mut argv: Vec<&str> = vec!["pip", verb.as_str()];
    argv.extend(packages.iter().map(String::as_str));
    let run = pkg_run(B, "uv", &argv, deadline)?;
    pkg_done(B, run, vec![("subcmd", Value::Str(verb))])
}

/// uv venv — Create a virtual environment with uv.
fn bi_uv_venv(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "uv_venv";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, ".venv")?;
    let run = pkg_run(B, "uv", &["venv", path.as_str()], TOOL_DEADLINE_SECS)?;
    pkg_done(B, run, vec![("path", Value::Str(path))])
}

// --- pipx (1054-1055) ---

/// pipx_install(package): pipx install of one package spec. A `file:` or
/// `link:` spec is refused, and so is a path outside the workspace.
fn bi_pipx_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "pipx_install";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 1)?;
    crate::safety::check_egress_unknown(
        B,
        "the package index is set by pipx's configuration, not the argument",
    )?;
    let package = k8s_need(B, "a package spec", &args, 0, pkg_spec)?;
    let run = pkg_run(
        B,
        "pipx",
        &["install", package.as_str()],
        TOOL_LONG_DEADLINE_SECS,
    )?;
    pkg_done(B, run, vec![("package", Value::Str(package))])
}

/// pipx list — List pipx-installed packages.
fn bi_pipx_list(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("pipx");
    cmd.arg("list");
    let output = bounded_cmd_output("pipx_list", "pipx", cmd, PROBE_DEADLINE_SECS);
    match output {
        Ok(o) if o.status.success() => Ok(Value::Str(
            String::from_utf8_lossy(&o.stdout).trim().to_string(),
        )),
        // pipx's error text was returned as the list.
        Ok(o) => Err(crate::safety::tool_failed(
            "pipx",
            "pipx list",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        Err(e) => Err(crate::safety::tool_missing("pipx", "pipx", &e.to_string())),
    }
}

// --- poetry (1056-1057) ---

/// poetry run — Run a command in a Poetry environment.
fn bi_poetry_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "poetry_run";
    k8s_no_input(B, &input)?;
    let command = k8s_need(B, "a command", &args, 0, pkg_name)?;
    let mut argv = vec!["run".to_string(), command];
    argv.extend(pkg_trailing(B, args.get(1..).unwrap_or(&[]))?);
    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let run = pkg_run(B, "poetry", &refs, PKG_RUN_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

/// poetry install — Install Poetry project dependencies.
fn bi_poetry_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "poetry_install";
    pkg_shape(B, &args, &input, 0)?;
    crate::safety::check_egress_unknown(
        B,
        "the package sources are named by the project's pyproject.toml, not the arguments",
    )?;
    let run = pkg_run(B, "poetry", &["install"], TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

// --- node (1058) ---

/// node — Run a Node.js script.
fn bi_node_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "node_run";
    pkg_shape(B, &args, &input, 1)?;
    let script = match args.first() {
        Some(Value::Str(s)) if !s.trim().is_empty() && !s.contains('\0') => s.clone(),
        _ => {
            return Err(crate::safety::arg_err(
                "node_run requires a script path or expression",
            ))
        }
    };
    let run = if [".js", ".mjs", ".ts"]
        .iter()
        .any(|ext| script.ends_with(ext))
    {
        // A script file: a plain path inside the workspace, never a flag.
        let path = pkg_plain(B, "script path", &script)?;
        pkg_inside(B, &path)?;
        pkg_run(B, "node", &[path.as_str()], PKG_RUN_DEADLINE_SECS)?
    } else {
        // An expression: the text after -e is the program, whatever it begins with.
        pkg_run(B, "node", &["-e", script.as_str()], PKG_RUN_DEADLINE_SECS)?
    };
    pkg_done(B, run, Vec::new())
}

// --- npm (1059-1060) ---

/// npm run — Run an npm script.
fn bi_npm_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_named("npm_run", node_tool("npm"), "run", &args, &input)
}

/// npm install — Install npm packages.
fn bi_npm_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_install("npm_install", node_tool("npm"), &["install"], &args, &input)
}

// --- pnpm (1061-1062) ---

/// pnpm run — Run a pnpm script.
fn bi_pnpm_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_named("pnpm_run", node_tool("pnpm"), "run", &args, &input)
}

/// pnpm install — Install pnpm packages.
fn bi_pnpm_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_install(
        "pnpm_install",
        node_tool("pnpm"),
        &["install"],
        &args,
        &input,
    )
}

// --- yarn (1063-1064) ---

/// yarn run — Run a yarn script.
fn bi_yarn_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_named("yarn_run", node_tool("yarn"), "run", &args, &input)
}

/// yarn install — Install yarn packages.
fn bi_yarn_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let verb: &[&str] = if args.is_empty() {
        &["install"]
    } else {
        &["add"]
    };
    pkg_install("yarn_install", node_tool("yarn"), verb, &args, &input)
}

// --- cargo (1065-1067) ---

/// Why a cargo build, test or run is refused under an allowlist: it fetches
/// crates, and the registry is set by `.cargo/config.toml` (source replacement
/// and mirrors), not by the arguments. Also `CARGO_REGISTRIES_*` in the environment.
const CARGO_EGRESS_REASON: &str =
    "cargo fetches crates from a registry set by cargo's configuration, not the arguments";

/// cargo run — Run a Rust project.
fn bi_cargo_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cargo_run";
    k8s_no_input(B, &input)?;
    crate::safety::check_egress_unknown(B, CARGO_EGRESS_REASON)?;
    let (release, rest) = pkg_release(&args);
    let program_args = pkg_each(B, "argument", rest, pkg_plain)?;
    let mut argv: Vec<&str> = vec!["run"];
    if release {
        argv.push("--release");
    }
    if !program_args.is_empty() {
        argv.push("--");
        argv.extend(program_args.iter().map(String::as_str));
    }
    let run = pkg_run(B, "cargo", &argv, TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

/// cargo build — Build a Rust project.
fn bi_cargo_build_cmd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cargo_build_cmd";
    pkg_shape(B, &args, &input, 1)?;
    crate::safety::check_egress_unknown(B, CARGO_EGRESS_REASON)?;
    let release = match args.first() {
        None => false,
        Some(Value::Str(s)) if s == "--release" => true,
        Some(Value::Str(s)) => {
            return Err(crate::safety::arg_err(format!(
                "{B}: its only argument is \"--release\", got {s:?}"
            )))
        }
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{B}: its only argument is \"--release\", got a {}",
                other.type_name()
            )))
        }
    };
    let mut argv: Vec<&str> = vec!["build"];
    if release {
        argv.push("--release");
    }
    let run = pkg_run(B, "cargo", &argv, TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

/// cargo test — Run Rust tests.
fn bi_cargo_test_cmd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "cargo_test_cmd";
    k8s_no_input(B, &input)?;
    crate::safety::check_egress_unknown(B, CARGO_EGRESS_REASON)?;
    let (release, rest) = pkg_release(&args);
    k8s_max_args(B, rest, 1)?;
    let filter = pkg_each(B, "test name", rest, pkg_plain)?;
    let mut argv: Vec<&str> = vec!["test"];
    if release {
        argv.push("--release");
    }
    argv.extend(filter.iter().map(String::as_str));
    let run = pkg_run(B, "cargo", &argv, TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

// --- rustup (1068-1069) ---

/// rustup show — Show installed Rust toolchains.
fn bi_rustup_show(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("rustup");
    cmd.arg("show");
    let output = bounded_cmd_output("rustup_show", "rustup", cmd, PROBE_DEADLINE_SECS);
    match output {
        Ok(o) if o.status.success() => Ok(Value::Str(
            String::from_utf8_lossy(&o.stdout).trim().to_string(),
        )),
        // rustup's error text was returned as if it were the toolchain list.
        Ok(o) => Err(crate::safety::tool_failed(
            "rustup_show",
            "rustup",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        Err(e) => Err(crate::safety::tool_missing(
            "rustup",
            "rustup",
            &e.to_string(),
        )),
    }
}

/// rustup_update(): rustup update, which fetches and installs toolchains. It
/// takes no arguments and no pipeline input.
fn bi_rustup_update(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "rustup_update";
    pkg_shape(B, &args, &input, 0)?;
    crate::safety::check_egress_unknown(
        B,
        "the toolchain servers are set by rustup's configuration, not the arguments",
    )?;
    let run = pkg_run(B, "rustup", &["update"], TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

// --- go (1070-1072) ---

/// Why a go build, test or run is refused under an allowlist: it downloads
/// modules through GOPROXY (and GOFLAGS, go.env), which the arguments do not name.
const GO_EGRESS_REASON: &str =
    "go fetches modules through GOPROXY, which is set by the environment or go env, not the arguments";

/// go run — Run a Go program.
fn bi_go_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "go_run";
    pkg_shape(B, &args, &input, 1)?;
    crate::safety::check_egress_unknown(B, GO_EGRESS_REASON)?;
    let target = pkg_path_arg(B, &args, 0, ".")?;
    let run = pkg_run(B, "go", &["run", target.as_str()], TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

/// go build — Build a Go project.
fn bi_go_build(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "go_build";
    k8s_no_input(B, &input)?;
    crate::safety::check_egress_unknown(B, GO_EGRESS_REASON)?;
    let packages = pkg_each(B, "package", &args, pkg_go_target)?;
    let mut argv: Vec<&str> = vec!["build"];
    argv.extend(packages.iter().map(String::as_str));
    let run = pkg_run(B, "go", &argv, TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

/// go test — Run Go tests.
fn bi_go_test(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "go_test";
    pkg_shape(B, &args, &input, 1)?;
    crate::safety::check_egress_unknown(B, GO_EGRESS_REASON)?;
    let target = pkg_path_arg(B, &args, 0, "./...")?;
    let run = pkg_run(
        B,
        "go",
        &["test", "-v", target.as_str()],
        TOOL_LONG_DEADLINE_SECS,
    )?;
    pkg_done(B, run, Vec::new())
}

// --- mage (1073) ---

/// mage — Run a mage target (Go task runner).
fn bi_mage_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "mage_run";
    pkg_shape(B, &args, &input, 1)?;
    let target = k8s_need(B, "a target name", &args, 0, pkg_plain)?;
    let run = pkg_run(B, "mage", &[target.as_str()], PKG_RUN_DEADLINE_SECS)?;
    pkg_done(B, run, vec![("target", Value::Str(target))])
}

// --- bun (1074-1075) ---

/// bun run — Run a script or file with Bun.
fn bi_bun_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    pkg_named("bun_run", "bun", "run", &args, &input)
}

/// bun install — Install packages with Bun.
fn bi_bun_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    let verb: &[&str] = if args.is_empty() {
        &["install"]
    } else {
        &["add"]
    };
    pkg_install("bun_install", "bun", verb, &args, &input)
}

// --- deno (1076-1077) ---

/// deno run — Run a script with Deno.
fn bi_deno_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "deno_run";
    pkg_shape(B, &args, &input, 1)?;
    // Remote imports are fetched without a permission prompt, from URLs the
    // script names, and an import map or DENO_* setting can redirect them.
    crate::safety::check_egress_unknown(
        B,
        "deno fetches remote imports named by the script and its import map, not the arguments",
    )?;
    let script = k8s_need(B, "a script path", &args, 0, pkg_deno_script)?;
    // --no-prompt: a permission the script lacks is an error, never a prompt
    // on a closed stdin. No permission is granted.
    let run = pkg_run(
        B,
        "deno",
        &["run", "--no-prompt", script.as_str()],
        PKG_RUN_DEADLINE_SECS,
    )?;
    pkg_done(B, run, Vec::new())
}

/// deno task — Run a deno task.
fn bi_deno_task(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "deno_task";
    pkg_shape(B, &args, &input, 1)?;
    let task = k8s_need(B, "a task name", &args, 0, pkg_plain)?;
    let run = pkg_run(B, "deno", &["task", task.as_str()], PKG_RUN_DEADLINE_SECS)?;
    pkg_done(B, run, vec![("task", Value::Str(task))])
}

// --- gh (1078-1080) ---

/// gh pr(subcommand, ...): gh pr with one of the listed subcommands. Reads
/// return the output; writes (create, comment, edit, close, reopen, ready)
/// change the remote and are approval-gated in agent mode.
fn bi_gh_pr(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    ops_forge("gh_pr", "gh", "pr", GH_PR_VERBS, &args, &input)
}

/// gh issue(subcommand, ...): gh issue with one of the listed subcommands. Writes
/// change the remote and are approval-gated in agent mode.
fn bi_gh_issue(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    ops_forge("gh_issue", "gh", "issue", GH_ISSUE_VERBS, &args, &input)
}

/// gh repo(subcommand, ...): gh repo list or view only. Every subcommand that
/// changes a repository is refused.
fn bi_gh_repo_cmd(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    // Both verbs (list, view) are GitHub API calls to the host gh is configured
    // for (GH_HOST, the hosts file), which the arguments do not name, so there is
    // no local mode to allow.
    crate::safety::check_egress_unknown(
        "gh_repo_cmd",
        "gh contacts the host it is configured for (GH_HOST, the hosts file), not the arguments",
    )?;
    ops_forge("gh_repo_cmd", "gh", "repo", GH_REPO_VERBS, &args, &input)
}

// --- glab (1081-1082) ---

/// glab mr(subcommand, ...): glab mr with one of the listed subcommands. Writes
/// change the remote and are approval-gated in agent mode.
fn bi_glab_mr(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    ops_forge("glab_mr", "glab", "mr", GLAB_MR_VERBS, &args, &input)
}

/// glab issue(subcommand, ...): glab issue with one of the listed subcommands.
/// Writes change the remote and are approval-gated in agent mode.
fn bi_glab_issue(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    ops_forge(
        "glab_issue",
        "glab",
        "issue",
        GLAB_ISSUE_VERBS,
        &args,
        &input,
    )
}

// --- act (1083) ---

/// act_run([event]): act, which runs GitHub Actions workflows for an event in
/// Docker containers. The event is a plain name; a leading `-` is refused. A
/// nonzero exit is E_TOOL_FAILED. Runs with a 15 minute deadline.
fn bi_act_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "act_run";
    pkg_shape(B, &args, &input, 1)?;
    let event = k8s_arg(B, "event", &args, 0, ops_event)?;
    let mut argv: Vec<&str> = Vec::new();
    let mut fields: Vec<(&str, Value)> = Vec::new();
    if let Some(name) = event.as_deref() {
        argv.push(name);
        fields.push(("event", Value::Str(name.to_string())));
    }
    let run = pkg_run(B, "act", &argv, TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, fields)
}

// --- pre-commit (1084-1085) ---

/// pre-commit run — Run pre-commit hooks.
fn bi_pre_commit_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "pre_commit_run";
    pkg_shape(B, &args, &input, 1)?;
    // The first run clones each hook repository named in .pre-commit-config.yaml.
    crate::safety::check_egress_unknown(
        B,
        "pre-commit clones the hook repositories named by the project's config, not the arguments",
    )?;
    let all = matches!(args.first(), Some(Value::Str(s)) if s == "--all-files");
    let hook = if all {
        None
    } else {
        k8s_arg(B, "hook name", &args, 0, pkg_plain)?
    };
    let mut argv: Vec<&str> = vec!["run"];
    if all {
        argv.push("--all-files");
    }
    if let Some(hook) = hook.as_deref() {
        argv.push(hook);
    }
    let run = pkg_run(B, "pre-commit", &argv, TOOL_LONG_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

/// pre-commit install — Install pre-commit hooks.
fn bi_pre_commit_install(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "pre_commit_install";
    pkg_shape(B, &args, &input, 0)?;
    // The hook is written into the repository's .git directory.
    pkg_inside(B, ".")?;
    let run = pkg_run(B, "pre-commit", &["install"], TOOL_DEADLINE_SECS)?;
    pkg_done(B, run, Vec::new())
}

// --- buildah (1086-1087) ---

/// buildah_build(tag, [context]): buildah bud of a context directory inside the
/// workspace, tagged `tag`. A URL or git context is refused. Runs with a 15
/// minute deadline.
fn bi_buildah_build(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "buildah_build";
    pkg_shape(B, &args, &input, 2)?;
    // A build pulls the base images its Dockerfile's FROM lines name, so the
    // registries are in the build context, not in the arguments.
    crate::safety::check_egress_unknown(
        B,
        "the base images are named in the build context's Dockerfile, not in the arguments",
    )?;
    let tag = k8s_need(B, "an image tag", &args, 0, ops_image_ref)?;
    let context = k8s_arg(B, "context", &args, 1, ops_scan_dir)?.unwrap_or_else(|| ".".to_string());
    let run = tool_run(
        B,
        "buildah",
        None,
        &["bud", "-t", tag.as_str(), context.as_str()],
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    pkg_done(B, run, vec![("tag", Value::Str(tag))])
}

/// buildah images — List Buildah images.
fn bi_buildah_images(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let mut cmd = crate::safety::child_command("buildah");
    cmd.args(["images", "--json"]);
    let output = bounded_cmd_output("buildah_images", "buildah", cmd, TOOL_DEADLINE_SECS);
    match output {
        Ok(o) if o.status.success() => {
            let stdout = String::from_utf8_lossy(&o.stdout);
            // Non-JSON output came back as a String, and a failure's stderr
            // as the answer.
            serde_json::from_str::<serde_json::Value>(&stdout)
                .map(json_to_value)
                .map_err(|e| {
                    crate::safety::tool_failed(
                        "buildah_images",
                        "buildah images --json",
                        o.status.code(),
                        &format!("output that is not JSON: {e}"),
                    )
                })
        }
        Ok(o) => Err(crate::safety::tool_failed(
            "buildah_images",
            "buildah images",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        Err(e) => Err(crate::safety::tool_missing(
            "buildah",
            "buildah",
            &e.to_string(),
        )),
    }
}

// --- skopeo (1088-1089) ---

/// The skopeo egress rule. Only a `docker://` reference reaches a registry, and
/// `registries.conf` can redirect a registry to a mirror, which the arguments do
/// not show. So under an allowlist a `docker://` reference is refused as
/// destination-unknown, and the local transports (`dir:`, `oci:`, `docker-archive:`,
/// `oci-archive:`, `docker-daemon:`, `containers-storage:`) pass.
fn skopeo_registry_egress(builtin: &str, refs: &[&String]) -> Result<()> {
    if refs.iter().any(|r| r.starts_with("docker://")) {
        crate::safety::check_egress_unknown(
            builtin,
            "skopeo reaches a docker:// registry that registries.conf can redirect to a mirror, not the arguments",
        )?;
    }
    Ok(())
}

/// skopeo_copy(src, dst): skopeo copy between two transport references. A
/// registry reference is a network copy; a local transport must name a path
/// inside the workspace. Runs with a 15 minute deadline.
fn bi_skopeo_copy(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "skopeo_copy";
    pkg_shape(B, &args, &input, 2)?;
    let src = k8s_need(B, "a source transport reference", &args, 0, ops_transport)?;
    let dst = k8s_need(
        B,
        "a destination transport reference",
        &args,
        1,
        ops_transport,
    )?;
    skopeo_registry_egress(B, &[&src, &dst])?;
    let run = tool_run(
        B,
        "skopeo",
        None,
        &["copy", src.as_str(), dst.as_str()],
        Keep::Tail(TOOL_KEEP_TAIL),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    pkg_done(
        B,
        run,
        vec![("src", Value::Str(src)), ("dst", Value::Str(dst))],
    )
}

/// skopeo_inspect(image): skopeo inspect of a transport reference, as JSON.
fn bi_skopeo_inspect(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "skopeo_inspect";
    pkg_shape(B, &args, &input, 1)?;
    let image = k8s_need(B, "an image transport reference", &args, 0, ops_transport)?;
    skopeo_registry_egress(B, &[&image])?;
    let run = tool_run(
        B,
        "skopeo",
        None,
        &["inspect", image.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    tool_json(B, run)
}

// --- trivy (1090-1091) ---

/// trivy_scan([path]): trivy fs of a path inside the workspace (default the
/// workspace directory), as JSON. Trivy may download its vulnerability database.
fn bi_trivy_scan(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "trivy_scan";
    pkg_shape(B, &args, &input, 1)?;
    // Trivy downloads its vulnerability database from a repository that is set by
    // its configuration (TRIVY_DB_REPOSITORY, trivy.yaml), not the arguments, and
    // it refreshes that database on a schedule. There is no local-only mode.
    crate::safety::check_egress_unknown(
        B,
        "trivy downloads its vulnerability database from a repository set by its configuration, not the arguments",
    )?;
    // Trivy downloads its vulnerability database from a repository that is set by
    // its configuration (TRIVY_DB_REPOSITORY, trivy.yaml), not the arguments, and
    // it refreshes that database on a schedule. There is no local-only mode.
    let path = k8s_arg(B, "path", &args, 0, ops_scan_dir)?.unwrap_or_else(|| ".".to_string());
    let run = tool_run(
        B,
        "trivy",
        None,
        &["fs", "--format", "json", path.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    tool_json(B, run)
}

/// trivy_image(image): trivy image scan of a container image, as JSON. Trivy
/// pulls the image from its registry.
fn bi_trivy_image(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "trivy_image";
    pkg_shape(B, &args, &input, 1)?;
    // The image is pulled from its registry and the vulnerability database is
    // downloaded from the configured repository; both are judged as unknown.
    crate::safety::check_egress_unknown(
        B,
        "trivy pulls the image and downloads its vulnerability database from sources set by its configuration",
    )?;
    let image = k8s_need(B, "an image name", &args, 0, ops_image_ref)?;
    let run = tool_run(
        B,
        "trivy",
        None,
        &["image", "--format", "json", image.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    tool_json(B, run)
}

// --- hadolint (1092) ---

/// hadolint — Lint Dockerfiles.
fn bi_hadolint_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "hadolint_check";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, "Dockerfile")?;
    if !std::path::Path::new(&path).is_file() {
        return Err(crate::safety::not_found(B, "file", &path));
    }
    let run = tool_run(
        B,
        "hadolint",
        None,
        &["--format", "json", path.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    // hadolint exits 1 when it reports findings: that is the answer.
    findings_json(B, run, 1)
}

// --- shellcheck (1093) ---

/// shellcheck — Lint shell scripts.
fn bi_shellcheck_check(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("shellcheck requires a script path")),
    };
    crate::safety::reject_option_like("shellcheck", std::slice::from_ref(&path))?;
    let mut cmd = crate::safety::child_command("shellcheck");
    cmd.args(["--format=json", &path]);
    let output = bounded_cmd_output("shellcheck_check", "shellcheck", cmd, TOOL_DEADLINE_SECS);
    match output {
        // Exit 0 is clean and 1 means issues; 2 and up are failures. A file
        // that did not exist exits 2 and still prints `[]`, which read as
        // a clean lint. Output that was not JSON came back as a different
        // shape, {success, output}.
        Ok(o) if !matches!(o.status.code(), Some(0) | Some(1)) => Err(crate::safety::tool_failed(
            "shellcheck",
            "shellcheck",
            o.status.code(),
            &String::from_utf8_lossy(&o.stderr),
        )),
        Ok(o) => {
            let stdout = String::from_utf8_lossy(&o.stdout);
            serde_json::from_str::<serde_json::Value>(&stdout)
                .map(json_to_value)
                .map_err(|e| {
                    crate::safety::tool_failed(
                        "shellcheck",
                        "shellcheck --format=json",
                        o.status.code(),
                        &format!("output that is not JSON: {e}"),
                    )
                })
        }
        Err(e) => Err(crate::safety::tool_missing(
            "shellcheck",
            "shellcheck",
            &e.to_string(),
        )),
    }
}

// --- shfmt (1094) ---

/// shfmt — Format shell scripts.
fn bi_shfmt_format(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "shfmt_format";
    pkg_shape(B, &args, &input, 1)?;
    let path = k8s_need(B, "a script path", &args, 0, pkg_plain)?;
    pkg_inside(B, &path)?;
    // Without -w shfmt writes the formatted script to stdout and changes no file.
    let run = tool_run(
        B,
        "shfmt",
        None,
        &[path.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_DEADLINE_SECS,
    )?;
    tool_text(B, run).map(Value::Str)
}

// --- yamllint (1095) ---

/// yamllint — Lint YAML files.
fn bi_yamllint_check(args: Vec<Value>, _input: Option<Value>) -> Result<Value> {
    let path = match args.first() {
        Some(Value::Str(s)) => s.clone(),
        _ => return Err(crate::safety::arg_err("yamllint requires a file path")),
    };
    crate::safety::reject_option_like("yamllint", std::slice::from_ref(&path))?;
    let mut cmd = crate::safety::child_command("yamllint");
    cmd.args(["-f", "parsable", &path]);
    let output = bounded_cmd_output("yamllint_check", "yamllint", cmd, TOOL_DEADLINE_SECS);
    match output {
        Ok(o) => {
            let stdout = String::from_utf8_lossy(&o.stdout);
            let issues: Vec<Value> = stdout
                .lines()
                .filter(|l| !l.is_empty())
                .map(|line| Value::Str(line.to_string()))
                .collect();
            // A file yamllint could not read answered {success: false,
            // issues: []}: failed, with nothing wrong.
            if !o.status.success() && issues.is_empty() {
                return Err(crate::safety::tool_failed(
                    "yamllint",
                    "yamllint",
                    o.status.code(),
                    &String::from_utf8_lossy(&o.stderr),
                ));
            }
            let mut rec = BTreeMap::new();
            rec.insert("success".to_string(), Value::Bool(o.status.success()));
            rec.insert("issues".to_string(), Value::Array(issues));
            Ok(Value::Record(rec))
        }
        Err(e) => Err(crate::safety::tool_missing(
            "yamllint",
            "yamllint",
            &e.to_string(),
        )),
    }
}

// --- prettier (1096) ---

/// prettier — Format code with Prettier.
fn bi_prettier_format(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "prettier_format";
    k8s_no_input(B, &input)?;
    k8s_max_args(B, &args, 2)?;
    let path = k8s_need(B, "a file path", &args, 0, pkg_plain)?;
    pkg_inside(B, &path)?;
    let write = match args.get(1) {
        None => false,
        Some(Value::Str(s)) if s == "--write" => true,
        Some(Value::Str(s)) => {
            return Err(crate::safety::arg_err(format!(
                "{B}: the only option is \"--write\", got {s:?}"
            )))
        }
        Some(other) => {
            return Err(crate::safety::arg_err(format!(
                "{B}: the option must be a String, got {}",
                other.type_name()
            )))
        }
    };
    let mut argv: Vec<&str> = Vec::new();
    if write {
        argv.push("--write");
    }
    argv.push(path.as_str());
    let run = tool_run(
        B,
        node_tool("prettier"),
        None,
        &argv,
        Keep::Head(TOOL_MAX_TEXT),
        PKG_RUN_DEADLINE_SECS,
    )?;
    pkg_done(B, run, vec![("path", Value::Str(path))])
}

// --- eslint (1097) ---

/// eslint — Lint JavaScript/TypeScript files.
fn bi_eslint_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "eslint_check";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, ".")?;
    let run = tool_run(
        B,
        node_tool("eslint"),
        None,
        &["--format=json", path.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    // eslint exits 1 when it reports problems: that is the answer.
    findings_json(B, run, 1)
}

// --- ruff (1098-1099) ---

/// ruff check — Lint Python files with Ruff.
fn bi_ruff_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ruff_check";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, ".")?;
    let mut run = tool_run(
        B,
        "ruff",
        None,
        &["check", "--output-format=json", path.as_str()],
        Keep::Head(TOOL_MAX_JSON),
        TOOL_DEADLINE_SECS,
    )?;
    // ruff exits 1 when it reports violations: that is the answer, not a
    // failure. Any other nonzero exit is a failure, and tool_json reports it.
    if run.code == Some(1) {
        run.success = true;
    }
    tool_json(B, run)
}

/// ruff format — Format Python files with Ruff.
fn bi_ruff_format(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "ruff_format";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, ".")?;
    let run = pkg_run(B, "ruff", &["format", path.as_str()], PKG_RUN_DEADLINE_SECS)?;
    pkg_done(B, run, vec![("path", Value::Str(path))])
}

// --- black (1100) ---

/// black — Format Python code with Black.
fn bi_black_format(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "black_format";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, ".")?;
    let run = pkg_run(B, "black", &[path.as_str()], PKG_RUN_DEADLINE_SECS)?;
    pkg_done(B, run, vec![("path", Value::Str(path))])
}

// --- mypy (1101) ---

/// mypy — Type check Python code.
fn bi_mypy_check(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "mypy_check";
    pkg_shape(B, &args, &input, 1)?;
    let path = pkg_path_arg(B, &args, 0, ".")?;
    let run = tool_run(
        B,
        "mypy",
        None,
        &[path.as_str()],
        Keep::Head(TOOL_MAX_TEXT),
        TOOL_LONG_DEADLINE_SECS,
    )?;
    let clean = run.code == Some(0);
    let text = stdout_with_exit1(B, run)?;
    let issues: Vec<Value> = text
        .lines()
        .map(str::trim_end)
        .filter(|l| !l.is_empty() && !l.starts_with("Success:") && !l.starts_with("Found "))
        .map(|l| Value::Str(l.to_string()))
        .collect();
    let mut rec = BTreeMap::new();
    rec.insert("success".to_string(), Value::Bool(clean));
    rec.insert("issues".to_string(), Value::Array(issues));
    Ok(Value::Record(rec))
}

// --- pytest (1102) ---

/// pytest — Run Python tests.
fn bi_pytest_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    const B: &str = "pytest_run";
    k8s_no_input(B, &input)?;
    // Options and test selectors pass through as given. A path-shaped value
    // that is not an option must lie inside the workspace.
    let extra = pkg_trailing(B, &args)?;
    for value in extra.iter().filter(|v| !v.starts_with('-')) {
        if pkg_is_pathlike(value) {
            pkg_inside(B, value)?;
        }
    }
    let mut argv: Vec<&str> = vec!["-v"];
    argv.extend(extra.iter().map(String::as_str));
    let run = pkg_run(B, "pytest", &argv, PKG_RUN_DEADLINE_SECS)?;
    // A failing test is a nonzero exit, so it is E_TOOL_FAILED with the output tail.
    pkg_done(B, run, Vec::new())
}

// --- nodemon (1103) ---

/// nodemon — Run a .js script and restart it on changes in its directory,
/// bounded by timeout_ms.
fn bi_nodemon_run(args: Vec<Value>, input: Option<Value>) -> Result<Value> {
    tool_runs::nodemon_run(args, input)
}

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

    /// The FIPS posture (`safety::require_fips_hash`) had no test coverage at
    /// all, despite being the enforcement point the compliance claim rests on.
    /// This pins it: MD5 and SHA-1 are refused under `IRONSHELL_FIPS`, SHA-256
    /// still works, and MD5 stays available for legacy interop when FIPS is off.
    #[test]
    fn file_checksum_honors_the_fips_gate() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        let dir = std::env::temp_dir().join("ae_fips_checksum_test");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("sample.txt");
        std::fs::write(&path, b"ironshell").unwrap();
        // Repointed from `bi_file_checksum` to `bi_crypto_hash_file` when the
        // former was deleted as unreachable: it duplicated this one and nothing
        // dispatched to it, so the only coverage of the FIPS gate was pointed at
        // a builtin no caller could reach. Argument order here is (path, algo).
        let call = |algo: &str| {
            bi_crypto_hash_file(
                vec![
                    Value::Str(path.to_string_lossy().to_string()),
                    Value::Str(algo.to_string()),
                ],
                None,
            )
        };

        std::env::remove_var("IRONSHELL_FIPS");
        assert!(
            call("md5").is_ok(),
            "MD5 stays available for legacy interop when FIPS is off"
        );

        std::env::set_var("IRONSHELL_FIPS", "1");
        for weak in ["md5", "sha1"] {
            let err = call(weak).unwrap_err().to_string();
            assert!(
                err.contains("E_FIPS_DISALLOWED"),
                "FIPS mode must refuse {weak} with a machine-readable code; got: {err}"
            );
        }
        assert!(call("sha256").is_ok(), "sha256 is FIPS-approved");

        std::env::remove_var("IRONSHELL_FIPS");
        let _ = std::fs::remove_dir_all(&dir);
    }
}

#[cfg(test)]
mod declaration_narrowness {
    use super::*;
    use crate::signature::SIGNATURES;

    /// A declaration is enforced *before* the body runs, so it is not
    /// documentation -- it is the contract. Five of the first fifty-two were
    /// narrower than the language and each silently deleted a form that
    /// worked; two of them shipped. `reverse` declared `subject: Array`
    /// refused `"abc" | reverse` from 5a54fc3 onward and passed a full green
    /// gate, because one test pipes an array and another passes a string *by
    /// argument* -- the broken combination was covered by neither.
    ///
    /// None was found by review. They were found one at a time, by a corpus
    /// happening to contain the right call. This asks the question directly:
    /// for every declaration, every shape of value, in both calling positions,
    /// does the declaration refuse something the body would have honoured?
    ///
    /// The oracle is the body itself, via `call_with_input_inner`, which is
    /// the same dispatch minus validation. That is the only oracle available:
    /// there is no independent record of which forms are "meant" to work, and
    /// a regex over `src/` is the name-based reasoning this whole effort
    /// exists to remove.
    fn probe_values() -> Vec<(&'static str, Value)> {
        vec![
            ("Int", Value::Int(3)),
            ("Float", Value::Float(1.5)),
            ("Str", Value::Str("abc".to_string())),
            ("Bool", Value::Bool(true)),
            ("Array", Value::Array(vec![Value::Int(1), Value::Int(2)])),
            (
                "Record",
                Value::Record(
                    [("a".to_string(), Value::Int(1))]
                        .into_iter()
                        .collect::<std::collections::BTreeMap<_, _>>(),
                ),
            ),
        ]
    }

    /// Whether the body produced something worth preserving.
    ///
    /// A body that answers `Ok(Value::Null)` for nonsense is being sloppy, not
    /// supporting a form -- several do exactly that (`crypto_jwt_decode`
    /// returns `Ok(Null)` for a non-string). Counting those as "the
    /// declaration is too narrow" would argue for keeping bugs.
    fn meaningful(v: &Value) -> bool {
        !matches!(v, Value::Null | Value::Error(_))
    }

    #[test]
    fn no_declaration_refuses_a_call_its_body_would_have_honoured() {
        let _env_lock = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        // Put back what this sets, even when an assertion below fails. These
        // are process-global: left behind, IRONSHELL_MAX_NET=0 refused the
        // workflow HTTP tests that happened to run later in the same process.
        struct Restore(Vec<(&'static str, Option<std::ffi::OsString>)>);
        impl Drop for Restore {
            fn drop(&mut self) {
                for (k, v) in &self.0 {
                    match v {
                        Some(v) => std::env::set_var(k, v),
                        None => std::env::remove_var(k),
                    }
                }
            }
        }
        let _restore = Restore(
            [
                "IRONSHELL_MODE",
                "IRONSHELL_POLICY",
                "IRONSHELL_WORKSPACE",
                "IRONSHELL_MAX_NET",
            ]
            .iter()
            .map(|k| (*k, std::env::var_os(k)))
            .collect(),
        );

        let jail = std::env::temp_dir().join(format!("ae_narrow_{}", std::process::id()));
        std::fs::create_dir_all(&jail).expect("create jail");
        std::env::set_var("IRONSHELL_MODE", "agent");
        std::env::set_var("IRONSHELL_POLICY", "strict");
        std::env::set_var("IRONSHELL_WORKSPACE", &jail);
        std::env::set_var("IRONSHELL_MAX_NET", "0");

        let mut too_narrow: Vec<String> = Vec::new();
        let (mut checked, mut refused) = (0usize, 0usize);

        for sig in SIGNATURES {
            // Only builtins that transform data and return. The effect gate
            // would refuse the rest before the body ran, which tells us
            // nothing about the declaration.
            if crate::safety::effect_of(sig.name) != crate::safety::Effect::Pure {
                continue;
            }
            for (label, v) in probe_values() {
                for piped in [true, false] {
                    let (args, input) = if piped {
                        (Vec::new(), Some(v.clone()))
                    } else {
                        (vec![v.clone()], None)
                    };
                    checked += 1;

                    // What the declaration says.
                    if crate::signature::validate(sig.name, &args, input.as_ref()).is_ok() {
                        continue;
                    }
                    refused += 1;

                    // What the body would have done.
                    let mut env = crate::env::Env::new();
                    let body = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        call_with_input_inner(sig.name, args.clone(), input.clone(), &mut env)
                    }));
                    if let Ok(Ok(out)) = body {
                        // Did the argument make any difference? A body that
                        // ignores its arguments succeeds for every input by
                        // construction, so its success is no evidence that the
                        // form is supported -- and refusing that argument is
                        // the whole point of declaring the builtin
                        // parameterless. Comparing against the bare call is
                        // what separates "the declaration is too narrow" from
                        // "the body was answering calls it should not".
                        //
                        // Without this the harness reported all 17
                        // `project_*` declarations as regressions at the
                        // moment they fixed the defect they were written for.
                        let mut bare_env = crate::env::Env::new();
                        let bare = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                            call_with_input_inner(sig.name, Vec::new(), None, &mut bare_env)
                        }));
                        // A piped value to a TAKES_NO_INPUT builtin is ignored
                        // by construction: tests/pipe_input_refused.rs derives
                        // that list from bodies that never read their input.
                        // Comparing outputs instead misread tool_schema and
                        // telemetry_report, whose answers change between calls.
                        let ignored = matches!(bare, Ok(Ok(ref b)) if *b == out)
                            || (piped
                                && crate::signature::TAKES_NO_INPUT
                                    .binary_search(&sig.name)
                                    .is_ok());
                        // A parameterless builtin whose own answer changes
                        // between identical calls (mount_info reads the live
                        // mount table) cannot be compared this way: the noise
                        // looks like the argument mattering. Refusing an
                        // argument is the point of declaring it parameterless,
                        // so a disagreement between two bare calls settles it.
                        // Two samples do not catch every jitter, so builtins
                        // whose answer is live system state are listed: their
                        // bodies bind `let _ = args`, so the argument provably
                        // cannot matter, and uptime ticks every second.
                        const LIVE_STATE: &[&str] = &["mount_info", "lsblk", "monitor_uptime"];
                        let noisy = (sig.params.is_empty() && LIVE_STATE.contains(&sig.name))
                            || sig.params.is_empty() && {
                                let mut again_env = crate::env::Env::new();
                                let again =
                                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                        call_with_input_inner(
                                            sig.name,
                                            Vec::new(),
                                            None,
                                            &mut again_env,
                                        )
                                    }));
                                match (&bare, &again) {
                                    (Ok(Ok(a)), Ok(Ok(b))) => a != b,
                                    _ => false,
                                }
                            };
                        if meaningful(&out) && !ignored && !noisy {
                            let position = if piped { "piped" } else { "direct" };
                            too_narrow.push(format!(
                                "{}({label}, {position}) -> declaration refuses, body returns {}",
                                sig.name,
                                out.type_name()
                            ));
                        }
                    }
                }
            }
        }

        let _ = std::fs::remove_dir_all(&jail);

        // Non-vacuity, both directions. A run where nothing was refused proves
        // the declarations accept everything; a run where nothing was checked
        // proves the filter is broken.
        assert!(
            checked > 200,
            "only {checked} (builtin, value, position) combinations probed; \
             the filter is broken and a sweep over nothing proves nothing"
        );
        assert!(
            refused > 20,
            "only {refused} of {checked} combinations were refused by a \
             declaration; either the probes are too weak or validation is not \
             running, and in both cases this test cannot fail"
        );

        assert!(
            too_narrow.is_empty(),
            "{} declared signature(s) refuse a call the body would have \
             honoured. A declaration is enforced before the body runs, so each \
             of these deletes a form of the language:\n{:#?}\n\
             ({checked} combinations probed, {refused} refused)",
            too_narrow.len(),
            too_narrow
        );
    }
}

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

    /// A fresh directory under the system temp dir. The process id keeps two
    /// test runs from sharing one.
    fn scratch(name: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("ae-quiet-walk-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn project_loc_counts_a_non_utf8_source_file() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("loc");
        std::fs::write(dir.join("main.rs"), b"fn main() {}\n").unwrap();
        // Latin-1 e-acute is not UTF-8. Three lines, the last unterminated.
        std::fs::write(dir.join("latin.rs"), b"// caf\xe9\nx\n\xe9").unwrap();
        let total = project_loc_in(&dir);
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(total.unwrap(), 4);
    }

    #[cfg(unix)]
    #[test]
    fn walks_refuse_a_directory_they_cannot_read() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        use std::os::unix::fs::PermissionsExt;
        // Root reads a mode-000 directory anyway, so there is nothing to refuse.
        let running_as_root = unsafe { libc::geteuid() } == 0;
        if running_as_root {
            return;
        }
        let dir = scratch("unreadable");
        let locked = dir.join("locked");
        std::fs::create_dir(&locked).unwrap();
        std::fs::write(locked.join("hidden.txt"), b"x").unwrap();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        let root = Value::Str(dir.to_string_lossy().to_string());
        let du = bi_fs_du(vec![root.clone()], None);
        let walk = bi_fs_walk(vec![root.clone()], None);
        let tree = bi_fs_tree(vec![root], None);
        // Restore before removing: a mode-000 directory cannot be emptied.
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(
            du.is_err(),
            "fs_du returned a size for a tree it could not read"
        );
        assert!(
            walk.is_err(),
            "fs_walk returned a listing for a tree it could not read"
        );
        assert!(
            tree.is_err(),
            "fs_tree rendered an unreadable directory as a leaf"
        );
    }
}

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

    /// A scratch directory unique to this process and test. Never changes cwd.
    fn scratch(name: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("ae-quietfs-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn path_arg(p: &std::path::Path) -> Vec<Value> {
        vec![Value::Str(p.to_string_lossy().into_owned())]
    }

    #[test]
    fn fs_stat_missing_path_is_null() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("stat_missing");
        let r = bi_fs_stat(path_arg(&dir.join("nope")), None);
        std::fs::remove_dir_all(&dir).ok();
        assert!(matches!(r, Ok(Value::Null)));
    }

    #[test]
    fn fs_stat_existing_file_is_a_record() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("stat_existing");
        let file = dir.join("plain.txt");
        std::fs::write(&file, b"abc").unwrap();
        let r = bi_fs_stat(path_arg(&file), None);
        std::fs::remove_dir_all(&dir).ok();
        match r {
            Ok(Value::Record(rec)) => assert!(matches!(rec.get("size"), Some(Value::Int(3)))),
            _ => panic!("expected a record for an existing file"),
        }
    }

    #[test]
    fn fs_stat_below_a_file_is_null() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("stat_below_file");
        let file = dir.join("plain");
        std::fs::write(&file, b"x").unwrap();
        let r = bi_fs_stat(path_arg(&file.join("x")), None);
        std::fs::remove_dir_all(&dir).ok();
        assert!(
            matches!(r, Ok(Value::Null)),
            "plain/x does not exist: {r:?}"
        );
    }

    /// A directory the caller may not search: its children cannot be
    /// checked, which is not the same as their being absent.
    #[cfg(unix)]
    #[test]
    fn a_stat_the_os_denies_is_an_error_not_absence() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        use std::os::unix::fs::PermissionsExt;
        if unsafe { libc::geteuid() } == 0 {
            return;
        }
        let dir = scratch("stat_denied");
        let locked = dir.join("locked");
        std::fs::create_dir(&locked).unwrap();
        std::fs::write(locked.join("f"), b"x").unwrap();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        let child = locked.join("f");
        let stat = bi_fs_stat(path_arg(&child), None);
        let exists = bi_file_exists(path_arg(&child), None);
        let text = read_text_lossy("project_readme", &child);
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::remove_dir_all(&dir).ok();
        assert!(stat.is_err(), "fs_stat: {stat:?}");
        assert!(exists.is_err(), "file_exists: {exists:?}");
        assert!(text.is_err(), "read_text_lossy: {text:?}");
    }

    #[test]
    fn fs_lstat_missing_path_is_null() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("lstat_missing");
        let r = bi_fs_lstat(path_arg(&dir.join("nope")), None);
        std::fs::remove_dir_all(&dir).ok();
        assert!(matches!(r, Ok(Value::Null)));
    }

    #[test]
    fn fs_realpath_missing_path_is_null() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("realpath_missing");
        let r = bi_fs_realpath(path_arg(&dir.join("nope")), None);
        std::fs::remove_dir_all(&dir).ok();
        assert!(matches!(r, Ok(Value::Null)));
    }

    #[test]
    fn file_exists_missing_is_false() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("exists_missing");
        let r = bi_file_exists(path_arg(&dir.join("nope")), None);
        std::fs::remove_dir_all(&dir).ok();
        match r {
            Ok(Value::Record(rec)) => {
                assert!(matches!(rec.get("exists"), Some(Value::Bool(false))));
                assert!(matches!(rec.get("is_file"), Some(Value::Bool(false))));
                assert!(matches!(rec.get("is_dir"), Some(Value::Bool(false))));
            }
            _ => panic!("expected a record"),
        }
    }

    #[test]
    fn file_exists_below_a_file_is_false() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("exists_below_file");
        let file = dir.join("plain");
        std::fs::write(&file, b"x").unwrap();
        let r = bi_file_exists(path_arg(&file.join("x")), None);
        std::fs::remove_dir_all(&dir).ok();
        assert!(
            matches!(&r, Ok(Value::Record(rec)) if matches!(rec.get("exists"), Some(Value::Bool(false)))),
            "{r:?}"
        );
    }

    #[test]
    fn read_text_lossy_keeps_latin1_text() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("lossy_latin1");
        let file = dir.join("README.md");
        std::fs::write(&file, [b'c', b'a', b'f', 0xE9, b'\n']).unwrap();
        let got = read_text_lossy("project_readme", &file);
        std::fs::remove_dir_all(&dir).ok();
        assert_eq!(got.unwrap().as_deref(), Some("caf\u{FFFD}\n"));
    }

    #[test]
    fn read_text_lossy_missing_file_is_none() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("lossy_missing");
        let got = read_text_lossy("project_readme", &dir.join("README.md"));
        std::fs::remove_dir_all(&dir).ok();
        assert!(matches!(got, Ok(None)));
    }

    #[test]
    fn read_text_lossy_of_a_directory_is_an_error() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = scratch("lossy_dir");
        let got = read_text_lossy("project_readme", &dir);
        std::fs::remove_dir_all(&dir).ok();
        assert!(got.is_err(), "{got:?}");
    }
}

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

    fn tool_run(code: Option<i32>) -> ToolRun {
        ToolRun {
            command: "tool".to_string(),
            keep: Keep::Tail(0),
            success: code == Some(0),
            code,
            stdout: String::new(),
            stdout_truncated: false,
            stderr: String::new(),
            stderr_truncated: false,
        }
    }

    #[test]
    fn exit_code_is_null_without_a_code() {
        let killed = run_fields(tool_run(None), "stdout", "stderr");
        assert_eq!(killed.get("exit_code"), Some(&Value::Null));
        let exited = run_fields(tool_run(Some(3)), "stdout", "stderr");
        assert_eq!(exited.get("exit_code"), Some(&Value::Int(3)));
    }

    #[test]
    fn ssh_port_accepts_only_1_to_65535() {
        assert_eq!(ssh_port_value("2222"), Some(2222));
        assert_eq!(ssh_port_value("65535"), Some(65535));
        assert_eq!(ssh_port_value("0"), None);
        assert_eq!(ssh_port_value("65536"), None);
        assert_eq!(ssh_port_value("ssh"), None);
        assert_eq!(ssh_port_value(""), None);
    }

    #[test]
    fn env_read_classifies_unset_and_non_utf8() {
        assert_eq!(
            env_read("env", "X", Ok("v".to_string())).unwrap(),
            Some("v".to_string())
        );
        assert_eq!(
            env_read("env", "X", Err(std::env::VarError::NotPresent)).unwrap(),
            None
        );
        let err = env_read(
            "env_var",
            "AE_BAD",
            Err(std::env::VarError::NotUnicode(std::ffi::OsString::from(
                "x",
            ))),
        )
        .unwrap_err();
        assert!(err.to_string().contains("AE_BAD"), "{err}");
    }
}

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

    fn obj(json: &str) -> serde_json::Map<String, serde_json::Value> {
        serde_json::from_str::<serde_json::Value>(json)
            .unwrap()
            .as_object()
            .unwrap()
            .clone()
    }

    fn int_field(v: &Value, key: &str) -> Option<i64> {
        match v {
            Value::Record(r) => match r.get(key) {
                Some(Value::Int(n)) => Some(*n),
                _ => None,
            },
            _ => None,
        }
    }

    #[test]
    fn tmux_no_server_is_only_the_absent_server() {
        assert!(tmux_no_server(
            "no server running on /tmp/tmux-1000/default\n"
        ));
        assert!(tmux_no_server(
            "error connecting to /tmp/tmux-1001/default (No such file or directory)"
        ));
        // A socket the caller may not open is a failure, not an empty list.
        assert!(!tmux_no_server(
            "error connecting to /tmp/tmux-1000/default (Permission denied)"
        ));
        assert!(!tmux_no_server("unknown option -- Z"));
    }

    #[test]
    fn tmux_session_lines_parse_strictly() {
        let Ok(Value::Record(r)) = tmux_session_record("main:3:1") else {
            panic!("a well-formed session line must parse");
        };
        assert!(matches!(r.get("name"), Some(Value::Str(s)) if s == "main"));
        assert!(matches!(r.get("windows"), Some(Value::Int(3))));
        assert!(matches!(r.get("attached"), Some(Value::Bool(true))));
        assert!(tmux_session_record("main:0:0").is_ok());
        assert!(tmux_session_record("main:x:1").is_err());
        assert!(tmux_session_record("main:3").is_err());
        assert!(tmux_session_record("main:3:yes").is_err());
    }

    #[test]
    fn windows_counters_require_every_field() {
        let row = net_counter_record(
            "net_counters",
            &obj(r#"{"Name":"Ethernet","ReceivedBytes":10,"SentBytes":20,"ReceivedUnicastPackets":3,"SentUnicastPackets":4}"#),
        )
        .unwrap();
        assert_eq!(int_field(&row, "rx_bytes"), Some(10));
        assert_eq!(int_field(&row, "tx_bytes"), Some(20));
        assert_eq!(int_field(&row, "rx_packets"), Some(3));
        assert_eq!(int_field(&row, "tx_packets"), Some(4));
        // A missing counter is refused, not reported as 0 bytes.
        assert!(net_counter_record(
            "net_counters",
            &obj(r#"{"Name":"Ethernet","ReceivedBytes":10,"ReceivedUnicastPackets":3,"SentUnicastPackets":4}"#),
        )
        .is_err());
        // A counter that is not an integer is refused too.
        assert!(net_counter_record(
            "net_counters",
            &obj(r#"{"Name":"Ethernet","ReceivedBytes":"10","SentBytes":20,"ReceivedUnicastPackets":3,"SentUnicastPackets":4}"#),
        )
        .is_err());
    }

    #[test]
    fn socket_ports_are_real_ports() {
        let o = obj(r#"{"LocalPort":8080,"RemotePort":0,"Other":"x"}"#);
        assert_eq!(
            net_socket_port("net_sockets", &o, "LocalPort").ok(),
            Some(8080)
        );
        // Remote port 0 is the table's "no peer" (a listener): read as 0.
        assert_eq!(
            net_remote_port("net_sockets", &o, "RemotePort").ok(),
            Some(0)
        );
        assert!(net_remote_port("net_sockets", &o, "Missing").is_err());
        assert!(
            net_remote_port("net_sockets", &obj(r#"{"RemotePort":70000}"#), "RemotePort").is_err()
        );
        assert!(net_socket_port("net_sockets", &o, "RemotePort").is_err());
        assert!(net_socket_port("net_sockets", &o, "Missing").is_err());
        assert!(
            net_socket_port("net_sockets", &obj(r#"{"LocalPort":"80"}"#), "LocalPort").is_err()
        );
        assert!(
            net_socket_port("net_sockets", &obj(r#"{"LocalPort":70000}"#), "LocalPort").is_err()
        );
    }

    #[test]
    fn battery_capacity_is_a_percentage_or_refused() {
        let path = "/sys/class/power_supply/BAT0/capacity";
        assert_eq!(battery_capacity_from(path, "87\n").ok(), Some(87));
        assert_eq!(battery_capacity_from(path, " 0 ").ok(), Some(0));
        assert!(battery_capacity_from(path, "").is_err());
        assert!(battery_capacity_from(path, "unknown\n").is_err());
    }
}

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

    fn obj(v: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        match v {
            serde_json::Value::Object(m) => m,
            other => panic!("not a JSON object: {other}"),
        }
    }

    #[test]
    fn required_field_is_refused_when_missing_or_not_a_string() {
        let o = obj(serde_json::json!({"Name": "Ethernet", "Count": 3}));
        assert_eq!(
            net_req_str("net_interfaces", "powershell", &o, "Name").unwrap(),
            "Ethernet"
        );
        assert!(net_req_str("net_interfaces", "powershell", &o, "IPAddress").is_err());
        assert!(net_req_str("net_interfaces", "powershell", &o, "Count").is_err());
    }

    #[test]
    fn optional_field_is_left_out_not_read_as_empty() {
        // A virtual adapter: no MacAddress key at all.
        let o = obj(serde_json::json!({
            "Name": "vEthernet (Default Switch)",
            "InterfaceDescription": "Hyper-V Virtual Ethernet Adapter",
            "Status": "Up",
            "LinkSpeed": "10 Gbps"
        }));
        let Value::Record(r) = net_interface_record("net_interfaces", &o).unwrap() else {
            panic!("not a record");
        };
        assert!(!r.contains_key("mac"));
        assert!(
            matches!(r.get("name"), Some(Value::Str(s)) if s.as_str() == "vEthernet (Default Switch)")
        );
        assert!(matches!(r.get("status"), Some(Value::Str(s)) if s.as_str() == "Up"));
        assert!(r.contains_key("description"));
        assert!(r.contains_key("speed"));
    }

    #[test]
    fn identity_field_missing_refuses_the_whole_record() {
        let o = obj(serde_json::json!({"InterfaceDescription": "x"}));
        assert!(net_interface_record("net_interfaces", &o).is_err());
    }

    #[test]
    fn windows_state_names_and_unnamed_codes() {
        assert_eq!(windows_state_name(5), "ESTABLISHED");
        assert_eq!(windows_state_name(2), "LISTEN");
        assert_eq!(windows_state_name(100), "BOUND");
        assert_eq!(windows_state_name(99), "UNKNOWN");
    }

    #[test]
    fn macos_netstat_endpoints_read_as_addr_colon_port() {
        assert_eq!(macos_netstat_endpoint("127.0.0.1.49817"), "127.0.0.1:49817");
        assert_eq!(macos_netstat_endpoint("*.*"), "*:*");
        assert_eq!(macos_netstat_endpoint("*.22"), "*:22");
        assert_eq!(macos_netstat_endpoint("::1.5353"), "[::1]:5353");
    }

    #[test]
    fn macos_netstat_rows_list_the_listener_on_its_port() {
        // The shape of `netstat -an -p tcp` on macOS: two header lines, then
        // one row per socket.
        let sample = [
            "Active Internet connections (including servers)",
            "Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)",
            "tcp4       0      0  127.0.0.1.49817        *.*                    LISTEN",
            "tcp4       0      0  127.0.0.1.49817        127.0.0.1.50012        ESTABLISHED",
        ]
        .join("\n");
        let rows = macos_netstat_rows("net_ports", &sample).unwrap();
        assert_eq!(rows.len(), 2);
        let field = |i: usize, key: &str| match &rows[i] {
            Value::Record(r) => match r.get(key) {
                Some(Value::Str(s)) => s.clone(),
                other => panic!("no {key} in row {i}: {other:?}"),
            },
            other => panic!("row {i} is not a record: {other:?}"),
        };
        assert_eq!(field(0, "local"), "127.0.0.1:49817");
        assert_eq!(field(0, "peer"), "*:*");
        assert!(net_is_listening(&rows[0]));
        assert!(!net_is_listening(&rows[1]));
    }
}

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

    fn str_field(v: &Value, key: &str) -> Option<String> {
        match v {
            Value::Record(r) => match r.get(key) {
                Some(Value::Str(s)) => Some(s.clone()),
                _ => None,
            },
            _ => None,
        }
    }

    #[test]
    fn windows_array_of_two_services_becomes_two_records() {
        let json = r#"[{"Name":"Spooler","DisplayName":"Print Spooler","Status":4},{"Name":"BITS","DisplayName":"Background Intelligent Transfer Service","Status":1}]"#;
        let recs = win_service_records("svc_list", json).unwrap();
        assert_eq!(recs.len(), 2);
        assert_eq!(str_field(&recs[0], "name").as_deref(), Some("Spooler"));
        assert_eq!(str_field(&recs[0], "status").as_deref(), Some("running"));
        assert_eq!(str_field(&recs[1], "name").as_deref(), Some("BITS"));
        assert_eq!(str_field(&recs[1], "status").as_deref(), Some("stopped"));
    }

    #[test]
    fn windows_single_object_becomes_one_record() {
        let json = r#"{"Name":"sshd","DisplayName":"OpenSSH","Status":2}"#;
        let recs = win_service_records("svc_list", json).unwrap();
        assert_eq!(recs.len(), 1);
        assert_eq!(str_field(&recs[0], "name").as_deref(), Some("sshd"));
        assert_eq!(
            str_field(&recs[0], "status").as_deref(),
            Some("start_pending")
        );
    }

    #[test]
    fn windows_empty_stdout_is_no_services() {
        assert!(win_service_records("svc_list", "").unwrap().is_empty());
        assert!(win_service_records("svc_list", " \r\n\t ")
            .unwrap()
            .is_empty());
    }

    #[test]
    fn windows_garbage_is_refused() {
        assert!(win_service_records("svc_list", "Get-Service: access denied").is_err());
        assert!(win_service_records("svc_list", "42").is_err());
        assert!(win_service_records("svc_list", "\"text\"").is_err());
    }

    #[test]
    fn windows_item_missing_name_is_refused() {
        let json = r#"[{"Name":"ok","Status":4},{"DisplayName":"no name","Status":4}]"#;
        assert!(win_service_records("svc_list", json).is_err());
    }

    #[test]
    fn windows_item_that_is_not_an_object_is_refused() {
        let json = r#"[{"Name":"ok"},"stray"]"#;
        assert!(win_service_records("svc_list", json).is_err());
    }

    #[test]
    fn systemd_array_of_objects_passes_through_as_array() {
        let json = r#"[{"unit":"cron.service","load":"loaded","active":"active","sub":"running","description":"Regular jobs"}]"#;
        match systemd_units("svc_list", json).unwrap() {
            Value::Array(items) => {
                assert_eq!(items.len(), 1);
                assert_eq!(
                    str_field(&items[0], "unit").as_deref(),
                    Some("cron.service")
                );
            }
            other => panic!("expected an array, got {}", other.type_name()),
        }
    }

    #[test]
    fn systemd_empty_or_garbage_or_non_array_is_refused() {
        assert!(systemd_units("svc_list", "").is_err());
        assert!(systemd_units("svc_list", "Failed to connect to bus").is_err());
        assert!(systemd_units("svc_list", r#"{"unit":"x.service"}"#).is_err());
        assert!(systemd_units("svc_list", r#"[1, 2]"#).is_err());
    }
}

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

    fn scratch(name: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("ae-capped-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn code(e: &anyhow::Error) -> Option<crate::safety::ErrorCode> {
        e.downcast_ref::<crate::safety::SafetyError>()
            .map(|se| se.code)
    }

    #[test]
    fn a_file_within_the_limit_is_read_whole() {
        let dir = scratch("within");
        let p = dir.join("f.txt");
        std::fs::write(&p, "abcd").unwrap();
        assert_eq!(read_text_capped_at("t", &p, 4).unwrap(), "abcd");
    }

    #[test]
    fn a_file_over_the_limit_is_a_budget_refusal() {
        let dir = scratch("over");
        let p = dir.join("f.txt");
        std::fs::write(&p, "abcde").unwrap();
        let e = read_text_capped_at("t", &p, 4).unwrap_err();
        assert_eq!(code(&e), Some(crate::safety::ErrorCode::BudgetExceeded));
    }

    #[test]
    fn a_missing_file_is_not_found() {
        let dir = scratch("missing");
        let e = read_text_capped_at("t", &dir.join("none"), 4).unwrap_err();
        assert_eq!(code(&e), Some(crate::safety::ErrorCode::NotFound));
    }

    #[test]
    fn the_file_size_check_is_coded() {
        let e = crate::security::check_file_size_limit(u64::MAX).unwrap_err();
        assert_eq!(code(&e), Some(crate::safety::ErrorCode::BudgetExceeded));
    }
}

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

    fn temp_file(name: &str, body: &str) -> String {
        let path = std::env::temp_dir().join(format!("ae-cr-{}-{name}", std::process::id()));
        std::fs::write(&path, body).expect("write temp file");
        path.display().to_string()
    }

    #[test]
    fn get_content_returns_every_line_of_a_small_file() {
        let path = temp_file("get-content.txt", "alpha\nbeta\n");
        let result = bi_get_content(vec![Value::Str(path.clone())], None);
        let _ = std::fs::remove_file(&path);
        match result.expect("get_content reads a small file") {
            Value::Array(lines) => {
                let lines: Vec<String> = lines
                    .into_iter()
                    .map(|v| match v {
                        Value::Str(s) => s,
                        other => panic!("expected a string line, got {other:?}"),
                    })
                    .collect();
                assert_eq!(lines, vec!["alpha".to_string(), "beta".to_string()]);
            }
            other => panic!("expected an array of lines, got {other:?}"),
        }
    }

    #[test]
    fn code_todos_still_reads_a_small_file() {
        let path = temp_file("code-todos.rs", "fn a() {}\n// TODO: later\n");
        let result = bi_code_todos(vec![Value::Str(path.clone())], None);
        let _ = std::fs::remove_file(&path);
        assert!(
            result.is_ok(),
            "code_todos should read the file: {result:?}"
        );
    }

    #[test]
    fn get_content_on_a_missing_file_is_still_not_found() {
        let path = std::env::temp_dir()
            .join(format!("ae-cr-{}-missing.txt", std::process::id()))
            .display()
            .to_string();
        let err =
            bi_get_content(vec![Value::Str(path)], None).expect_err("a missing file is an error");
        let safety = err
            .downcast_ref::<crate::safety::SafetyError>()
            .expect("the error carries a safety code");
        assert!(matches!(safety.code, crate::safety::ErrorCode::NotFound));
    }
}

#[cfg(test)]
mod walk_cap_tests {
    use super::*;
    use crate::safety::ErrorCode;

    fn is_budget(e: &anyhow::Error) -> bool {
        e.downcast_ref::<crate::safety::SafetyError>()
            .is_some_and(|s| matches!(s.code, ErrorCode::BudgetExceeded))
    }

    /// A fresh directory under the temp dir, holding `n` files.
    fn fixture(name: &str, n: usize) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("ae-wc-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        for i in 0..n {
            std::fs::write(dir.join(format!("f{i}.txt")), b"x").unwrap();
        }
        dir
    }

    #[test]
    fn push_capped_refuses_the_entry_past_the_cap() {
        let mut out = Vec::new();
        for i in 0..3 {
            push_capped("find", &mut out, Value::Int(i), 3).unwrap();
        }
        let e = push_capped("find", &mut out, Value::Int(3), 3).unwrap_err();
        assert!(is_budget(&e));
        assert_eq!(out.len(), 3);
    }

    #[test]
    fn walk_refuses_when_entries_exceed_the_cap() {
        let dir = fixture("over", 5);
        let result = walk_entries_capped(&dir, 100, 3);
        let _ = std::fs::remove_dir_all(&dir);
        assert!(is_budget(&result.unwrap_err()));
    }

    #[test]
    fn walk_succeeds_when_the_cap_is_not_exceeded() {
        let dir = fixture("under", 5);
        let result = walk_entries_capped(&dir, 100, 5);
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(result.unwrap().len(), 5);
    }
}

#[cfg(test)]
mod range_cap_tests {
    use super::*;
    use crate::safety::ErrorCode;

    fn ints(args: Vec<Value>) -> Result<Vec<i64>> {
        match bi_range(args, None)? {
            Value::Array(items) => Ok(items
                .into_iter()
                .map(|v| match v {
                    Value::Int(n) => n,
                    other => panic!("expected Int, got {:?}", other),
                })
                .collect()),
            other => panic!("expected Array, got {:?}", other),
        }
    }

    fn code_of(err: anyhow::Error) -> ErrorCode {
        err.downcast_ref::<crate::safety::SafetyError>()
            .map(|s| s.code)
            .expect("a SafetyError")
    }

    #[test]
    fn plain_ranges_are_unchanged() {
        assert_eq!(ints(vec![Value::Int(5)]).unwrap(), vec![0, 1, 2, 3, 4]);
        assert_eq!(
            ints(vec![Value::Int(0), Value::Int(10), Value::Int(3)]).unwrap(),
            vec![0, 3, 6, 9]
        );
        assert_eq!(
            ints(vec![Value::Int(5), Value::Int(0), Value::Int(-2)]).unwrap(),
            vec![5, 3, 1]
        );
    }

    #[test]
    fn oversized_range_is_refused_before_allocation() {
        match bi_range(vec![Value::Int(0), Value::Int(20_000_000)], None) {
            Ok(_) => panic!("a 20,000,000 element range must be refused"),
            Err(e) => assert_eq!(code_of(e), ErrorCode::BudgetExceeded),
        }
    }

    #[test]
    fn zero_step_is_a_bad_argument() {
        match bi_range(vec![Value::Int(0), Value::Int(1), Value::Int(0)], None) {
            Ok(_) => panic!("a zero step must be refused"),
            Err(e) => assert_eq!(code_of(e), ErrorCode::BadArg),
        }
    }

    #[test]
    fn range_near_the_i64_limits_does_not_overflow() {
        assert_eq!(
            ints(vec![
                Value::Int(9_223_372_036_854_775_800),
                Value::Int(9_223_372_036_854_775_807),
                Value::Int(100),
            ])
            .unwrap(),
            vec![9_223_372_036_854_775_800]
        );
        assert_eq!(
            ints(vec![
                Value::Int(-9_223_372_036_854_775_803),
                Value::Int(-9_223_372_036_854_775_808),
                Value::Int(-100),
            ])
            .unwrap(),
            vec![-9_223_372_036_854_775_803]
        );
    }
}

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

    fn scratch(name: &str, body: &[u8]) -> std::path::PathBuf {
        let path = std::env::temp_dir().join(format!("ae-cb-{}-{name}", std::process::id()));
        std::fs::write(&path, body).expect("write temp file");
        path
    }

    fn budget_code(e: &anyhow::Error) -> Option<crate::safety::ErrorCode> {
        e.downcast_ref::<crate::safety::SafetyError>()
            .map(|s| s.code)
    }

    #[test]
    fn read_bytes_capped_at_under_at_and_over_the_limit() {
        let under = scratch("under", &[7u8; 15]);
        let at = scratch("at", &[7u8; 16]);
        let over = scratch("over", &[7u8; 17]);

        assert_eq!(
            read_bytes_capped_at("t", &under, 16).unwrap(),
            vec![7u8; 15]
        );
        assert_eq!(read_bytes_capped_at("t", &at, 16).unwrap(), vec![7u8; 16]);
        let e = read_bytes_capped_at("t", &over, 16).unwrap_err();
        assert_eq!(
            budget_code(&e),
            Some(crate::safety::ErrorCode::BudgetExceeded)
        );

        for p in [under, at, over] {
            let _ = std::fs::remove_file(p);
        }
    }

    #[test]
    fn read_bytes_capped_at_missing_file_is_not_found() {
        let missing =
            std::env::temp_dir().join(format!("ae-cb-{}-no-such-file", std::process::id()));
        let e = read_bytes_capped_at("t", &missing, 16).unwrap_err();
        assert!(capped_read_not_found(&e), "{e:#}");
        assert_eq!(budget_code(&e), Some(crate::safety::ErrorCode::NotFound));
    }

    #[test]
    fn read_text_capped_at_rejects_invalid_utf8() {
        let bad = scratch("bad-utf8", &[b'a', 0xff, 0xfe, b'b']);
        let good = scratch("good-utf8", "héllo".as_bytes());

        assert!(read_text_capped_at("t", &bad, 1024).is_err());
        assert_eq!(read_text_capped_at("t", &good, 1024).unwrap(), "héllo");

        for p in [bad, good] {
            let _ = std::fs::remove_file(p);
        }
    }

    #[test]
    fn read_text_lossy_under_a_regular_file_is_absent() {
        let f = std::env::temp_dir().join(format!("ae-cb-{}-plainfile", std::process::id()));
        std::fs::write(&f, "x").unwrap();
        let under = f.join("README.md");
        let got = read_text_lossy("t", &under);
        let _ = std::fs::remove_file(&f);
        assert!(matches!(got, Ok(None)), "{got:?}");
    }
}

#[cfg(test)]
mod glob_cap_tests {
    use crate::posix::{glob_paths, glob_paths_capped};

    fn dir_with_five(name: &str) -> std::path::PathBuf {
        let root = std::env::temp_dir().join(format!("ae-gc-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        for f in ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"] {
            std::fs::write(root.join(f), "").unwrap();
        }
        root
    }

    #[test]
    fn capped_glob_refuses_over_and_matches_below() {
        let _env = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let root = dir_with_five("caps");
        let base = root.to_string_lossy().replace('\\', "/");
        let pattern = format!("{base}/*.txt");

        let (none, over) = glob_paths_capped(&pattern, 3);
        assert!(over, "5 matches must be over a cap of 3");
        assert!(none.is_empty(), "nothing is returned once over: {none:?}");

        let (all, over) = glob_paths_capped(&pattern, 5);
        assert!(!over);
        assert_eq!(all.len(), 5);
        assert_eq!(all, glob_paths(&pattern));
        let names: Vec<&str> = all.iter().map(|p| p.rsplit('/').next().unwrap()).collect();
        assert_eq!(names, ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"]);

        // The recursive form gathers the same names.
        let recursive = format!("{base}/**/*.txt");
        let (r, over) = glob_paths_capped(&recursive, 5);
        assert!(!over);
        assert_eq!(r, glob_paths(&recursive));
        assert_eq!(r.len(), 5);
        let _ = std::fs::remove_dir_all(&root);
    }
}

#[cfg(test)]
mod atomic_write_tests {
    use super::{gzip_file_capped, write_file_atomically};
    use std::path::{Path, PathBuf};

    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("ae-aw-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn has_no_temporary(dir: &Path) -> bool {
        std::fs::read_dir(dir).unwrap().all(|entry| {
            !entry
                .unwrap()
                .file_name()
                .to_string_lossy()
                .starts_with(".ironshell_tmp_")
        })
    }

    #[test]
    fn overwrite_keeps_content_and_leaves_no_temporary() {
        let dir = scratch("content");
        let target = dir.join("config.txt");
        std::fs::write(&target, "old").unwrap();
        write_file_atomically("file_write", target.to_str().unwrap(), b"new line\n").unwrap();
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "new line\n");
        assert!(has_no_temporary(&dir));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn overwrite_keeps_execute_mode() {
        use std::os::unix::fs::PermissionsExt;
        let dir = scratch("mode");
        let target = dir.join("run.sh");
        std::fs::write(&target, "#!/bin/sh\necho old\n").unwrap();
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).unwrap();
        write_file_atomically(
            "file_write",
            target.to_str().unwrap(),
            b"#!/bin/sh\necho new\n",
        )
        .unwrap();
        let mode = std::fs::metadata(&target).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o755);
        assert_eq!(
            std::fs::read_to_string(&target).unwrap(),
            "#!/bin/sh\necho new\n"
        );
        assert!(has_no_temporary(&dir));
        let _ = std::fs::remove_dir_all(&dir);
    }

    // Decision: a read-only file is refused, as the OS refuses it. The rename
    // onto a read-only target fails, the content is unchanged, and no temporary
    // is left behind (its read-only copy is made writable before removal).
    #[cfg(windows)]
    #[test]
    #[allow(clippy::permissions_set_readonly_false)] // cleanup only: clears the attribute so the directory can be removed
    fn overwrite_of_read_only_file_is_refused() {
        let dir = scratch("readonly");
        let target = dir.join("locked.txt");
        std::fs::write(&target, "old").unwrap();
        let mut permissions = std::fs::metadata(&target).unwrap().permissions();
        permissions.set_readonly(true);
        std::fs::set_permissions(&target, permissions).unwrap();
        let result = write_file_atomically("file_write", target.to_str().unwrap(), b"new");
        assert!(result.is_err());
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "old");
        assert!(has_no_temporary(&dir));
        let mut permissions = std::fs::metadata(&target).unwrap().permissions();
        permissions.set_readonly(false);
        std::fs::set_permissions(&target, permissions).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn write_through_symlink_updates_target_and_keeps_link() {
        let dir = scratch("symlink");
        let target = dir.join("real.txt");
        let link = dir.join("link.txt");
        std::fs::write(&target, "old").unwrap();
        std::os::unix::fs::symlink(&target, &link).unwrap();
        write_file_atomically("file_write", link.to_str().unwrap(), b"new").unwrap();
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "new");
        assert!(std::fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink());
        assert_eq!(std::fs::read_to_string(&link).unwrap(), "new");
        assert!(has_no_temporary(&dir));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn gzip_refuses_existing_output_and_leaves_it_untouched() {
        let dir = scratch("gzip");
        let input = dir.join("data.txt");
        let output = dir.join("data.txt.gz");
        std::fs::write(&input, "payload").unwrap();
        std::fs::write(&output, "keep me").unwrap();
        let result = gzip_file_capped(
            "gzip_compress",
            input.to_str().unwrap(),
            output.to_str().unwrap(),
            false,
            1024,
        );
        assert!(result.is_err());
        assert_eq!(std::fs::read_to_string(&output).unwrap(), "keep me");
        let _ = std::fs::remove_dir_all(&dir);
    }
}

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

    fn entries(items: &[(&str, Option<&str>)]) -> Vec<(String, Option<String>)> {
        items
            .iter()
            .map(|(n, t)| (n.to_string(), t.map(str::to_string)))
            .collect()
    }

    fn check(items: &[(&str, Option<&str>)]) -> bool {
        check_archive_entries("tar_extract", entries(items).into_iter()).is_ok()
    }

    #[test]
    fn relative_names_inside_the_destination_are_allowed() {
        assert!(!archive_entry_escapes("a/b.txt"));
        assert!(!archive_entry_escapes("a"));
        assert!(!archive_entry_escapes("a/"));
        assert!(!archive_entry_escapes("./a/b"));
        // `..` is only special as a whole component.
        assert!(!archive_entry_escapes("a..b/c"));
        assert!(!archive_entry_escapes("dir/..hidden"));
    }

    #[test]
    fn escaping_names_are_refused() {
        for name in [
            "../x",
            "a/../../x",
            "/etc/passwd",
            "\\\\server\\share\\x",
            "C:\\x",
            "C:x",
            "a\\..\\..\\x",
            "..",
            "a/..",
        ] {
            assert!(archive_entry_escapes(name), "{name} should be refused");
        }
    }

    #[test]
    fn symlink_targets_are_checked_like_names() {
        assert!(check(&[("a", Some("b"))]));
        assert!(check(&[("a", Some("sub/b"))]));
        assert!(!check(&[("a", Some("../../etc"))]));
        assert!(!check(&[("a", Some("/etc"))]));
        assert!(check(&[("a/b.txt", None)]));
    }

    #[test]
    fn an_xz_tar_is_listed_through_the_tar_tool() {
        let dir =
            std::env::temp_dir().join(format!("ae_prescan_xz_{}", uuid::Uuid::new_v4().simple()));
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src").join("a.txt"), "a").unwrap();
        let archive = dir.join("t.tar.xz");
        let made = crate::safety::child_command("tar")
            .arg("-cJf")
            .arg(&archive)
            .arg("-C")
            .arg(dir.join("src"))
            .arg("a.txt")
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        if !made {
            let _ = std::fs::remove_dir_all(&dir);
            eprintln!("skipped: this tar cannot write xz");
            return;
        }
        let names = tar_archive_entries("tar_extract", archive.to_str().unwrap());
        let _ = std::fs::remove_dir_all(&dir);
        let names = names.unwrap();
        assert!(names
            .iter()
            .any(|(n, t)| n.trim_end_matches('/') == "a.txt" && t.is_none()));
    }

    #[test]
    fn an_xz_tar_has_its_link_targets_checked() {
        use std::io::Write;
        let dir = std::env::temp_dir().join(format!(
            "ae_prescan_xzlink_{}",
            uuid::Uuid::new_v4().simple()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let mut raw = Vec::new();
        {
            let mut b = tar::Builder::new(&mut raw);
            let mut h = tar::Header::new_gnu();
            h.set_path("a").unwrap();
            h.set_entry_type(tar::EntryType::Symlink);
            h.set_link_name("../../etc").unwrap();
            h.set_size(0);
            h.set_cksum();
            b.append(&h, std::io::empty()).unwrap();
            b.finish().unwrap();
        }
        let xz = crate::safety::child_command("xz")
            .arg("-c")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn();
        let Ok(mut xz) = xz else {
            let _ = std::fs::remove_dir_all(&dir);
            eprintln!("skipped: no xz on PATH");
            return;
        };
        let mut stdin = xz.stdin.take().unwrap();
        let feed = std::thread::spawn(move || stdin.write_all(&raw));
        let out = xz.wait_with_output().unwrap();
        feed.join().unwrap().unwrap();
        assert!(out.status.success());
        let archive = dir.join("evil.tar.xz");
        std::fs::write(&archive, &out.stdout).unwrap();
        let listed = tar_archive_entries("tar_extract", archive.to_str().unwrap());
        let _ = std::fs::remove_dir_all(&dir);
        let listed = listed.unwrap();
        assert_eq!(listed, entries(&[("a", Some("../../etc"))]));
        assert!(check_archive_entries("tar_extract", listed.into_iter()).is_err());
    }

    #[test]
    fn a_corrupt_xz_stream_is_a_tool_failure() {
        let dir = std::env::temp_dir().join(format!(
            "ae_prescan_xzbad_{}",
            uuid::Uuid::new_v4().simple()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let archive = dir.join("bad.tar.xz");
        // xz magic, then garbage.
        std::fs::write(&archive, [0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00, 1, 2, 3, 4]).unwrap();
        let mut xz = crate::safety::child_command("xz");
        xz.arg("--version");
        let have_xz = bounded_cmd_output("tar_extract", "xz", xz, PROBE_DEADLINE_SECS).is_ok();
        let listed = tar_archive_entries("tar_extract", archive.to_str().unwrap());
        let _ = std::fs::remove_dir_all(&dir);
        if !have_xz {
            eprintln!("skipped: no xz on PATH");
            return;
        }
        assert!(listed.is_err());
    }

    #[test]
    fn one_escaping_entry_refuses_the_whole_archive() {
        assert!(!check(&[
            ("ok.txt", None),
            ("../x", None),
            ("ok2.txt", None)
        ]));
        assert!(check(&[("ok.txt", None), ("dir/ok2.txt", None)]));
    }

    #[test]
    fn too_many_entries_are_refused() {
        let items = (0..=WALK_MAX_ENTRIES).map(|_| ("a".to_string(), None));
        assert!(check_archive_entries("tar_extract", items).is_err());
    }

    #[test]
    fn a_declared_total_over_the_budget_is_budget_exceeded() {
        assert!(check_archive_budget("tar_extract", ARCHIVE_EXTRACT_MAX_BYTES).is_ok());
        let err = check_archive_budget("tar_extract", ARCHIVE_EXTRACT_MAX_BYTES + 1)
            .expect_err("one byte over must be refused");
        assert!(format!("{err}").contains("E_BUDGET_EXCEEDED"), "{err}");
    }

    #[test]
    fn a_zip_listing_totals_its_declared_sizes() {
        use std::io::Write;
        let dir =
            std::env::temp_dir().join(format!("ae_budget_zip_{}", uuid::Uuid::new_v4().simple()));
        std::fs::create_dir_all(&dir).unwrap();
        let archive = dir.join("sizes.zip");
        {
            let file = std::fs::File::create(&archive).unwrap();
            let mut w = zip::ZipWriter::new(file);
            let opts = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            w.start_file("a.bin", opts).unwrap();
            w.write_all(b"abc").unwrap();
            w.start_file("b.bin", opts).unwrap();
            w.write_all(b"defgh").unwrap();
            w.finish().unwrap();
        }
        let listed = zip_archive_entries("zip_extract", archive.to_str().unwrap());
        let _ = std::fs::remove_dir_all(&dir);
        let (names, declared) = listed.unwrap();
        assert_eq!(names.len(), 2);
        assert_eq!(declared, 8);
    }

    #[test]
    fn a_tar_listing_totals_its_declared_sizes() {
        let dir =
            std::env::temp_dir().join(format!("ae_budget_tar_{}", uuid::Uuid::new_v4().simple()));
        std::fs::create_dir_all(&dir).unwrap();
        let archive = dir.join("sizes.tar");
        {
            let file = std::fs::File::create(&archive).unwrap();
            let mut b = tar::Builder::new(file);
            for (name, body) in [("a.bin", &b"abc"[..]), ("b.bin", &b"defgh"[..])] {
                let mut h = tar::Header::new_gnu();
                h.set_path(name).unwrap();
                h.set_size(body.len() as u64);
                h.set_mode(0o644);
                h.set_cksum();
                b.append(&h, body).unwrap();
            }
            b.finish().unwrap();
        }
        let listed = tar_archive_listing("tar_extract", archive.to_str().unwrap());
        let _ = std::fs::remove_dir_all(&dir);
        let (names, declared) = listed.unwrap();
        assert_eq!(names.len(), 2);
        assert_eq!(declared, 8);
    }

    #[test]
    fn zip_extract_refuses_a_zip_slip_member_before_writing() {
        use std::io::Write;
        let root = std::env::temp_dir().join(format!("ae-ap-{}-zip", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let dest = root.join("dest");
        std::fs::create_dir_all(&dest).unwrap();
        let archive = root.join("evil.zip");
        {
            let file = std::fs::File::create(&archive).unwrap();
            let mut w = zip::ZipWriter::new(file);
            let opts = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            w.start_file("../evil.txt", opts).unwrap();
            w.write_all(b"pwned").unwrap();
            w.finish().unwrap();
        }
        let args = vec![
            Value::Str(archive.display().to_string()),
            Value::Str(dest.display().to_string()),
        ];
        let result = bi_zip_extract(args, None);
        assert!(result.is_err(), "zip-slip archive must be refused");
        assert!(
            !root.join("evil.txt").exists(),
            "nothing may land outside dest"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn tar_extract_refuses_a_symlink_to_outside_before_writing() {
        let root = std::env::temp_dir().join(format!("ae-ap-{}-tar", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let dest = root.join("dest");
        std::fs::create_dir_all(&dest).unwrap();
        let archive = root.join("evil.tar");
        {
            let file = std::fs::File::create(&archive).unwrap();
            let mut b = tar::Builder::new(file);
            let mut h = tar::Header::new_gnu();
            h.set_path("a").unwrap();
            h.set_entry_type(tar::EntryType::Symlink);
            h.set_link_name("../../etc").unwrap();
            h.set_size(0);
            h.set_cksum();
            b.append(&h, std::io::empty()).unwrap();
            b.finish().unwrap();
        }
        let args = vec![
            Value::Str(archive.display().to_string()),
            Value::Str(dest.display().to_string()),
        ];
        let result = bi_tar_extract(args, None);
        assert!(result.is_err(), "escaping symlink must be refused");
        assert!(!dest.join("a").exists(), "nothing may be written");
        let _ = std::fs::remove_dir_all(&root);
    }
}

#[cfg(test)]
mod apply_preflight_tests {
    use super::{apply_op_refusal, apply_preflight_refusal};

    type Op = (String, String, Option<String>, Option<String>);

    fn op(o: &str, p: &str, d: Option<&str>) -> Op {
        (o.to_string(), p.to_string(), None, d.map(str::to_string))
    }

    // These use enforce_jail = false, so they never read the workspace root or
    // the environment, and they are safe to run in parallel.

    #[test]
    fn copy_onto_its_own_source_is_refused() {
        let refusal = apply_op_refusal("copy", "a.txt", Some("a.txt"), false);
        assert_eq!(
            refusal.as_deref(),
            Some("copy a.txt: destination is the source")
        );
    }

    #[test]
    fn move_to_a_distinct_destination_is_allowed() {
        assert_eq!(
            apply_op_refusal("move", "a.txt", Some("b.txt"), false),
            None
        );
    }

    #[test]
    fn write_has_no_destination_to_check() {
        assert_eq!(apply_op_refusal("write", "a.txt", None, false), None);
    }

    #[test]
    fn plan_refusal_is_the_first_refused_op() {
        let ops = vec![
            op("write", "a.txt", None),
            op("copy", "b.txt", Some("b.txt")),
            op("copy", "c.txt", Some("c.txt")),
        ];
        assert_eq!(
            apply_preflight_refusal(&ops, false).as_deref(),
            Some("copy b.txt: destination is the source")
        );
    }

    #[test]
    fn delete_then_write_the_same_path_is_a_clean_plan() {
        let ops = vec![
            op("rm", "a.txt", None),
            op("write", "a.txt", None),
            op("mkdir", "d", None),
        ];
        assert_eq!(apply_preflight_refusal(&ops, false), None);
    }
}

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

    fn code_of(e: &anyhow::Error) -> Option<crate::safety::ErrorCode> {
        e.downcast_ref::<crate::safety::SafetyError>()
            .map(|s| s.code)
    }

    fn scratch_path(name: &str) -> std::path::PathBuf {
        std::env::temp_dir().join(format!(
            "ae_coded2_{}_{}",
            name,
            uuid::Uuid::new_v4().simple()
        ))
    }

    #[test]
    fn ls_missing_path_is_coded_not_found() {
        let missing = scratch_path("ls_missing");
        let e = bi_ls(vec![Value::Str(missing.display().to_string())], None).unwrap_err();
        assert_eq!(code_of(&e), Some(crate::safety::ErrorCode::NotFound));
    }

    #[test]
    fn ls_on_a_plain_file_lists_that_file() {
        // read_dir on a file fails with an OS error, which once reached the
        // caller uncoded. As GNU ls does, ls of a file now lists that file.
        let file = scratch_path("ls_file");
        fs::write(&file, b"not a directory").unwrap();
        let result = bi_ls(vec![Value::Str(file.display().to_string())], None);
        let _ = fs::remove_file(&file);
        match result {
            Ok(Value::Array(entries)) => assert_eq!(entries.len(), 1, "{entries:?}"),
            other => panic!("ls of a file must list it, got: {other:?}"),
        }
    }

    #[test]
    fn save_json_into_a_missing_directory_is_coded() {
        let path = scratch_path("nodir").join("out.json").display().to_string();
        let args = vec![Value::Str(path.clone()), Value::Str("payload".to_string())];
        let e = bi_save_json(args, None).unwrap_err();
        assert!(
            code_of(&e).is_some(),
            "save_json into a missing directory must carry an error code, got: {e}"
        );
        assert!(!std::path::Path::new(&path).exists());
    }

    #[test]
    fn ai_set_default_unknown_provider_is_bad_arg() {
        let e = bi_ai_set_default(vec![Value::Str("no-such-provider-xyz".to_string())], None)
            .unwrap_err();
        assert_eq!(code_of(&e), Some(crate::safety::ErrorCode::BadArg));
    }
}

#[cfg(test)]
mod clip_deadline_tests {
    // Only harmless stand-in programs run here. No clipboard tool is ever
    // started, and the real clipboard is never touched.
    use super::*;
    use std::process::{Command, Stdio};
    use std::time::{Duration, Instant};

    fn piped(mut cmd: Command) -> std::process::Child {
        cmd.stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null());
        cmd.spawn().expect("the stand-in program should start")
    }

    /// Reads all of its input and exits 0.
    #[cfg(unix)]
    fn reads_stdin_and_exits() -> Command {
        let mut c = crate::safety::child_command("sh");
        c.args(["-c", "cat >/dev/null"]);
        c
    }
    #[cfg(windows)]
    fn reads_stdin_and_exits() -> Command {
        let mut c = crate::safety::child_command("cmd");
        c.args(["/C", "more"]);
        c
    }

    /// Ignores its input and runs for about five seconds.
    #[cfg(unix)]
    fn ignores_stdin_and_sleeps() -> Command {
        let mut c = crate::safety::child_command("sh");
        c.args(["-c", "sleep 5"]);
        c
    }
    #[cfg(windows)]
    fn ignores_stdin_and_sleeps() -> Command {
        let mut c = crate::safety::child_command("cmd");
        c.args(["/C", "ping -n 6 127.0.0.1"]);
        c
    }

    /// Exits 0 at once, without reading its input.
    #[cfg(unix)]
    fn exits_without_reading() -> Command {
        let mut c = crate::safety::child_command("sh");
        c.args(["-c", "exit 0"]);
        c
    }
    #[cfg(windows)]
    fn exits_without_reading() -> Command {
        let mut c = crate::safety::child_command("cmd");
        c.args(["/C", "exit 0"]);
        c
    }

    fn safety_code(e: &anyhow::Error) -> Option<crate::safety::ErrorCode> {
        e.downcast_ref::<crate::safety::SafetyError>()
            .map(|se| se.code)
    }

    #[test]
    fn a_helper_that_reads_its_input_and_exits_succeeds() {
        let child = piped(reads_stdin_and_exits());
        let status = feed_stdin_and_wait("t", "stand-in", child, vec![b'x'; 4096], 20)
            .expect("a helper that reads its input should not be an error");
        assert!(status.success());
    }

    #[test]
    fn a_helper_that_ignores_its_input_is_stopped_at_the_deadline() {
        let child = piped(ignores_stdin_and_sleeps());
        let start = Instant::now();
        let err = feed_stdin_and_wait("t", "stand-in", child, b"hello".to_vec(), 1)
            .expect_err("a helper still running at the deadline must be stopped");
        let took = start.elapsed();
        assert!(took < Duration::from_secs(4), "took {took:?}");
        assert_eq!(
            safety_code(&err),
            Some(crate::safety::ErrorCode::BudgetExceeded)
        );
    }

    #[test]
    fn a_large_input_to_a_helper_that_exits_at_once_returns() {
        let child = piped(exits_without_reading());
        let start = Instant::now();
        let res = feed_stdin_and_wait("t", "stand-in", child, vec![0u8; 4 << 20], 20);
        assert!(start.elapsed() < Duration::from_secs(15));
        match res {
            Ok(status) => assert!(status.success()),
            Err(e) => assert_ne!(
                safety_code(&e),
                Some(crate::safety::ErrorCode::BudgetExceeded),
                "a helper that exited at once must not be reported as a timeout"
            ),
        }
    }
}

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

    fn code_of(e: &anyhow::Error) -> Option<crate::safety::ErrorCode> {
        e.downcast_ref::<crate::safety::SafetyError>()
            .map(|s| s.code)
    }

    #[test]
    fn an_os_permission_refusal_is_not_the_shells_policy() {
        let e = crate::safety::fs_error(
            "file_read",
            "x",
            &std::io::Error::from(std::io::ErrorKind::PermissionDenied),
        );
        assert_eq!(code_of(&e), Some(crate::safety::ErrorCode::OsDenied));
        // Same exit status as a policy refusal, different code.
        assert_eq!(crate::safety::ErrorCode::OsDenied.exit_code(), 77);
        assert_ne!(
            crate::safety::ErrorCode::OsDenied.as_str(),
            crate::safety::ErrorCode::PolicyDeny.as_str()
        );
    }

    #[test]
    #[cfg(windows)]
    fn a_missing_privilege_is_an_os_refusal() {
        // ERROR_PRIVILEGE_NOT_HELD, which fs_symlink meets without Developer Mode.
        let e =
            crate::safety::fs_error("fs_symlink", "x", &std::io::Error::from_raw_os_error(1314));
        assert_eq!(code_of(&e), Some(crate::safety::ErrorCode::OsDenied));
    }

    #[test]
    fn a_plan_over_the_op_limit_is_refused_before_anything_runs() {
        let op = |i: usize| {
            let mut m = BTreeMap::new();
            m.insert("op".to_string(), Value::Str("write".to_string()));
            m.insert("path".to_string(), Value::Str(format!("never-written-{i}")));
            m.insert("content".to_string(), Value::Str(String::new()));
            Value::Record(m)
        };
        let ops = Value::Array((0..=APPLY_MAX_OPS).map(op).collect());
        let e = bi_apply(vec![ops], None).unwrap_err();
        assert_eq!(code_of(&e), Some(crate::safety::ErrorCode::BudgetExceeded));
        assert!(!std::path::Path::new("never-written-0").exists());
    }
}

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

    #[test]
    fn agent_mode_nc_listen_refuses_a_bind_beyond_loopback() {
        let _l = crate::safety::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let prev_mode = std::env::var_os("IRONSHELL_MODE");
        let prev_allow = std::env::var_os("IRONSHELL_ALLOW_REMOTE_BIND");
        std::env::set_var("IRONSHELL_MODE", "agent");
        std::env::remove_var("IRONSHELL_ALLOW_REMOTE_BIND");
        // TEST-NET-1 is not assigned here, so even an unguarded bind could only
        // fail; the refusal must come before any socket is made.
        let mut opts = std::collections::BTreeMap::new();
        opts.insert("host".to_string(), Value::Str("192.0.2.1".into()));
        let result = bi_nc_listen(vec![Value::Int(9), Value::Record(opts)], None);
        match prev_mode {
            Some(v) => std::env::set_var("IRONSHELL_MODE", v),
            None => std::env::remove_var("IRONSHELL_MODE"),
        }
        if let Some(v) = prev_allow {
            std::env::set_var("IRONSHELL_ALLOW_REMOTE_BIND", v);
        }
        let err = result.expect_err("agent mode must refuse a remote bind");
        assert!(format!("{err}").contains("in agent mode"), "{err}");
    }
}

#[cfg(test)]
mod sleep_deadline_tests {
    use super::*;
    use std::time::{Duration, Instant};

    #[test]
    fn a_sleep_past_the_deadline_is_cut_short_with_budget_exceeded() {
        let _g = crate::safety::enter_deadline(Duration::from_millis(50));
        let started = Instant::now();
        let err = bi_sleep(vec![Value::Int(5)], None).expect_err("sleep must be refused");
        assert!(
            started.elapsed() < Duration::from_secs(2),
            "sleep ran past the deadline: {:?}",
            started.elapsed()
        );
        assert!(format!("{err}").contains("E_BUDGET_EXCEEDED"), "{err}");
    }

    #[test]
    fn a_short_sleep_inside_the_deadline_returns_null() {
        let _g = crate::safety::enter_deadline(Duration::from_secs(10));
        let v = bi_sleep(vec![Value::Float(0.01)], None).expect("inside the deadline");
        assert!(matches!(v, Value::Null));
    }

    #[test]
    fn without_a_deadline_sleep_returns_null() {
        let v = bi_sleep(vec![Value::Float(0.01)], None).expect("no deadline");
        assert!(matches!(v, Value::Null));
    }
}

#[cfg(test)]
mod win_hwprobe_tests {
    use super::*;
    use serde_json::json;

    fn record(v: Option<Value>) -> BTreeMap<String, Value> {
        match v {
            Some(Value::Record(m)) => m,
            _ => panic!("expected a record"),
        }
    }

    fn str_of(m: &BTreeMap<String, Value>, key: &str) -> Option<String> {
        match m.get(key) {
            Some(Value::Str(s)) => Some(s.clone()),
            _ => None,
        }
    }

    fn int_of(m: &BTreeMap<String, Value>, key: &str) -> Option<i64> {
        match m.get(key) {
            Some(Value::Int(n)) => Some(*n),
            _ => None,
        }
    }

    #[test]
    fn gpu_probe_uses_the_driver_size_for_identical_cards_and_amd() {
        let probe = json!([
            {"Name": "NVIDIA GeForce RTX 3090 Ti", "AdapterRAM": 4293918720_i64, "DriverVersion": "32.0.15.7270", "QwMemorySize": 25757220864_i64},
            {"Name": "NVIDIA GeForce RTX 3090 Ti", "AdapterRAM": 4293918720_i64, "DriverVersion": "32.0.15.7270", "QwMemorySize": 25757220864_i64},
            {"Name": "AMD Radeon(TM) Graphics", "AdapterRAM": 2147483648_i64, "DriverVersion": "31.0.21923.1000", "QwMemorySize": 2147483648_i64}
        ]);
        let gpus = win_gpus_from_probe(&probe);
        assert_eq!(gpus.len(), 3);
        assert_eq!(gpus[0].vram_bytes, Some(25_757_220_864));
        assert_eq!(gpus[1].vram_bytes, Some(25_757_220_864));
        assert_eq!(gpus[1].name.as_deref(), Some("NVIDIA GeForce RTX 3090 Ti"));
        assert_eq!(gpus[1].driver.as_deref(), Some("32.0.15.7270"));
        assert_eq!(gpus[2].vram_bytes, Some(2_147_483_648));
        assert_eq!(gpus[2].name.as_deref(), Some("AMD Radeon(TM) Graphics"));
        assert_eq!(gpus[2].driver.as_deref(), Some("31.0.21923.1000"));
    }

    #[test]
    fn gpu_probe_falls_back_to_adapter_ram_without_a_positive_driver_size() {
        let probe = json!([
            {"Name": "Null size", "AdapterRAM": 1073741824_i64, "DriverVersion": "1.0", "QwMemorySize": null},
            {"Name": "Zero size", "AdapterRAM": 536870912_i64, "DriverVersion": "2.0", "QwMemorySize": 0},
            {"Name": "No key", "AdapterRAM": 268435456_i64, "DriverVersion": "3.0"}
        ]);
        let gpus = win_gpus_from_probe(&probe);
        assert_eq!(gpus.len(), 3);
        assert_eq!(gpus[0].vram_bytes, Some(1_073_741_824));
        assert_eq!(gpus[1].vram_bytes, Some(536_870_912));
        assert_eq!(gpus[2].vram_bytes, Some(268_435_456));
    }

    #[test]
    fn gpu_probe_accepts_a_single_object() {
        let probe = json!({"Name": "NVIDIA GeForce RTX 3090 Ti", "AdapterRAM": 4293918720_i64, "DriverVersion": "32.0.15.7270", "QwMemorySize": 25757220864_i64});
        let gpus = win_gpus_from_probe(&probe);
        assert_eq!(gpus.len(), 1);
        assert_eq!(gpus[0].vram_bytes, Some(25_757_220_864));
    }

    #[test]
    fn gpu_probe_skips_non_objects_and_empty_output() {
        assert!(win_gpus_from_probe(&json!([])).is_empty());
        assert!(win_gpus_from_probe(&json!(null)).is_empty());
        assert!(win_gpus_from_probe(&json!("text")).is_empty());
        let gpus = win_gpus_from_probe(&json!([1, "x", {"Name": "Kept"}]));
        assert_eq!(gpus.len(), 1);
        assert_eq!(gpus[0].name.as_deref(), Some("Kept"));
        assert_eq!(gpus[0].vram_bytes, None);
        assert_eq!(gpus[0].driver, None);
    }

    #[test]
    fn gpu_record_has_the_name_vram_and_driver_shape() {
        let g = WinGpu {
            name: Some("NVIDIA GeForce RTX 3090 Ti".to_string()),
            vram_bytes: Some(25_757_220_864),
            driver: Some("32.0.15.7270".to_string()),
        };
        let m = record(Some(win_gpu_record(&g)));
        assert_eq!(m.len(), 3);
        assert_eq!(
            str_of(&m, "name").as_deref(),
            Some("NVIDIA GeForce RTX 3090 Ti")
        );
        assert_eq!(int_of(&m, "vram"), Some(25_757_220_864));
        assert_eq!(str_of(&m, "driver").as_deref(), Some("32.0.15.7270"));
    }

    #[test]
    fn battery_status_codes_map_per_the_documented_table() {
        let expected: [(i64, &str); 15] = [
            (0, "unknown"),
            (1, "discharging"),
            (2, "ac"),
            (3, "full"),
            (4, "low"),
            (5, "critical"),
            (6, "charging"),
            (7, "charging"),
            (8, "charging"),
            (9, "charging"),
            (10, "unknown"),
            (11, "partially_charged"),
            (12, "unknown"),
            (-1, "unknown"),
            (99, "unknown"),
        ];
        for (code, want) in expected {
            assert_eq!(windows_battery_status(code), want, "code {code}");
        }
    }

    #[test]
    fn battery_object_reports_a_ups_on_ac_with_its_name() {
        let probe = json!({"Name": "Back-UPS ES 600M1 FW:932.2 USB FW:L2", "EstimatedChargeRemaining": 100, "BatteryStatus": 2});
        let m = record(windows_battery_from_probe(&probe));
        assert_eq!(int_of(&m, "capacity"), Some(100));
        assert_eq!(str_of(&m, "status").as_deref(), Some("ac"));
        assert_eq!(
            str_of(&m, "name").as_deref(),
            Some("Back-UPS ES 600M1 FW:932.2 USB FW:L2")
        );
    }

    #[test]
    fn battery_name_is_omitted_when_null_or_blank() {
        let null_name = json!({"Name": null, "EstimatedChargeRemaining": 50, "BatteryStatus": 1});
        let blank_name = json!({"Name": "  ", "EstimatedChargeRemaining": 50, "BatteryStatus": 1});
        for probe in [null_name, blank_name] {
            let m = record(windows_battery_from_probe(&probe));
            assert!(!m.contains_key("name"));
            assert_eq!(str_of(&m, "status").as_deref(), Some("discharging"));
        }
    }

    #[test]
    fn battery_missing_fields_and_array_form() {
        let no_status = json!({"EstimatedChargeRemaining": 40});
        let m = record(windows_battery_from_probe(&no_status));
        assert_eq!(str_of(&m, "status").as_deref(), Some("unknown"));
        assert_eq!(int_of(&m, "capacity"), Some(40));

        let no_capacity = json!({"BatteryStatus": 3});
        let m = record(windows_battery_from_probe(&no_capacity));
        assert!(!m.contains_key("capacity"));
        assert_eq!(str_of(&m, "status").as_deref(), Some("full"));

        let array =
            json!([{"Name": "Battery", "EstimatedChargeRemaining": 87, "BatteryStatus": 6}]);
        let m = record(windows_battery_from_probe(&array));
        assert_eq!(str_of(&m, "status").as_deref(), Some("charging"));
        assert_eq!(str_of(&m, "name").as_deref(), Some("Battery"));

        assert!(windows_battery_from_probe(&json!([])).is_none());
        assert!(windows_battery_from_probe(&json!(null)).is_none());
    }
}

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

    fn code_of(e: &anyhow::Error) -> Option<crate::safety::ErrorCode> {
        e.downcast_ref::<crate::safety::SafetyError>()
            .map(|s| s.code)
    }

    fn gpu_fields(output: &str) -> BTreeMap<String, Value> {
        match gpu_memory_record(output).expect("valid nvidia-smi rows") {
            Value::Record(rec) => rec,
            other => panic!("expected a Record, got {other:?}"),
        }
    }

    #[test]
    fn load_fields_are_null_without_a_sample_and_floats_with_one() {
        assert_eq!(
            load_field_values(None),
            [Value::Null, Value::Null, Value::Null]
        );
        assert_eq!(
            load_field_values(Some([0.5, 0.25, 0.125])),
            [Value::Float(0.5), Value::Float(0.25), Value::Float(0.125)]
        );
    }

    #[test]
    fn one_gpu_row_gives_its_figures_and_one_device() {
        let rec = gpu_fields("24564, 4919, 19395\n");
        assert_eq!(rec.get("total_mb"), Some(&Value::Int(24564)));
        assert_eq!(rec.get("used_mb"), Some(&Value::Int(4919)));
        assert_eq!(rec.get("free_mb"), Some(&Value::Int(19395)));
        assert_eq!(rec.get("devices"), Some(&Value::Int(1)));
    }

    #[test]
    fn two_gpu_rows_are_summed_across_every_gpu() {
        // CRLF line endings, as nvidia-smi prints them on Windows.
        let rec = gpu_fields("24564, 4919, 19395\r\n24564, 772, 23792\r\n");
        assert_eq!(rec.get("total_mb"), Some(&Value::Int(49128)));
        assert_eq!(rec.get("used_mb"), Some(&Value::Int(5691)));
        assert_eq!(rec.get("free_mb"), Some(&Value::Int(43187)));
        assert_eq!(rec.get("devices"), Some(&Value::Int(2)));
    }

    #[test]
    fn a_malformed_row_is_refused_with_bad_state_not_skipped() {
        let e = gpu_memory_record("24564, 4919, 19395\n24564, oops, 23792\n")
            .expect_err("a non-numeric row must be refused");
        assert_eq!(code_of(&e), Some(crate::safety::ErrorCode::BadState));
    }

    #[test]
    fn a_short_or_long_row_is_refused_with_bad_state() {
        let short = gpu_memory_record("24564, 4919\n").expect_err("two fields");
        assert_eq!(code_of(&short), Some(crate::safety::ErrorCode::BadState));
        let long = gpu_memory_record("24564, 4919, 19395, 7\n").expect_err("four fields");
        assert_eq!(code_of(&long), Some(crate::safety::ErrorCode::BadState));
    }

    #[test]
    fn no_rows_is_refused_with_bad_state() {
        for output in ["", "\n"] {
            let e = gpu_memory_record(output).expect_err("no GPU rows");
            assert_eq!(code_of(&e), Some(crate::safety::ErrorCode::BadState));
        }
    }
}

#[cfg(all(test, windows))]
mod win_job_tests {
    use super::*;
    use std::collections::BTreeSet;
    use std::time::{Duration, Instant};

    /// The live `ping.exe` processes started with `-n <count>`. Each test uses its
    /// own count, so tests that run in parallel do not see each other's processes.
    fn pings_with_count(count: &str) -> BTreeSet<u32> {
        let mut sys = sysinfo::System::new();
        sys.refresh_processes_specifics(
            sysinfo::ProcessesToUpdate::All,
            true,
            sysinfo::ProcessRefreshKind::everything(),
        );
        sys.processes()
            .iter()
            .filter(|(_, p)| {
                p.name().eq_ignore_ascii_case("ping.exe")
                    && p.cmd().iter().any(|a| a.to_str() == Some(count))
            })
            .map(|(pid, _)| pid.as_u32())
            .collect()
    }

    /// Runs `cmd /C <line>` through `run_tree` on a thread. Before the call can
    /// be judged, a `ping -n <count>` grandchild must exist, so a pass cannot come
    /// from the grandchild never starting. Returns the run, how long the call took,
    /// and any such `ping` still alive a second after the call returned.
    fn run_with_ping(
        line: &'static str,
        count: &'static str,
        limit: Duration,
    ) -> (TreeRun, Duration, BTreeSet<u32>) {
        let before = pings_with_count(count);
        let call = std::thread::spawn(move || {
            let started = Instant::now();
            let run = run_tree(
                "cmd",
                &["/C", line],
                |_| {},
                None,
                limit,
                Keep::Tail(4096),
                Keep::Tail(4096),
            );
            (run, started.elapsed())
        });
        let until = Instant::now() + Duration::from_secs(10);
        while pings_with_count(count).is_subset(&before) && Instant::now() < until {
            std::thread::sleep(Duration::from_millis(50));
        }
        assert!(
            !pings_with_count(count).is_subset(&before),
            "the grandchild ping never started"
        );
        let (run, elapsed) = call.join().expect("the run thread panicked");
        let run = match run {
            Ok(run) => run,
            Err(_) => panic!("the run did not start"),
        };
        std::thread::sleep(Duration::from_secs(1));
        let survivors = pings_with_count(count)
            .difference(&before)
            .copied()
            .collect();
        (run, elapsed, survivors)
    }

    /// `cmd` exits at once, but its `start /B` child keeps the inherited pipes and
    /// would run for 33 s. The job must take it down: the call returns quickly,
    /// the pipes close, and the grandchild is gone.
    #[test]
    fn grandchild_holding_a_pipe_is_killed_after_the_child_exits() {
        let (run, elapsed, survivors) = run_with_ping(
            "start /B ping -n 33 127.0.0.1",
            "33",
            Duration::from_secs(20),
        );
        assert!(
            !run.timed_out,
            "the child exits at once; the call must not time out"
        );
        assert!(
            !run.pipes_abandoned,
            "the grandchild's pipes must close once it is killed"
        );
        assert!(
            elapsed < Duration::from_secs(10),
            "the call took {elapsed:?}"
        );
        assert!(
            survivors.is_empty(),
            "ping survived the call: {survivors:?}"
        );
    }

    /// The child is still running at the deadline. Its job, and the `ping` it
    /// started, must both be killed, and the call reports the timeout.
    #[test]
    fn deadline_kills_the_child_and_its_descendants() {
        // The deadline leaves the watcher time to see the grandchild: on a
        // loaded host one process-list refresh can take seconds, and a 4 s
        // deadline once killed ping before the watcher saw it start. ping
        // still runs about 33 s, so a pass needs the kill.
        let (run, elapsed, survivors) =
            run_with_ping("ping -n 34 127.0.0.1", "34", Duration::from_secs(8));
        assert!(run.timed_out, "the deadline must report a timeout");
        assert!(
            elapsed < Duration::from_secs(15),
            "the call took {elapsed:?}"
        );
        assert!(
            survivors.is_empty(),
            "ping survived the deadline kill: {survivors:?}"
        );
    }
}

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

    fn message(role: &str, content: Value) -> Value {
        let mut rec = BTreeMap::new();
        rec.insert("role".to_string(), Value::Str(role.to_string()));
        rec.insert("content".to_string(), content);
        Value::Record(rec)
    }

    /// The error code of a refused `ai_local_generate` call on a handle that
    /// names no loaded model, so only the argument check can refuse it.
    fn refused(messages: Vec<Value>) -> crate::safety::ErrorCode {
        let args = vec![Value::Str("candle:x".to_string()), Value::Array(messages)];
        let e = bi_ai_local_generate(args, None).unwrap_err();
        e.downcast_ref::<crate::safety::SafetyError>()
            .map(|s| s.code)
            .expect("a SafetyError")
    }

    #[test]
    fn malformed_chat_messages_are_bad_arg_before_any_backend() {
        use crate::safety::ErrorCode::BadArg;
        assert_eq!(refused(vec![]), BadArg);
        assert_eq!(refused(vec![Value::Str("hi".to_string())]), BadArg);
        assert_eq!(
            refused(vec![message("bot", Value::Str("hi".to_string()))]),
            BadArg
        );
        assert_eq!(refused(vec![message("user", Value::Int(3))]), BadArg);

        let mut no_content = BTreeMap::new();
        no_content.insert("role".to_string(), Value::Str("user".to_string()));
        assert_eq!(refused(vec![Value::Record(no_content)]), BadArg);

        let mut extra = BTreeMap::new();
        extra.insert("role".to_string(), Value::Str("user".to_string()));
        extra.insert("content".to_string(), Value::Str("hi".to_string()));
        extra.insert("name".to_string(), Value::Str("x".to_string()));
        assert_eq!(refused(vec![Value::Record(extra)]), BadArg);
    }
}