arblang 0.1.24

Visualize and modify Unix pipelines: pipe a stream in, arb spawns a dynamic TUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
//! arb — visualize and modify Unix pipelines.
//!
//! Pipe a stream in and arb renders a dynamic TUI built from a declarative spec.
//! With no spec it synthesizes a full-screen `tail` of stdin. With no controlling
//! terminal on stdout (piped onward / CI) it prints the parsed spec, each source
//! pipeline, and its evaluated result instead of a TUI — correct behavior and the
//! headless-test path.
//!
//! M1/M2a interpret the declarative subset (widgets, `source` query pipelines,
//! binds). The expression layer, fusevm lowering, web target, actors, and package
//! manager are later milestones (see SPEC.md) and are not faked here.

use std::io::{self, BufRead, BufReader, IsTerminal, Read, Write};
use std::os::unix::io::RawFd;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use clap::Parser;

use crate::query::{self, QueryOp, QueryResult};
use crate::spec::{self, Spec};
use crate::stream::StreamState;
use crate::{cache, parser, tui};

// Cyberpunk `-h` help — help template, ASCII banner, and footer, ported from the
// `temprs` (`tp -h`) house style (`temprs/src/model/opts.rs`): `{before-help}`
// banner, cyberpunk section dividers, green `//` per-option prefixes, and a
// `── SYSTEM ──` footer. clap emits raw ANSI in these verbatim.
const HELP_TEMPLATE: &str = "
{before-help}
{about}

\x1b[33m  USAGE:\x1b[0m {usage}

\x1b[36m  ── OPTIONS ────────────────────────────────────────────\x1b[0m
{options}
\x1b[36m  ── POSITIONAL ─────────────────────────────────────────\x1b[0m
{positionals}
{after-help}";

const BANNER: &str = concat!(
    "\x1b[36m █████╗ ██████╗ ██████╗\x1b[0m\n",
    "\x1b[36m██╔══██╗██╔══██╗██╔══██╗\x1b[0m\n",
    "\x1b[35m███████║██████╔╝██████╔╝\x1b[0m\n",
    "\x1b[35m██╔══██║██╔══██╗██╔══██╗\x1b[0m\n",
    "\x1b[31m██║  ██║██║  ██║██████╔╝\x1b[0m\n",
    "\x1b[31m╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝\x1b[0m\n",
    "\x1b[36m ┌──────────────────────────────────────────────────────┐\x1b[0m\n",
    "\x1b[36m │ STATUS: ONLINE  // SIGNAL: ████████░░ // v",
    env!("CARGO_PKG_VERSION"),
    "\x1b[36m      │\x1b[0m\n",
    "\x1b[36m └──────────────────────────────────────────────────────┘\x1b[0m\n",
    "\x1b[35m  >> A TUI FOR EVERY PIPELINE // FULL SPECTRUM <<\x1b[0m"
);

const AFTER: &str = concat!(
    "\x1b[36m  ── SYSTEM ─────────────────────────────────────────\x1b[0m\n",
    "\x1b[35m  v",
    env!("CARGO_PKG_VERSION"),
    " \x1b[0m// \x1b[33m(c) MenkeTechnologies\x1b[0m\n",
    "\x1b[35m  A TUI for every pipeline.\x1b[0m\n",
    "\x1b[33m  >>> PIPE IN. SHAPE THE STREAM. OWN YOUR OUTPUT. <<<\x1b[0m\n",
    "\x1b[36m ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\x1b[0m"
);

/// arb — pipe a stream in, get a live TUI.
#[derive(Parser, Debug)]
#[command(
    name = "arb",
    version,
    about = "Visualize and modify Unix pipelines.",
    help_template = HELP_TEMPLATE,
    before_help = BANNER,
    after_help = AFTER,
)]
struct Cli {
    /// Dashboard spec file (.arb).
    #[arg(help = "\x1b[32m//\x1b[0m Dashboard spec file (.arb)")]
    spec: Option<String>,
    /// Inline spec, e.g. `-e 'gauge .g -max 100; source .g { in; count }'`.
    #[arg(
        short = 'e',
        long = "eval",
        help = "\x1b[32m//\x1b[0m Inline spec, e.g. -e 'gauge .g -max 100; source .g { in; count }'"
    )]
    eval: Option<String>,
    /// Run a preset / stdlib module by name, e.g. `-p logs` (== `import logs`).
    #[arg(
        short = 'p',
        long = "preset",
        help = "\x1b[32m//\x1b[0m Run a preset / stdlib module by name (== import NAME)"
    )]
    preset: Option<String>,
    /// List available presets (bundled stdlib + `~/.arb/lib`) and exit.
    #[arg(
        short = 'l',
        long = "list",
        help = "\x1b[32m//\x1b[0m List available presets (stdlib + ~/.arb/lib) and exit"
    )]
    list: bool,
    /// Override the spec's color theme (one of the 31 built-ins, e.g. neon-noir).
    #[arg(
        long = "theme",
        value_name = "NAME",
        help = "\x1b[32m//\x1b[0m Color theme (one of 31, e.g. neon-noir); overrides the spec"
    )]
    theme: Option<String>,
    /// List the 31 built-in color themes (with swatches) and exit.
    #[arg(
        long = "list-themes",
        help = "\x1b[32m//\x1b[0m List the 31 built-in color themes and exit"
    )]
    list_themes: bool,
    /// Evaluate EXPR on fusevm, then report which execution tier took its
    /// chunk, and exit.
    #[arg(
        long = "tiers",
        value_name = "EXPR",
        help = "\x1b[32m//\x1b[0m Evaluate EXPR, then report which fusevm tiers took it"
    )]
    tiers: Option<String>,
    /// Persist a global default theme to ~/.arb/config.toml, then exit.
    #[arg(
        long = "set-theme",
        value_name = "NAME",
        help = "\x1b[32m//\x1b[0m Save NAME as the global default theme in ~/.arb/config.toml, then exit"
    )]
    set_theme: Option<String>,
    /// Save a spec as a named user preset in `~/.arb/lib`, then exit.
    /// Source is the `FILE` argument or `-e SRC`. E.g. `arb --save api dash.arb`.
    #[arg(
        long = "save",
        value_name = "NAME",
        help = "\x1b[32m//\x1b[0m Save a spec (FILE or -e SRC) as a named user preset, then exit"
    )]
    save: Option<String>,
    /// Install a shared `.arb` spec into the preset library, then exit.
    /// `arb --install dash.arb` (name = file stem, or override with `--as NAME`).
    #[arg(
        long = "install",
        value_name = "FILE",
        help = "\x1b[32m//\x1b[0m Install a .arb spec into the preset library, then exit"
    )]
    install: Option<String>,
    /// Name to install under (defaults to the file stem).
    #[arg(
        long = "as",
        value_name = "NAME",
        help = "\x1b[32m//\x1b[0m Name to install the spec under (default: file stem)"
    )]
    install_as: Option<String>,
    /// Uninstall a named preset from the library, then exit.
    #[arg(
        long = "uninstall",
        value_name = "NAME",
        help = "\x1b[32m//\x1b[0m Remove a named preset from the library, then exit"
    )]
    uninstall: Option<String>,
    /// List only installed (user library) presets, then exit.
    #[arg(
        long = "installed",
        help = "\x1b[32m//\x1b[0m List installed user-library presets, then exit"
    )]
    installed: bool,
    /// Interactive REPL — author + test specs against a sample buffer.
    #[arg(
        short = 'r',
        long = "repl",
        help = "\x1b[32m//\x1b[0m Interactive REPL — author + test specs against a sample buffer"
    )]
    repl: bool,
    /// Generate a static HTML dashboard from the spec to stdout, then exit
    /// (`arb -p logs --html > dash.html`).
    #[arg(
        long = "html",
        help = "\x1b[32m//\x1b[0m Emit a static HTML dashboard from the spec to stdout, then exit"
    )]
    html: bool,
    /// Validate the spec (parse + build) and exit 0/1 without reading stdin.
    #[arg(
        long = "check",
        help = "\x1b[32m//\x1b[0m Validate the spec (parse + build) and exit 0/1, no stdin"
    )]
    check: bool,
    /// Run the spec's in-language `test { … }` blocks headlessly and exit 0/1.
    #[arg(
        long = "test",
        help = "\x1b[32m//\x1b[0m Run the spec's `test { … }` blocks (TAP output), exit 0/1"
    )]
    test: bool,
    /// Serve the spec as a live browser dashboard (polls the stream over HTTP).
    #[arg(
        long = "serve",
        help = "\x1b[32m//\x1b[0m Serve the spec as a live browser dashboard on 127.0.0.1"
    )]
    serve: bool,
    /// Port for `--serve` (0 = OS-assigned, printed on start).
    #[arg(
        long = "port",
        value_name = "N",
        default_value_t = 8787,
        help = "\x1b[32m//\x1b[0m Port for --serve (0 = pick a free port)"
    )]
    port: u16,
    /// Run as a Language Server over stdio (JSON-RPC) for `.arb` specs.
    #[arg(
        long = "lsp",
        help = "\x1b[32m//\x1b[0m Run the LSP over stdio (diagnostics/completion/hover/…)"
    )]
    lsp: bool,
    /// Run as a Debug Adapter over stdio: step the stream, regex breakpoints,
    /// inspect the paused line / stats / controls (launch with program+input).
    #[arg(
        long = "dap",
        help = "\x1b[32m//\x1b[0m Run the DAP over stdio (step the stream, regex breakpoints)"
    )]
    dap: bool,
    /// Print the Tcl-flavored lexer token stream for the spec and exit.
    #[arg(
        long = "dump-tokens",
        help = "\x1b[32m//\x1b[0m Print the lexer token stream for the spec and exit"
    )]
    dump_tokens: bool,
    /// Print the parsed command-tree AST for the spec and exit.
    #[arg(
        long = "dump-ast",
        help = "\x1b[32m//\x1b[0m Print the parsed AST for the spec and exit"
    )]
    dump_ast: bool,
    /// Print the built spec's compiled query-pipeline op vectors and exit.
    #[arg(
        long = "dump-bytecode",
        help = "\x1b[32m//\x1b[0m Print the compiled pipeline op vectors for the spec and exit"
    )]
    dump_bytecode: bool,
    /// Print a numbered disassembly of the built spec's compiled pipelines and exit.
    #[arg(
        long = "disasm",
        help = "\x1b[32m//\x1b[0m Print a disassembly of the compiled pipelines and exit"
    )]
    disasm: bool,
    /// With an `out { … }` pipeline, emit results as JSON (array / number /
    /// object) instead of plain lines — pipe to `jq` or programs.
    #[arg(
        long = "json",
        help = "\x1b[32m//\x1b[0m With an out { } pipeline, emit JSON instead of plain lines"
    )]
    json: bool,
    /// fzf select mode: interactively filter the stream and pick one line;
    /// the chosen line is printed to stdout on Enter (`vim $(ls | arb --fzf)`).
    #[arg(
        long = "fzf",
        help = "\x1b[32m//\x1b[0m fzf mode: filter + select one line, printed to stdout on Enter"
    )]
    fzf: bool,
    /// Run a pipeline with arb as the interactive stage, e.g.
    /// `arb --fzf --run 'sudo find / | _ | grep foo'`. arb spawns the
    /// surrounding commands (each via `sh -c`, so globs/quotes work) and controls
    /// their fds: the producer's stdout feeds arb's stream, its stderr goes to a
    /// pane instead of corrupting the TUI.
    #[arg(
        long = "run",
        value_name = "PIPELINE",
        help = "\x1b[32m//\x1b[0m Run 'PROD | _ | CONS': arb spawns them, stderr -> pane"
    )]
    run: Option<String>,
    /// fzf preview: run this command for the line under the cursor (`{}` is the
    /// current line, shell-escaped) and show its output in a right pane, updated
    /// as you move. E.g. `arb --fzf --preview 'bat --color=always {}'`.
    #[arg(
        long = "preview",
        value_name = "CMD",
        overrides_with = "preview",
        help = "\x1b[32m//\x1b[0m fzf preview: run CMD on the cursor line ({}), output in a pane"
    )]
    preview: Option<String>,
    /// fzf prompt string (default `> `).
    #[arg(
        long = "prompt",
        value_name = "STR",
        overrides_with = "prompt",
        help = "\x1b[32m//\x1b[0m fzf prompt string (default '> ')"
    )]
    prompt: Option<String>,
    /// fzf header line shown above the list.
    #[arg(
        long = "header",
        value_name = "STR",
        overrides_with = "header",
        help = "\x1b[32m//\x1b[0m fzf header line shown above the list"
    )]
    header: Option<String>,

    // ── fzf-compatibility flags (honored) ───────────────────────────────────
    // So `arb --fzf` can drop in for the `fzf` binary (e.g. `ZPWR_FZF='arb --fzf'`).
    // The presentation flags (--ansi/--border/--reverse/--preview-window/…) are
    // stripped from the args by `fzf_compat_args` before clap sees them, because
    // clap knows only arb's own options — they are read off the FULL argv by
    // `fzf::Look::parse` and honored from there. These are the ones clap parses.
    /// fzf compat: exact substring match instead of fuzzy. (`-e` under `--fzf`
    /// is rewritten to this; arb's own `-e` is `--eval`.)
    #[arg(
        long = "exact",
        overrides_with = "exact",
        help = "\x1b[32m//\x1b[0m fzf: exact substring match (not fuzzy)"
    )]
    exact: bool,
    /// fzf compat: don't sort by score — keep input order.
    #[arg(
        long = "no-sort",
        overrides_with = "no_sort",
        help = "\x1b[32m//\x1b[0m fzf: keep input order (no score sort)"
    )]
    no_sort: bool,
    /// fzf compat: start with this query in the filter.
    #[arg(
        long = "query",
        value_name = "STR",
        overrides_with = "query",
        help = "\x1b[32m//\x1b[0m fzf: initial query"
    )]
    query: Option<String>,
    /// fzf compat: enable multi-select (arb always allows Tab-marking).
    #[arg(
        short = 'm',
        long = "multi",
        overrides_with = "multi",
        help = "\x1b[32m//\x1b[0m fzf: multi-select (Tab marks)"
    )]
    multi: bool,
    /// fzf `-f`/`--filter`: no UI — print the matching lines, best-first, and
    /// exit. Same matcher, sort and tiebreak as the picker.
    #[arg(
        short = 'f',
        long = "filter",
        value_name = "STR",
        overrides_with = "filter",
        help = "\x1b[32m//\x1b[0m fzf: print ranked matches for STR and exit (no UI)"
    )]
    filter: Option<String>,
    /// fzf height: render inline in N rows (or `N%` of the terminal) at the
    /// bottom instead of full-screen, keeping the scrollback. E.g. `--height 40%`.
    #[arg(
        long = "height",
        value_name = "N|N%",
        overrides_with = "height",
        help = "\x1b[32m//\x1b[0m fzf height: inline in N rows or N% (not full-screen)"
    )]
    height: Option<String>,
    /// Preview command after `--`: re-run over arb's current post-filter output
    /// whenever the filter changes; its stdout+stderr show in a pane, always in
    /// sync with the filter and never touching the terminal.
    /// E.g. `find / | arb -- grep error`.
    #[arg(
        last = true,
        help = "\x1b[32m//\x1b[0m Preview `-- CMD …`: re-run over the filtered output, shown in a pane"
    )]
    down: Vec<String>,
}

/// One word of a rewritten argv, so the helpers below can consume a flag's
/// separate value out of the same iterator the loop is walking.
type Argv = std::iter::Peekable<std::vec::IntoIter<String>>;

/// fzf's rule for a flag whose value is OPTIONAL: `--border STYLE` takes the
/// next word, `--border --preview CMD` does not (a value never starts with
/// `-`), and `--gap 2` takes it only because a gap size is a number. Getting
/// this wrong swallows the flag that follows, which is how `--color` used to
/// eat a `--preview` behind it.
fn eats_next(next: Option<&String>, numeric: bool) -> bool {
    match next {
        Some(v) if numeric => v.parse::<i64>().is_ok(),
        Some(v) => !v.starts_with('-'),
        None => false,
    }
}

/// fzf's `--no-X` cancels an earlier `--X` — last one wins. For the options arb
/// declares itself that can't be a silent drop: `--preview CMD --no-preview`
/// has to reach clap with no preview at all, so the pending flag (and its
/// separate value) is removed from the rewritten argv.
fn cancel(out: &mut Vec<String>, names: &[&str], takes_value: bool) {
    let Some(i) = out.iter().rposition(|a| {
        names
            .iter()
            .any(|n| a == n || a.starts_with(&format!("{n}=")))
    }) else {
        return;
    };
    let attached = out[i].contains('=');
    out.remove(i);
    if takes_value && !attached && i < out.len() {
        out.remove(i);
    }
}

/// Rewrite argv so `arb --fzf` tolerates the `fzf` binary's flags (for drop-in
/// use like `ZPWR_FZF='arb --fzf'`): translate fzf's `+`-negations and short
/// forms, cancel an arb flag when its `--no-X` follows it, and DROP the flags
/// clap doesn't declare, consuming a value for the value-taking ones. Flags arb
/// honors (`-e`, `--no-sort`, `--query`, `-m`, `--preview`, `--prompt`,
/// `--header`, `--height`, `--filter`) pass through to clap untouched.
fn fzf_compat_args(args: impl Iterator<Item = String>) -> Vec<String> {
    // Presentation flags (`--border`, `--layout`, `--info`, `--color`,
    // `--pointer`, `--marker`, `--bind`, the case flags, …) are stripped HERE
    // but not ignored: `fzf::Look::parse` already read them off the full argv,
    // so they drive the picker's look while clap only ever sees arb's own
    // options. The rest (`--tiebreak`, `--walker`, …) genuinely have no arb
    // analog and are dropped.
    //
    // The four lists are fzf 0.74's whole option surface minus the nine arb
    // declares (`--preview`, `--prompt`, `--header`, `--height`, `--query`,
    // `--exact`, `--no-sort`, `--multi`, `--filter`). They are exhaustive on
    // purpose: an unknown flag makes clap abort, which would break the drop-in
    // for anyone whose `$FZF_DEFAULT_OPTS` mentions a flag arb never modeled.
    // The split is by how a value attaches, which the fzf man page does NOT
    // document — it shows the `[=VALUE]` forms but not which of those also
    // swallow a separate next word — so it was probed off the `fzf` binary:
    // `fzf -f a FLAG XYZZY` reports `unknown option: XYZZY` exactly when FLAG
    // left the word alone.
    //
    // Never takes a value — every `--no-*` negation lives here too.
    const DROP_BOOL: &[&str] = &[
        "--ambidouble",
        "--ansi",
        "--async",
        "--bash",
        "--bench",
        "--black",
        "--bold",
        "--clear",
        "--cycle",
        "--disabled",
        "--enabled",
        "--exit-0",
        "--extended",
        "--filepath-word",
        "--fish",
        "--force-tty-in",
        "--header-first",
        "--highlight-line",
        "--hscroll",
        "--ignore-case",
        "--inline-info",
        "--keep-right",
        "--literal",
        "--man",
        "--multi-line",
        "--no-256",
        "--no-ambidouble",
        "--no-ansi",
        "--no-black",
        "--no-bold",
        "--no-border",
        "--no-border-label",
        "--no-clear",
        "--no-color",
        "--no-cycle",
        "--no-exit-0",
        "--no-expect",
        "--no-extended",
        "--no-filepath-word",
        "--no-footer",
        "--no-footer-border",
        "--no-footer-label",
        "--no-force-tty-in",
        "--no-gap",
        "--no-gap-line",
        "--no-header-border",
        "--no-header-first",
        "--no-header-label",
        "--no-header-lines",
        "--no-header-lines-border",
        "--no-highlight-line",
        "--no-history",
        "--no-hscroll",
        "--no-id-nth",
        "--no-ignore-case",
        "--no-info",
        "--no-info-command",
        "--no-inline-info",
        "--no-input",
        "--no-input-border",
        "--no-input-label",
        "--no-keep-right",
        "--no-list-border",
        "--no-list-label",
        "--no-listen",
        "--no-listen-unsafe",
        "--no-literal",
        "--no-margin",
        "--no-mouse",
        "--no-multi-line",
        "--no-padding",
        "--no-phony",
        "--no-popup",
        "--no-preview-border",
        "--no-preview-label",
        "--no-print-query",
        "--no-print0",
        "--no-raw",
        "--no-read0",
        "--no-reverse",
        "--no-scrollbar",
        "--no-select-1",
        "--no-separator",
        "--no-sync",
        "--no-tac",
        "--no-tail",
        "--no-tmux",
        "--no-track",
        "--no-tty-default",
        "--no-unicode",
        "--no-winpty",
        "--no-wrap",
        "--no-wrap-word",
        "--nushell",
        "--phony",
        "--print-query",
        "--print0",
        "--raw",
        "--read0",
        "--reverse",
        "--select-1",
        "--smart-case",
        "--sync",
        "--tac",
        "--track",
        "--unicode",
        "--wrap-word",
        "--zsh",
        "-0",
        "-1",
    ];
    // Always takes one: fzf consumes the next word even when it looks like a
    // flag (`--prompt --exact` really does set the prompt to `--exact`).
    const DROP_VALUE: &[&str] = &[
        "--accept-nth",
        "--algo",
        "--bind",
        "--border-label",
        "--border-label-pos",
        "--delimiter",
        "--ellipsis",
        "--expect",
        "--footer",
        "--footer-label",
        "--footer-label-pos",
        "--freeze-left",
        "--freeze-right",
        "--ghost",
        "--gutter",
        "--gutter-raw",
        "--header-label",
        "--header-label-pos",
        "--header-lines",
        "--history",
        "--history-size",
        "--hscroll-off",
        "--id-nth",
        "--info",
        "--info-command",
        "--input-label",
        "--input-label-pos",
        "--jump-labels",
        "--layout",
        "--list-label",
        "--list-label-pos",
        "--margin",
        "--marker",
        "--marker-multi-line",
        "--min-height",
        "--nth",
        "--padding",
        "--pointer",
        "--preview-label",
        "--preview-label-pos",
        "--preview-window",
        "--preview-wrap-sign",
        "--profile-block",
        "--profile-cpu",
        "--profile-mem",
        "--profile-mutex",
        "--proxy-script",
        "--scheme",
        "--scroll-off",
        "--separator",
        "--style",
        "--tabstop",
        "--tail",
        "--threads",
        "--tiebreak",
        "--toggle-sort",
        "--tty-default",
        "--walker",
        "--walker-root",
        "--walker-skip",
        "--with-nth",
        "--with-shell",
        "--wrap-sign",
    ];
    // `--border[=STYLE]`: the next word is the value only when it isn't a flag.
    const DROP_OPT_STR: &[&str] = &[
        "--border",
        "--color",
        "--footer-border",
        "--gap-line",
        "--header-border",
        "--header-lines-border",
        "--input-border",
        "--list-border",
        "--listen",
        "--listen-unsafe",
        "--popup",
        "--preview-border",
        "--scrollbar",
        "--tmux",
        "--wrap",
    ];
    // `--gap[=N]`: the next word is the value only when it is a number.
    const DROP_OPT_NUM: &[&str] = &["--gap"];
    // The arb flags an fzf `--no-X` / `+x` has to cancel, with whether the
    // cancelled flag carries a separate value.
    const MULTI: &[&str] = &["--multi", "-m"];

    let argv: Vec<String> = args.collect();
    // Only rewrite fzf short-flags when in fzf mode (else `-e` stays `--eval`).
    let fzf = argv.iter().any(|a| a == "--fzf");
    let mut out: Vec<String> = Vec::new();
    let mut it: Argv = argv.into_iter().peekable();
    while let Some(a) = it.next() {
        if fzf {
            match a.as_str() {
                // `--extended-exact` is fzf's shorthand for `-x -e`; the
                // extended half is read by `fzf::Look`, the exact half is arb's
                // own flag.
                "-e" | "--extended-exact" => {
                    cancel(&mut out, &["--exact"], false);
                    out.push("--exact".to_string());
                    continue;
                }
                // `+e` cancels an earlier `-e`, the way `+i`/`+x`/`+m`/`+s`
                // cancel theirs. Without this the short and long spellings of
                // the same negation (`+e` and `--no-exact`) disagree.
                "+e" => {
                    cancel(&mut out, &["--exact"], false);
                    continue;
                }
                // The case flags and `-x`/`+x` (extended search on/off) reach the
                // matcher through `fzf::Look`, which read them off the full
                // argv; clap knows none of them. `+c` is fzf's undocumented
                // legacy no-color short form.
                "-i" | "+i" | "-x" | "+x" | "+c" => continue,
                // `+m` cancels an earlier `-m`; `+s` is `--no-sort`.
                "+m" => {
                    cancel(&mut out, MULTI, false);
                    continue;
                }
                "+s" => {
                    cancel(&mut out, &["--no-sort"], false);
                    out.push("--no-sort".to_string());
                    continue;
                }
                _ => {}
            }
            // `-q STR` / `-qSTR`: fzf's short `--query`.
            if let Some(rest) = a.strip_prefix("-q") {
                let v = match rest.is_empty() {
                    true => it.next().unwrap_or_default(),
                    false => rest.to_string(),
                };
                out.push("--query".to_string());
                out.push(v);
                continue;
            }
            // `-n FIELDS` / `-d CHAR`, attached or separate: `fzf::Look` already
            // read them off the full argv, so clap must not see them.
            if let Some(rest) = a.strip_prefix("-n").or_else(|| a.strip_prefix("-d")) {
                if rest.is_empty() {
                    it.next();
                }
                continue;
            }
            // `-m[MAX]` / `-s[MAX]`: fzf caps how many lines can be marked
            // and how many the sort covers. arb has no cap, so only the on/off
            // half of each survives.
            if let Some(rest) = a.strip_prefix("-m") {
                if rest.is_empty() && eats_next(it.peek(), true) {
                    it.next();
                }
                cancel(&mut out, MULTI, false);
                out.push("--multi".to_string());
                continue;
            }
            if let Some(rest) = a.strip_prefix("-s") {
                if rest.is_empty() && eats_next(it.peek(), true) {
                    it.next();
                }
                cancel(&mut out, &["--no-sort"], false);
                continue;
            }
        }
        let key = a.split('=').next().unwrap_or(&a);
        // fzf's `--no-X` cancels an earlier `--X`. For the options arb models
        // itself that means removing the pending flag from the rewritten argv,
        // not dropping the negation.
        match key {
            "--no-preview" => {
                cancel(&mut out, &["--preview"], true);
                continue;
            }
            "--no-height" => {
                cancel(&mut out, &["--height"], true);
                continue;
            }
            "--no-header" => {
                cancel(&mut out, &["--header"], true);
                continue;
            }
            "--no-multi" => {
                cancel(&mut out, MULTI, false);
                continue;
            }
            "--no-exact" => {
                cancel(&mut out, &["--exact"], false);
                continue;
            }
            "--no-sort" => {
                cancel(&mut out, &["--no-sort"], false);
                out.push("--no-sort".to_string());
                continue;
            }
            // `--sort[=MAX]` puts the score sort back after a `--no-sort`.
            "--sort" => {
                cancel(&mut out, &["--no-sort"], false);
                if !a.contains('=') && eats_next(it.peek(), true) {
                    it.next();
                }
                continue;
            }
            // `--multi[=MAX]`: the cap is dropped, the flag kept.
            "--multi" => {
                cancel(&mut out, MULTI, false);
                out.push("--multi".to_string());
                if !a.contains('=') && eats_next(it.peek(), true) {
                    it.next();
                }
                continue;
            }
            _ => {}
        }
        if DROP_BOOL.contains(&key) {
            continue;
        }
        if DROP_VALUE.contains(&key) {
            // `--flag=val` carries its value; `--flag val` consumes the next arg.
            if !a.contains('=') {
                it.next();
            }
            continue;
        }
        if DROP_OPT_STR.contains(&key) {
            if !a.contains('=') && eats_next(it.peek(), false) {
                it.next();
            }
            continue;
        }
        if DROP_OPT_NUM.contains(&key) {
            if !a.contains('=') && eats_next(it.peek(), true) {
                it.next();
            }
            continue;
        }
        out.push(a);
    }
    out
}

/// `--filter STR`: score every input line, print the matches best-first. Uses
/// the same scorer, sort and `--tiebreak` as the interactive picker, so the two
/// can never drift apart.
fn run_filter(pat: &str, exact: bool, no_sort: bool, look: &crate::fzf::Look) -> io::Result<()> {
    use std::io::Read;
    use std::io::{BufWriter, Write};
    let stdin = io::stdin();
    let mut reader = io::BufReader::new(stdin.lock());
    // Read the whole stream, then rank it across cores — the matching is the
    // work here, and it parallelizes perfectly.
    let mut blob = Vec::new();
    reader.read_to_end(&mut blob)?;
    // `--read0`: records arrive NUL-separated (`fd -0`, `find -print0`), so a
    // newline is ordinary text inside one of them.
    let sep = match look.read0 {
        true => b'\0',
        false => b'\n',
    };
    // Validate the WHOLE stream once rather than once per line. It is the same
    // work either way, but one pass over the blob runs wide while a million tiny
    // ones cannot, and `str::split` on an ASCII separator searches with the same
    // machinery. Invalid UTF-8 falls back to the per-line path, which keeps its
    // old behaviour of dropping just the offending line.
    // Split on the separator only: a trailing `\r` belongs to the line (macOS
    // `Icon\r` entries are real, and fzf scores them with the CR in place).
    let sep_char = sep as char;
    let mut lines: Vec<&str> = match std::str::from_utf8(&blob) {
        Ok(text) => text.split(sep_char).collect(),
        Err(_) => blob
            .split(|b| *b == sep)
            .map(|l| std::str::from_utf8(l).unwrap_or(""))
            .collect(),
    };
    // A trailing separator yields one empty tail element that was never a line.
    if lines.last() == Some(&"") {
        lines.pop();
    }
    // `--header-lines=N`: the first N lines are a header, not candidates — fzf
    // excludes them from the filter too, not just from the picker.
    // `--tail=N`: only the last N lines are candidates at all.
    // Both drop lines off the FRONT, and `{n}` in `--accept-nth` is the line's
    // index in the INPUT, so count what was dropped rather than renumbering.
    let mut dropped = 0usize;
    if look.header_lines > 0 {
        dropped += look.header_lines.min(lines.len());
        lines.drain(..look.header_lines.min(lines.len()));
    }
    if let Some(n) = look.tail {
        if lines.len() > n {
            dropped += lines.len() - n;
            lines.drain(..lines.len() - n);
        }
    }
    let order = crate::tui::rank(&lines, pat, exact, no_sort, look.tac, look);
    let out = io::stdout();
    let mut out = BufWriter::new(out.lock());
    // `--print0`: records are NUL-terminated, for `xargs -0` downstream.
    let end = match look.print0 {
        true => b"\0" as &[u8],
        false => b"\n",
    };
    // `--print-query` puts the query on its own record first — fzf does this in
    // filter mode too, not only in the picker.
    if look.print_query {
        out.write_all(pat.as_bytes())?;
        out.write_all(end)?;
    }
    for i in order {
        let text = crate::tui::item_text(lines[i], look);
        // `--accept-nth`: print the chosen fields, not the whole line.
        match &look.accept_nth {
            Some(spec) => {
                let rendered = spec.render(&text, look.delimiter.as_deref(), dropped + i);
                out.write_all(rendered.as_bytes())?;
            }
            None => out.write_all(text.as_bytes())?,
        }
        out.write_all(end)?;
    }
    out.flush()
}

/// Run one `arb` invocation inside a host process and return its exit status.
///
/// This is the entry point for a host that has no fork to spend — the `arb`
/// shell builtin in zshrs-native, where arb is linked into the shell and its
/// fzf-compatible finder runs without a process. `argv` is the whole command
/// line, `argv[0]` included, exactly as `main` would have received it.
///
/// [`crate::hosted::run`] is what makes the promise to return keep: an `exit` from
/// anywhere in the command line layer unwinds to here instead of taking the
/// shell down, a panic becomes a status, and the working directory the host
/// had is restored.
pub fn run_argv(argv: &[String]) -> i32 {
    crate::hosted::run(|| match run(argv) {
        Ok(()) => 0,
        // A closed downstream pipe is how `arb … | head` ends, not a failure.
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => 0,
        Err(e) => {
            eprintln!("arb: {e}");
            1
        }
    })
}

fn run(full_argv: &[String]) -> io::Result<()> {
    // Registry verbs (`arb install|add|search|update|publish|uninstall NAME`) are
    // handled before clap so a bare verb isn't mistaken for a spec file.
    let raw: Vec<String> = full_argv.iter().skip(1).cloned().collect();
    if let Some(code) = crate::pkg::dispatch(&raw) {
        crate::hosted::exit(code);
    }

    // `arb --fzf` inherits the user's fzf configuration exactly like the fzf
    // binary: `$FZF_DEFAULT_OPTS_FILE`, then `$FZF_DEFAULT_OPTS`, then the
    // command line — later wins, so an explicit flag still overrides the env.
    // Splicing the env words in right after argv[0] is what lets a themed setup
    // (`ZPWR_FZF='arb --fzf'`) keep its prompt, layout, border, colors and key
    // bindings without editing a single call site.
    let mut argv: Vec<String> = full_argv.to_vec();
    if argv.iter().any(|a| a == "--fzf") {
        let env = crate::fzf::env_args();
        argv.splice(1..1, env);
    }
    // The presentation flags are parsed from the FULL argv (env + command line)
    // before `fzf_compat_args` strips them for clap, which knows only arb's own
    // options.
    let fzf_look = crate::fzf::Look::parse(&argv);
    let cli = Cli::parse_from(fzf_compat_args(argv.into_iter()));

    if cli.repl {
        crate::repl::run();
        return Ok(());
    }

    // `--filter STR` (fzf's `-f`): the matcher without the UI — read stdin,
    // rank, print. No terminal is touched, so it works in a pipeline and in a
    // script, and it is the surface that makes arb's ranking directly
    // comparable to `fzf --filter`.
    if let Some(pat) = cli.filter.as_deref() {
        return run_filter(pat, cli.exact, cli.no_sort, &fzf_look);
    }

    // Editor frontends over stdio (stdin is a pipe, so this must come before the
    // no-args REPL / stdin-tail fallbacks below).
    if cli.lsp {
        crate::lsp::run();
        return Ok(());
    }
    if cli.dap {
        crate::dap::run();
        return Ok(());
    }

    // Introspection dumps: resolve the spec source (FILE / -e / -p), run it
    // through the requested front-end stage, print, and exit — no stream read.
    if cli.dump_tokens {
        return finish_dump(dump_tokens(&cli));
    }
    if cli.dump_ast {
        return finish_dump(dump_ast(&cli));
    }
    if cli.dump_bytecode {
        return finish_dump(dump_bytecode(&cli));
    }
    if cli.disasm {
        return finish_dump(disasm(&cli));
    }

    if cli.list {
        let mut out = io::stdout().lock();
        // Description, then the invocation the preset's header documents,
        // indented under it. Every preset reads a stream someone has to supply,
        // so the name and the blurb alone are not enough to run one.
        for (name, desc, example) in spec::list_presets() {
            writeln!(out, "{name:<10} {desc}")?;
            if !example.is_empty() {
                writeln!(out, "{:<10} {example}", "")?;
            }
        }
        return Ok(());
    }

    // `--tiers EXPR`: lower the expression to its fusevm chunk, evaluate it
    // past the block tier's warm-up threshold, then report which tier took it —
    // asked of fusevm's own eligibility and cache predicates, so the answer
    // comes from the compiler that would have done the work.
    if let Some(expr) = &cli.tiers {
        match crate::tiers::report(expr) {
            Ok(r) => println!("{r}"),
            Err(e) => {
                eprintln!("arb: --tiers: {e}");
                crate::hosted::exit(1);
            }
        }
        return Ok(());
    }

    if cli.list_themes {
        // Each theme printed with a 6-cell 256-color swatch (its c1..c6 palette).
        let mut out = io::stdout().lock();
        for (name, pal) in crate::theme::THEMES {
            let swatch: String = pal
                .iter()
                .map(|&c| format!("\x1b[48;5;{c}m  \x1b[0m"))
                .collect();
            writeln!(out, "{swatch}  {name}")?;
        }
        return Ok(());
    }

    if let Some(name) = &cli.set_theme {
        match crate::theme::set_config_default(name) {
            Ok(()) => {
                println!("arb: default theme set to `{name}` (~/.arb/config.toml)");
                return Ok(());
            }
            Err(e) => {
                eprintln!("arb: --set-theme: {e}");
                crate::hosted::exit(1);
            }
        }
    }

    if let Some(name) = cli.save.clone() {
        return save_preset(&name, &cli);
    }

    if cli.installed {
        let Some(dir) = spec::lib_dir() else {
            eprintln!("arb: no preset library (set HOME or ARB_LIB)");
            crate::hosted::exit(1);
        };
        let mut out = io::stdout().lock();
        for (name, desc, example) in spec::list_user_presets(&dir) {
            writeln!(out, "{name:<10} {desc}")?;
            if !example.is_empty() {
                writeln!(out, "{:<10} {example}", "")?;
            }
        }
        return Ok(());
    }

    if let Some(file) = cli.install.clone() {
        return install_cmd(&file, cli.install_as.as_deref());
    }

    if let Some(name) = cli.uninstall.clone() {
        let Some(dir) = spec::lib_dir() else {
            eprintln!("arb: no preset library (set HOME or ARB_LIB)");
            crate::hosted::exit(1);
        };
        match spec::uninstall_preset(&dir, &name) {
            Ok(true) => eprintln!("arb: uninstalled `{name}`"),
            Ok(false) => {
                eprintln!("arb: `{name}` is not installed");
                crate::hosted::exit(1);
            }
            Err(e) => {
                eprintln!("arb: uninstall: {e}");
                crate::hosted::exit(1);
            }
        }
        return Ok(());
    }

    // Bare `arb` on an interactive terminal — no spec/`-e`/`-p` and nothing
    // piped in — drops into the REPL rather than erroring on the stdin-tail
    // default (which needs a pipe). A piped `find / | arb` still tails.
    // A run-pipeline: `--run`, or a positional containing the `_` arb-stage marker
    // (`arb --fzf 'find / | _ | grep x'`). When the positional IS the pipeline,
    // arb runs it rather than loading it as a spec file.
    let run_pipeline: Option<String> = cli
        .run
        .clone()
        .or_else(|| cli.spec.as_ref().filter(|s| is_arb_pipeline(s)).cloned());
    let positional_pipeline = cli.run.is_none() && run_pipeline.is_some();

    let no_spec_args = cli.spec.is_none() && cli.eval.is_none() && cli.preset.is_none();
    if no_spec_args && run_pipeline.is_none() && io::stdin().is_terminal() {
        crate::repl::run();
        return Ok(());
    }

    // Zero-config sniffing: with no spec and a piped stream (not fzf), peek the
    // first lines and auto-pick the matching stdlib preset. The peeked lines are
    // replayed into the stream so nothing is lost.
    let sniff_ok = no_spec_args && run_pipeline.is_none() && !cli.fzf && !io::stdin().is_terminal();
    let mut prelude: Vec<String> = Vec::new();
    let sniffed: Option<&'static str> = if sniff_ok {
        prelude = peek_lines(SNIFF_LINES, SNIFF_DEADLINE_MS);
        let refs: Vec<&str> = prelude.iter().map(String::as_str).collect();
        crate::sniff::sniff(&refs)
    } else {
        None
    };

    let mut spec = if positional_pipeline {
        // The positional was a pipeline, not a spec file — use the zero-config
        // default (a select list under `--fzf`, otherwise a stream tail).
        spec::build(&parser::parse(default_spec_src(cli.fzf)).unwrap()).unwrap()
    } else if let Some(name) = sniffed {
        // Sniffed a producer/data shape -> its preset; fall back to the tail if
        // the preset fails to build for any reason (never break zero-config).
        parser::parse(&format!("import {name}"))
            .and_then(|c| spec::build(&c))
            .unwrap_or_else(|_| {
                spec::build(&parser::parse(default_spec_src(false)).unwrap()).unwrap()
            })
    } else {
        match load_spec(&cli) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("arb: {e}");
                crate::hosted::exit(1);
            }
        }
    };

    // Resolve the effective theme. Precedence: `--theme` (or `--theme off`) →
    // the spec's own `theme` directive / `theme off` → the `~/.arb/config.toml`
    // global default → the baked `neon-sprawl` default. So every dashboard (and
    // the stdlib presets, which set no color) is themed out of the box, tunable
    // globally via `--set-theme` and per-run via `--theme`.
    // Did anything ASK for an arb theme, or is one about to be applied merely as
    // the baked default? `--fzf` needs to know: a picker that nobody themed must
    // come out in fzf's own colors, not in `neon-sprawl`.
    let theme_requested = cli.theme.is_some() || spec.theme.is_some();
    match cli.theme.as_deref() {
        Some("off") | Some("none") => spec.theme = None,
        Some(name) => match crate::theme::by_name(name) {
            Some(p) => spec.theme = Some(p),
            None => {
                eprintln!("arb: --theme: unknown theme `{name}` (see `arb --list-themes`)");
                crate::hosted::exit(1);
            }
        },
        // No `--theme`: keep an explicit spec directive / `theme off`, else apply
        // the global config default (or the baked default) so presets are themed.
        None if !spec.theme_off && spec.theme.is_none() => {
            spec.theme =
                Some(crate::theme::config_default().unwrap_or_else(crate::theme::default_palette));
        }
        None => {}
    }

    // Select mode is the fzf surface expressed as a widget: `--fzf` synthesizes a
    // `select` spec, and a hand-written `select .name` widget turns it on too — so
    // fzf mode is literally a one-widget DSL spec. The select widget's `-prompt`/
    // `-header` opts feed the prompt line and header when the flags weren't passed.
    let fzf_mode = cli.fzf || has_select(&spec);
    // An unthemed picker renders in fzf's palette (`fzf::Colors`), which is the
    // whole point of the drop-in: `arb --fzf` should be indistinguishable from
    // `fzf`. `--theme NAME` or a spec `theme` directive still wins, and Ctrl-T
    // switches to an arb theme live.
    if fzf_mode && !theme_requested {
        spec.theme = None;
    }
    let (sel_prompt, sel_header) = spec
        .widgets
        .iter()
        .find(|w| w.kind == spec::WidgetKind::Select)
        .map(|w| (w.opts.get("prompt").cloned(), w.opts.get("header").cloned()))
        .unwrap_or((None, None));

    if cli.html {
        print!("{}", crate::web::render_html(&spec));
        return Ok(());
    }

    if cli.test {
        // Run the in-language `test { … }` blocks headlessly (TAP), exit 0/1.
        let report = crate::testrun::run(&spec.tests);
        print!("{}", report.text);
        crate::hosted::exit(if report.failed == 0 { 0 } else { 1 });
    }

    if cli.check {
        println!(
            "arb: ok \u{2014} {} widget(s){}",
            spec.widgets.len(),
            if spec.out.is_some() {
                ", out pipeline"
            } else {
                ""
            }
        );
        return Ok(());
    }

    // `--run 'PROD | arb | CONS'`: arb spawns the surrounding commands and owns
    // their fds. The producer's stdout feeds the stream, its stderr an error pane.
    let (run_producer, consumer) = match &run_pipeline {
        Some(p) => {
            let (pr, co) = parse_pipeline(p);
            (Some(pr), co)
        }
        None => (None, None),
    };
    // A spec-level `spawn CMD` or `< FILE` (§7) is an input source like `--run`'s
    // producer; CLI `--run` wins, then `spawn`, then `< FILE` (as `cat -- FILE`).
    // Either way the producer's stdout feeds the stream in place of stdin.
    let producer = run_producer.or_else(|| spec_producer(&spec));
    // `filename` (yq's) answers the path when the spec named one, and `-` for a
    // pipe — which is what yq answers for a piped document.
    if let Some(f) = spec.source_file.as_deref() {
        crate::yaml::set_input_name(f);
    }

    // A `! CMD every Ns` poll source (§7) feeds the stream on a timer. `--run`
    // and spec `spawn`/`< file` all populate `producer` and are mutually
    // exclusive with `poll` at the spec level, so `poll` only matters when no
    // producer took over (lets CLI `--run` win, mirroring `spawn`).
    let poll = if producer.is_some() {
        None
    } else {
        spec.poll.clone()
    };

    let needs_stdin = needs_stdin(&spec, fzf_mode);
    // A producer (`--run`/`spawn`/`< file`) or a `poll` source supplies the
    // stream itself, so stdin is not required even on an interactive tty.
    if needs_stdin && producer.is_none() && poll.is_none() && io::stdin().is_terminal() {
        // The spec documents what feeds it in its own header comment. Print THAT
        // rather than a generic `find / | arb` — for `arb -p git` the useful
        // answer is `git log --oneline | arb -p git`, and it is already written
        // down two lines into the preset.
        match spec_example(&cli, sniffed) {
            ex if ex.is_empty() => {
                eprintln!("arb: spec reads stdin but nothing is piped — e.g. `find / | arb`");
            }
            ex => eprintln!("arb: spec reads stdin but nothing is piped — try:\narb:   {ex}"),
        }
        crate::hosted::exit(2);
    }

    let state = Arc::new(Mutex::new(stream_state(&spec, fzf_mode)));

    // `--serve`: the same spec as a live browser dashboard. Feed the stream in the
    // background (spawned producer or stdin) and run the HTTP server (blocks).
    if cli.serve {
        // A stdin feed is held until the server returns, then stopped.
        let _feed = if let Some(prod) = &producer {
            if let Err(e) = spawn_producer(prod, state.clone()) {
                eprintln!("arb: run: {e}");
                crate::hosted::exit(1);
            }
            None
        } else if let Some((cmd, dur)) = &poll {
            poll_producer(cmd, *dur, state.clone());
            None
        } else if needs_stdin {
            let controls = Arc::new(Mutex::new(tui::Controls::default()));
            Some(spawn_reader(
                state.clone(),
                false,
                controls,
                None,
                prelude.clone(),
            ))
        } else {
            None
        };
        return crate::serve::serve(spec, state, cli.port);
    }

    // Interactive TUI whenever a controlling terminal is reachable (a `/dev/tty`
    // we can open — see `tui::events_available`); the TUI renders THERE, not to
    // stdout, so it runs even when stdout is piped onward. Exception: a STATIC
    // `out { … }` reshape (no live control) with a downstream consumer takes the
    // headless data path below so the consumer gets the transformed stream. But an
    // INTERACTIVE out — `input` widgets feeding `out { … apply .x }` — keeps the
    // TUI up so typing reshapes the piped stream live (the megafilter/map). With
    // no controlling tty (CI) it falls through, instead of crashing on the reader.
    let interactive_out = spec
        .widgets
        .iter()
        .any(|w| w.kind == spec::WidgetKind::Input)
        && spec
            .out
            .as_ref()
            .is_some_and(|ops| ops.iter().any(|op| matches!(op, QueryOp::Apply(_))));
    let downstream_reshape = spec.out.is_some() && !io::stdout().is_terminal() && !interactive_out;
    if tui::events_available() && !downstream_reshape {
        let controls = Arc::new(Mutex::new(tui::Controls::default()));

        // Feed the stream: a spawned producer (`--run`/`spawn`/`< file`), a
        // `! CMD every Ns` poll loop, or stdin. A stdin feed lives exactly as
        // long as the TUI session.
        let mut feed: Option<StdinFeed> = None;
        let err_pane = if spec.spawn_pty && run_pipeline.is_none() && producer.is_some() {
            // `spawn -pty CMD`: run on a PTY so the child acts interactive, and
            // keep the stdin writer so `send "…"` can drive it (Expect). The PTY
            // merges stdout+stderr, so there's no separate error pane.
            let prod = producer.as_deref().unwrap();
            match crate::pty::spawn_pty_producer(prod, state.clone()) {
                Ok(writer) => {
                    controls.lock().unwrap().pty_writer = Some(writer);
                    None
                }
                Err(e) => {
                    eprintln!("arb: spawn -pty: {e}");
                    crate::hosted::exit(1);
                }
            }
        } else if let Some(prod) = &producer {
            match spawn_producer(prod, state.clone()) {
                Ok(es) => Some((es, "stderr".to_string())),
                Err(e) => {
                    eprintln!("arb: run: {e}");
                    crate::hosted::exit(1);
                }
            }
        } else if let Some((cmd, dur)) = &poll {
            Some((
                poll_producer(cmd, *dur, state.clone()),
                "stderr".to_string(),
            ))
        } else {
            if needs_stdin {
                // Tee the live filtered stream to stdout (only when piped onward,
                // so arb never blocks or corrupts the terminal). fzf mode never
                // tees. The filter narrows the passthrough live — the megafilter.
                // An `out { … }` pipeline additionally MAPS each line as it flows,
                // resolving `apply .name` against live `input` values — so typing
                // in a control reshapes the downstream pipe in real time.
                let tee = !fzf_mode && !io::stdout().is_terminal();
                feed = Some(spawn_reader(
                    state.clone(),
                    tee,
                    controls.clone(),
                    spec.out.clone(),
                    prelude.clone(),
                ));
            }
            None
        };

        // Preview pane. In fzf mode: a per-item `--preview` (run CMD on the cursor
        // line). Otherwise: `arb -- CMD` / the `| CONS` consumer, re-run over the
        // whole filtered output.
        let down_cmd: Vec<String> = match &consumer {
            Some(c) => vec!["sh".to_string(), "-c".to_string(), c.clone()],
            None => cli.down.clone(),
        };
        let down_pane = if fzf_mode {
            cli.preview.as_ref().map(|pv| {
                let pstate = Arc::new(Mutex::new(StreamState::new()));
                spawn_item_preview(
                    pv.clone(),
                    fzf_look.shell(),
                    fzf_look.delimiter.clone(),
                    fzf_look.preview_window.scroll.clone(),
                    controls.clone(),
                    pstate.clone(),
                );
                (pstate, "preview".to_string())
            })
        } else if down_cmd.is_empty() {
            None
        } else {
            let dstate = Arc::new(Mutex::new(StreamState::new()));
            spawn_preview(
                down_cmd.clone(),
                state.clone(),
                controls.clone(),
                dstate.clone(),
            );
            let label = consumer.clone().unwrap_or_else(|| cli.down.join(" "));
            Some((dstate, label))
        };
        {
            let mut c = controls.lock().unwrap();
            // Flags win; else fall back to the `select` widget's -prompt/-header.
            c.prompt = cli
                .prompt
                .clone()
                .or(sel_prompt.clone())
                .unwrap_or_default();
            c.header = cli
                .header
                .clone()
                .or(sel_header.clone())
                .unwrap_or_default();
            // Form mode: register every control widget (input/filter/facet/
            // slider/check) so keys edit them and `apply`/`where … .name` resolve
            // against their live values. `control_meta` carries slider/facet
            // bounds + the facet cursor, parallel to `inputs`.
            for w in spec.widgets.iter().filter(|w| w.kind.is_control()) {
                // A `sel` widget's value is its highlighted row, exposed under the
                // `.<path>.sel` accessor (SPEC §14) — so a `.ps` selection list
                // registers control `ps.sel`. Every other control is `.<path>`.
                let name = if w.kind == spec::WidgetKind::Sel {
                    format!("{}.sel", w.path.trim_start_matches('.'))
                } else {
                    w.path.trim_start_matches('.').to_string()
                };
                let opt_f =
                    |k: &str, d: f64| w.opts.get(k).map(|s| spec::parse_scalar(s)).unwrap_or(d);
                let kind = tui::control_kind(w.kind);
                let (min, max, step) = (opt_f("min", 0.0), opt_f("max", 100.0), opt_f("step", 1.0));
                // Initial value: slider = min, check = "0", others = "".
                let init = match kind {
                    tui::ControlKind::Slider => format!("{min}"),
                    tui::ControlKind::Check => "0".to_string(),
                    _ => String::new(),
                };
                let opts: Vec<String> = w
                    .opts
                    .get("opts")
                    .map(|s| {
                        s.split(',')
                            .filter(|x| !x.is_empty())
                            .map(String::from)
                            .collect()
                    })
                    .unwrap_or_default();
                c.inputs.push((name, init));
                c.control_meta.push(tui::ControlMeta {
                    kind,
                    min,
                    max,
                    step,
                    opts,
                    cursor: 0,
                });
            }
            // Actor session (§15): spawn every `spawn`/`pool` ref once, held for
            // the session so `tell`/`ask` bind actions can drive them. Names are
            // validated at build, so this only fails on an internal mismatch.
            if !spec.actor_refs.is_empty() {
                match crate::actor::Session::build(&spec.actors, &spec.actor_refs) {
                    Ok(session) => c.session = session,
                    Err(e) => {
                        eprintln!("arb: {e}");
                        crate::hosted::exit(1);
                    }
                }
            }
            // Key bindings (`bind C-<letter> …`) drive the same input values.
            // Seed the live theme from the resolved spec/config theme; Ctrl-T
            // cycles it from here and persists the choice to ~/.arb.
            c.theme = spec.theme;
            c.theme_idx = spec.theme.map(crate::theme::index_of).unwrap_or(0);
            c.binds = spec.binds.clone();
            // Mouse reactions (`bind <Click> …`).
            c.mouse_binds = spec.mouse_binds.clone();
            // fzf-compat: exact/no-sort match modes; `--query` seeds the filter.
            c.exact = cli.exact;
            c.no_sort = cli.no_sort;
            // The resolved fzf presentation (layout/border/info/colors/pointer)
            // plus its `--bind` table, which the key handler consults first.
            // Only `--fzf` inherits fzf's bottom-up default layout; a DSL
            // `select` widget keeps arb's prompt-on-top list.
            c.look = if cli.fzf {
                fzf_look.clone()
            } else {
                crate::fzf::Look {
                    layout: crate::fzf::Layout::Reverse,
                    ..crate::fzf::Look::default()
                }
            };
            if let Some(q) = &cli.query {
                c.filter = q.clone();
            }
            // fzf only marks with `-m`/`--multi`; `arb --fzf` matches that. A
            // DSL `select` widget (fzf mode without `--fzf`) keeps marking on.
            c.multi = cli.multi || !cli.fzf;
        }
        let outcome = tui::run(
            &spec,
            state,
            controls.clone(),
            down_pane,
            err_pane,
            fzf_mode,
            cli.height.clone(),
        );
        // The session is over: stop reading stdin before emitting anything, so
        // no reader outlives this call (see `Interruptible`).
        drop(feed);
        if fzf_mode {
            // On Enter (submit) emit the selection (marked lines, or the cursor
            // line). With a `| CONS` consumer, pipe the selection through it first
            // (`find / | _ | perl -pe …` transforms the picked lines). Abort
            // (Esc/Ctrl-C) exits 130 with no output.
            // The guard must be gone before `exit`: hosted, `exit` unwinds, and a guard
            // dropped by that unwind poisons `controls` for the preview thread that
            // outlives this call.
            let submit = controls.lock().unwrap().submit;
            if submit {
                let c = controls.lock().unwrap();
                let out = match &consumer {
                    Some(cons) => run_capture(&["sh".into(), "-c".into(), cons.clone()], &c.result),
                    None => c.result.clone(),
                };
                // fzf's output contract: `--print-query` writes the query first,
                // then `--expect` writes the key that accepted (blank for plain
                // Enter), then the selection. fzf-tab parses exactly this.
                if fzf_look.print_query {
                    println!("{}", c.filter);
                }
                if !fzf_look.expect.is_empty() {
                    println!("{}", c.expect_key.clone().unwrap_or_default());
                }
                for line in out {
                    println!("{line}");
                }
            } else {
                crate::hosted::exit(130);
            }
        }
        outcome
    } else {
        let feed = Feed {
            producer: producer.as_deref(),
            poll: poll.as_ref().map(|(cmd, _)| cmd.as_str()),
            needs_stdin,
            prelude: &prelude,
        };
        headless(
            &spec,
            &state,
            &feed,
            cli.json,
            io::stdin().lock(),
            io::stdout().lock(),
            &mut io::stderr(),
        )
    }
}

/// Whether the spec has a `select` widget, which turns on fzf mode.
fn has_select(spec: &Spec) -> bool {
    spec.widgets
        .iter()
        .any(|w| w.kind == spec::WidgetKind::Select)
}

/// The spec's own input source: `spawn CMD`, or `< FILE` run as `cat -- FILE`.
/// A CLI `--run` producer takes precedence over both.
fn spec_producer(spec: &Spec) -> Option<String> {
    spec.spawn.clone().or_else(|| {
        spec.source_file
            .as_deref()
            .map(|f| format!("cat -- {}", shell_quote(f)))
    })
}

/// Whether the spec consumes the stream at all.
fn needs_stdin(spec: &Spec, fzf_mode: bool) -> bool {
    fzf_mode || spec.out.is_some() || spec.widgets.iter().any(|w| w.source.is_some())
}

/// The line buffer a run accumulates the stream into.
///
/// fzf select mode keeps every line (no ring drop), so marks persist as the
/// stream grows. An `out { … }` reshape also needs every line — its reducers
/// (`count`/`sum`/`sort`) run over the whole accumulated stream, so a bounded
/// ring would silently drop the oldest lines and yield a wrong total. The live
/// TUI/served dashboard uses the bounded ring (only the visible tail matters).
///
/// The retention is a large FINITE cap, not `usize::MAX`: a live producer
/// (`spawn tail -f`, a `! poll` source) is an unbounded stream, and an
/// uncapped buffer would grow until the process OOMs. This ceiling keeps every
/// line for any realistic finite input (a piped file/command that ends) — so
/// reducers stay exact — while windowing a genuinely infinite stream to its
/// most recent lines instead of exhausting memory.
fn stream_state(spec: &Spec, fzf_mode: bool) -> StreamState {
    const MAX_RETAIN: usize = 2_000_000;
    if fzf_mode || spec.out.is_some() {
        StreamState::with_cap(MAX_RETAIN)
    } else {
        StreamState::new()
    }
}

/// What feeds a headless run besides its input reader.
struct Feed<'a> {
    /// `--run`'s producer, or the spec's `spawn CMD` / `< FILE`.
    producer: Option<&'a str>,
    /// A `! CMD every Ns` source, when no producer took over.
    poll: Option<&'a str>,
    needs_stdin: bool,
    /// Lines already read off the input by zero-config sniffing.
    prelude: &'a [String],
}

/// A run with no TUI: write the `out { … }` reshape, the producer or input
/// passed through, or the spec summary to `out`, and diagnostics to `err`.
///
/// The `arb` binary hands it the process's stdin/stdout/stderr;
/// [`crate::embed::run_program`] hands it in-memory buffers.
fn headless<R: Read, W: Write>(
    spec: &Spec,
    state: &Arc<Mutex<StreamState>>,
    feed: &Feed,
    json: bool,
    input: R,
    out: W,
    err: &mut dyn Write,
) -> io::Result<()> {
    if let Some(out_ops) = &spec.out {
        // Piped downstream: arb modifies the stream. A per-line pipeline streams
        // (so `tail -f | arb 'out {…}' | …` works live); reducers/sorts batch.
        if let Some(prod) = feed.producer {
            // A spec `spawn CMD`/`< file` feeds the stream here (no tty); drain
            // it, then apply `out { … }` — without this the headless path would
            // read an empty stdin and emit nothing.
            read_producer_sync(prod, state)?;
            emit_out(out_ops, state, json, out, err)
        } else if let Some(cmd) = feed.poll {
            // Headless `! CMD every Ns`: run CMD once and reshape it (an endless
            // poll into a reducer/emit could never terminate).
            read_producer_sync(cmd, state)?;
            emit_out(out_ops, state, json, out, err)
        } else if feed.needs_stdin && !json && query::is_line_streamable(out_ops) {
            stream_out(out_ops, input, out, err)
        } else {
            if feed.needs_stdin {
                read_stdin_sync(state, feed.prelude, input);
            }
            emit_out(out_ops, state, json, out, err)
        }
    } else if let Some(prod) = feed.producer {
        // `spawn CMD`/`< file` with no `out { … }`, piped onward: forward the
        // producer's output through untouched (the passthrough twin).
        stream_producer(prod, out)
    } else if let Some(cmd) = feed.poll {
        // Headless `! CMD every Ns` with no `out { … }`: forward one run.
        stream_producer(cmd, out)
    } else if feed.needs_stdin {
        // A dashboard spec piped onward with no `out { … }` reshape — arb is a
        // passive tap: forward the stream through untouched so the downstream
        // consumer still receives it (`find / | arb dash.arb | stryke`). Only an
        // explicit `out { … }` changes what flows downstream.
        passthrough(feed.prelude, input, out)
    } else {
        dump(spec, state, out)
    }
}

/// Build `src` and run it the way `arb -e SRC` runs with its stdin and stdout
/// both pipes: `input` is the stream, `out` receives what the binary would
/// write to stdout, `err` what it would write to stderr. Never opens a TUI.
pub(crate) fn run_headless<R: Read, W: Write>(
    src: &str,
    input: R,
    out: W,
    err: &mut dyn Write,
) -> io::Result<()> {
    let spec = match build_spec(src) {
        Ok(s) => s,
        Err(e) => {
            let _ = writeln!(err, "arb: {e}");
            crate::hosted::exit(1);
        }
    };
    if let Some(f) = spec.source_file.as_deref() {
        crate::yaml::set_input_name(f);
    }
    let fzf_mode = has_select(&spec);
    let producer = spec_producer(&spec);
    let feed = Feed {
        producer: producer.as_deref(),
        poll: match &producer {
            Some(_) => None,
            None => spec.poll.as_ref().map(|(cmd, _)| cmd.as_str()),
        },
        needs_stdin: needs_stdin(&spec, fzf_mode),
        prelude: &[],
    };
    let state = Arc::new(Mutex::new(stream_state(&spec, fzf_mode)));
    headless(&spec, &state, &feed, false, input, out, err)
}

/// POSIX single-quote a string so it survives `sh -c` as one literal argument
/// (used to fold `< FILE` into a `cat -- FILE` producer). Any embedded `'` is
/// closed, escaped, and reopened (`'\''`).
fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

/// Run `producer` (`sh -c`) and drain its stdout into `state` synchronously,
/// blocking until the child closes stdout. The headless twin of `spawn_producer`
/// (which uses background threads) so `emit_out` sees the full output.
fn read_producer_sync(producer: &str, state: &Arc<Mutex<StreamState>>) -> io::Result<()> {
    let mut child = Command::new("sh")
        .arg("-c")
        .arg(producer)
        .stdout(Stdio::piped())
        .spawn()?;
    if let Some(out) = child.stdout.take() {
        for line in BufReader::new(out).lines() {
            match line {
                Ok(l) => state.lock().unwrap().push(l),
                Err(_) => break,
            }
        }
    }
    let _ = child.wait();
    Ok(())
}

/// A stdout writer for a line stream that must be fast on a BULK pipe and prompt
/// on a LIVE one.
///
/// `io::stdout().lock()` is a `LineWriter`: every `\n` costs a `write(2)`. On a
/// 2.4M-line stream that was 756 of 2434 profile samples — the single largest
/// cost in the run, and why `jq` (stdio, which block-buffers when stdout is
/// redirected) was ahead on every filter measured. A plain `BufWriter` fixes the
/// bulk case and breaks the live one: `tail -f … | arb | consumer` would stall
/// until 256KB accumulated.
///
/// So the flush is decided per line by the READER, not by a timer and not by an
/// `is_terminal()` guess. If the reader still holds buffered bytes, the next
/// lines are already in hand — a bulk stream — so hold the output. If its buffer
/// is empty the next read will block (a live stream, or EOF), so flush now.
/// Bulk piping costs one syscall per 256KB; a live tail still gets one per line,
/// because each line arrives as its own read.
struct LineOut<W: Write>(io::BufWriter<W>);

impl<W: Write> LineOut<W> {
    fn new(w: W) -> Self {
        LineOut(io::BufWriter::with_capacity(256 * 1024, w))
    }

    fn line(&mut self, l: &str) -> io::Result<()> {
        writeln!(self.0, "{l}")
    }

    /// Flush unless `more` says the reader has further input already buffered.
    fn sync(&mut self, more: bool) -> io::Result<()> {
        if more {
            Ok(())
        } else {
            self.0.flush()
        }
    }

    fn finish(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

/// Read one `\n`-terminated line into `buf`, appending its text to `line` with
/// the terminator stripped the way `BufRead::lines` strips it (`\r\n` too).
/// Returns `false` at EOF or on input that is not UTF-8, which is where
/// `lines()` yields an `Err` and every caller here stops.
///
/// This exists so the loops below can own their `BufReader` — `lines()` hides it,
/// and `LineOut::sync` needs to ask it whether more input is already buffered.
/// Reusing one buffer also drops the `String` `lines()` allocates per line.
fn read_line_into<R: BufRead>(r: &mut R, buf: &mut Vec<u8>, line: &mut String) -> bool {
    buf.clear();
    match r.read_until(b'\n', buf) {
        Ok(0) | Err(_) => return false,
        Ok(_) => {}
    }
    if buf.last() == Some(&b'\n') {
        buf.pop();
        if buf.last() == Some(&b'\r') {
            buf.pop();
        }
    }
    let Ok(text) = std::str::from_utf8(buf) else {
        return false;
    };
    line.clear();
    line.push_str(text);
    true
}

/// Run `producer` (`sh -c`) and copy its stdout to `out` line by line,
/// flushing per line. Used for a headless `spawn CMD` with no `out { … }` — arb
/// forwards the spawned stream to the downstream consumer.
fn stream_producer<W: Write>(producer: &str, out: W) -> io::Result<()> {
    let mut child = Command::new("sh")
        .arg("-c")
        .arg(producer)
        .stdout(Stdio::piped())
        .spawn()?;
    if let Some(pipe) = child.stdout.take() {
        let mut w = LineOut::new(out);
        let mut r = BufReader::with_capacity(256 * 1024, pipe);
        let (mut buf, mut line) = (Vec::new(), String::new());
        while read_line_into(&mut r, &mut buf, &mut line) {
            let more = !r.buffer().is_empty();
            if w.line(&line).and_then(|()| w.sync(more)).is_err() {
                break;
            }
        }
        let _ = w.finish();
    }
    let _ = child.wait();
    Ok(())
}

/// arb as a transparent tap: copy every stdin line to stdout unchanged, flushing
/// per line so a live upstream (`tail -f`) reaches the downstream consumer
/// promptly. Used when a dashboard spec is piped onward with no `out { … }`.
fn passthrough<R: Read, W: Write>(prelude: &[String], input: R, out: W) -> io::Result<()> {
    let mut out = LineOut::new(out);
    let mut r = BufReader::with_capacity(256 * 1024, input);
    // Replay any sniff-peeked lines first, then the rest of stdin. A peeked line
    // is already in hand, so it never forces a flush of its own.
    for (i, l) in prelude.iter().enumerate() {
        let more = i + 1 < prelude.len();
        if let Err(e) = out.line(l).and_then(|()| out.sync(more)) {
            return ok_on_broken_pipe(Err(e));
        }
    }
    let (mut buf, mut line) = (Vec::new(), String::new());
    while read_line_into(&mut r, &mut buf, &mut line) {
        let more = !r.buffer().is_empty();
        if let Err(e) = out.line(&line).and_then(|()| out.sync(more)) {
            return ok_on_broken_pipe(Err(e));
        }
    }
    ok_on_broken_pipe(out.finish())
}

/// Treat a closed downstream pipe (the consumer exited — `| head`, `| stryke`
/// quitting) as clean EOF rather than an error, like any well-behaved Unix
/// filter. Other I/O errors propagate.
fn ok_on_broken_pipe(r: io::Result<()>) -> io::Result<()> {
    match r {
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),
        other => other,
    }
}

/// Write the `out { … }` pipeline's result to stdout (arb as a pipe filter).
/// Stream a per-line `out` pipeline: apply it to each line as it arrives and
/// emit results immediately with a flush, so live pipes work without buffering.
fn stream_out<R: Read, W: Write>(
    ops: &[QueryOp],
    input: R,
    out: W,
    err: &mut dyn Write,
) -> io::Result<()> {
    let mut out = LineOut::new(out);
    let mut r = BufReader::with_capacity(256 * 1024, input);
    let (mut buf, mut line) = (Vec::new(), String::new());
    // `in.json` reads DOCUMENTS, which may span lines or share one, so its
    // regrouping runs here, ahead of the per-item pipeline.
    let (mut docs, ops) = match ops.split_first() {
        Some((QueryOp::JsonDocs, rest)) => (Some(crate::jsondocs::JsonDocs::default()), rest),
        _ => (None, ops),
    };
    let mut items = Vec::new();
    // jq's main loop: an input that raises prints what it produced, reports
    // the error, and the NEXT input still runs; the exit status is the last
    // input's (5 when it raised). `halt`/`halt_error` end the run.
    let mut failed = false;
    let mut lineno = 0usize;
    loop {
        let more = read_line_into(&mut r, &mut buf, &mut line);
        if more {
            lineno += 1;
        }
        let run = match (&mut docs, more) {
            (Some(d), true) if d.passes_through(&line) => stream_item(
                ops,
                std::slice::from_ref(&line),
                lineno,
                &mut out,
                &mut failed,
                err,
            ),
            (Some(d), true) => {
                d.push(&line, &mut items);
                Ok(())
            }
            (Some(d), false) => {
                d.finish(&mut items);
                Ok(())
            }
            (None, true) => stream_item(
                ops,
                std::slice::from_ref(&line),
                lineno,
                &mut out,
                &mut failed,
                err,
            ),
            (None, false) => Ok(()),
        };
        let run = run.and_then(|()| {
            items.drain(..).try_for_each(|item| {
                stream_item(
                    ops,
                    std::slice::from_ref(&item),
                    lineno,
                    &mut out,
                    &mut failed,
                    err,
                )
            })
        });
        if let Err(e) = run {
            return ok_on_broken_pipe(Err(e));
        }
        if !more {
            break;
        }
        if let Err(e) = out.sync(!r.buffer().is_empty()) {
            return ok_on_broken_pipe(Err(e));
        }
    }
    let done = ok_on_broken_pipe(out.finish());
    if failed {
        crate::hosted::exit(5);
    }
    done
}

/// Run one stream item (a one-element slice) through `ops`, writing its lines
/// and diagnostics. `failed` becomes this item's jq status; `halt` ends the
/// process here.
fn stream_item<W: Write>(
    ops: &[QueryOp],
    item: &[String],
    lineno: usize,
    out: &mut LineOut<W>,
    failed: &mut bool,
    err: &mut dyn Write,
) -> io::Result<()> {
    let mut rep = query::JqReport::default();
    match query::eval_reporting(ops, item, 0.0, lineno, &mut rep) {
        QueryResult::Lines(ls) => {
            for l in ls {
                out.line(&l)?;
            }
            *failed = rep.last_failed;
        }
        // SPEC §8: a construct outside the documented subset is a hard error,
        // never a silent reinterpretation. `5` is jq's own status for a filter
        // that raised.
        QueryResult::Error(msg) => {
            rep.errors.push(msg);
            *failed = true;
        }
        _ => *failed = false,
    }
    if !rep.errors.is_empty() || rep.halt.is_some() {
        // Flush first so the lines already produced reach the consumer before
        // the diagnostic.
        let _ = out.finish();
        report_jq(&rep, err);
    }
    if let Some((code, _)) = rep.halt {
        crate::hosted::exit(code);
    }
    Ok(())
}

/// Write a jq program's stderr: each uncaught error under arb's `arb: ` prefix,
/// then `halt_error`'s message exactly as jq writes it (no prefix, and a
/// trailing newline only where jq adds one).
fn report_jq(rep: &query::JqReport, err: &mut dyn Write) {
    for e in &rep.errors {
        let _ = writeln!(err, "arb: {e}");
    }
    if let Some((_, msg)) = &rep.halt {
        let _ = write!(err, "{msg}");
    }
}

fn emit_out<W: Write>(
    ops: &[QueryOp],
    state: &Arc<Mutex<StreamState>>,
    json: bool,
    mut out: W,
    err: &mut dyn Write,
) -> io::Result<()> {
    let st = state.lock().unwrap();
    let raw: Vec<String> = st.lines.iter().map(|l| l.to_string()).collect();
    let elapsed = st.start.elapsed().as_secs_f64();
    if json {
        let v = match query::eval(ops, &raw, elapsed) {
            QueryResult::Lines(ls) => {
                serde_json::Value::Array(ls.into_iter().map(serde_json::Value::String).collect())
            }
            QueryResult::Scalar(s) => serde_json::Number::from_f64(s)
                .map(serde_json::Value::Number)
                .unwrap_or(serde_json::Value::Null),
            QueryResult::Pairs(ps) => {
                let mut m = serde_json::Map::new();
                for (k, c) in ps {
                    m.insert(k, serde_json::Value::Number(c.into()));
                }
                serde_json::Value::Object(m)
            }
            QueryResult::Error(msg) => {
                let _ = writeln!(err, "arb: {msg}");
                crate::hosted::exit(5);
            }
        };
        writeln!(out, "{}", serde_json::to_string(&v).unwrap_or_default())?;
        return Ok(());
    }
    // The line output keeps jq's stream semantics, as `stream_out` does.
    let mut rep = query::JqReport::default();
    match query::eval_reporting(ops, &raw, elapsed, 1, &mut rep) {
        QueryResult::Lines(ls) => {
            for l in ls {
                writeln!(out, "{l}")?;
            }
        }
        // Same formatter the `--test` runner uses. A raw `{v}` printed the empty
        // `sum` as `-0`, because Rust's `Sum for f64` folds from `-0.0` (the only
        // identity that preserves the sign of a `+0.0` addend) — so a reducer over
        // no numeric lines rendered a negative zero, and `-e` disagreed with
        // `--test` on the same pipeline.
        QueryResult::Scalar(v) => writeln!(out, "{}", query::fmt_scalar(v))?,
        QueryResult::Pairs(ps) => {
            for (k, c) in ps {
                writeln!(out, "{k}\t{c}")?;
            }
        }
        QueryResult::Error(msg) => {
            let _ = out.flush();
            let _ = writeln!(err, "arb: {msg}");
            crate::hosted::exit(5);
        }
    }
    if !rep.errors.is_empty() || rep.halt.is_some() {
        out.flush()?;
        report_jq(&rep, err);
    }
    match rep.halt {
        Some((code, _)) => crate::hosted::exit(code),
        None if rep.last_failed => crate::hosted::exit(5),
        None => Ok(()),
    }
}

/// Validate a spec and copy it into `~/.arb/lib/NAME.arb` so it can later be run
/// with `arb -p NAME` from anywhere.
fn save_preset(name: &str, cli: &Cli) -> io::Result<()> {
    let src = if let Some(e) = &cli.eval {
        e.clone()
    } else if let Some(f) = &cli.spec {
        std::fs::read_to_string(f)?
    } else {
        eprintln!("arb: --save needs a spec — a FILE argument or -e SRC");
        crate::hosted::exit(2);
    };
    if let Err(e) = parser::parse(&src).and_then(|c| spec::build(&c)) {
        eprintln!("arb: --save: invalid spec: {e}");
        crate::hosted::exit(1);
    }
    let dir = spec::lib_dir().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            "no preset library (set HOME or ARB_LIB)",
        )
    })?;
    match spec::install_preset(&dir, name, &src) {
        Ok(path) => {
            eprintln!("arb: saved preset `{name}` -> {}", path.display());
            Ok(())
        }
        Err(e) => {
            eprintln!("arb: --save: {e}");
            crate::hosted::exit(1);
        }
    }
}

/// `arb --install FILE [--as NAME]`: install a shared spec file into the preset
/// library so it can be run with `arb -p NAME` from anywhere.
fn install_cmd(file: &str, as_name: Option<&str>) -> io::Result<()> {
    let src = std::fs::read_to_string(file)
        .map_err(|e| io::Error::new(e.kind(), format!("{file}: {e}")))?;
    let name = as_name
        .map(str::to_string)
        .or_else(|| {
            std::path::Path::new(file)
                .file_stem()
                .and_then(|s| s.to_str())
                .map(str::to_string)
        })
        .unwrap_or_default();
    let Some(dir) = spec::lib_dir() else {
        eprintln!("arb: no preset library (set HOME or ARB_LIB)");
        crate::hosted::exit(1);
    };
    match spec::install_preset(&dir, &name, &src) {
        Ok(path) => {
            eprintln!("arb: installed `{name}` -> {}", path.display());
            Ok(())
        }
        Err(e) => {
            eprintln!("arb: {e}");
            crate::hosted::exit(1);
        }
    }
}

/// The invocation the loaded spec documents in its own header comment: a
/// preset's (`-p NAME`, or the one a sniffed stream picked) resolved the way
/// `import` resolves it, a spec FILE's read off disk. Empty when the spec is
/// `-e SRC`, or when its header is prose rather than a command line.
fn spec_example(cli: &Cli, sniffed: Option<&str>) -> String {
    if let Some(name) = cli.preset.as_deref().or(sniffed) {
        return spec::preset_example(name);
    }
    match cli
        .spec
        .as_deref()
        .and_then(|p| std::fs::read_to_string(p).ok())
    {
        Some(src) => spec::example_comment(&src),
        None => String::new(),
    }
}

/// Resolve the spec SOURCE for the introspection dumps: `-p NAME` -> `import NAME`,
/// `-e SRC` -> the literal, a `FILE` positional -> its contents. Errors if none is
/// given (a dump has nothing to inspect without a spec).
fn dump_src(cli: &Cli) -> Result<String, String> {
    if let Some(p) = &cli.preset {
        Ok(format!("import {p}"))
    } else if let Some(e) = &cli.eval {
        Ok(e.clone())
    } else if let Some(path) = &cli.spec {
        std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))
    } else {
        Err("dump needs a spec — a FILE argument, -e SRC, or -p NAME".into())
    }
}

/// Report a dump's outcome the arb way: on error, `arb: <reason>` to stderr and
/// exit 1; on success, exit 0. The dump-flag twin of the pervasive `arb: {e}`
/// pattern, adapting the `Result<(), String>` dump fns to `main`'s `io::Result`.
fn finish_dump(r: Result<(), String>) -> io::Result<()> {
    if let Err(e) = r {
        eprintln!("arb: {e}");
        crate::hosted::exit(1);
    }
    Ok(())
}

/// `--dump-tokens`: print the Tcl-flavored lexer token stream, one
/// `offset<TAB>Tok` per line (offset = the token's start char position in the
/// source — the same anchor the LSP uses for diagnostics).
fn dump_tokens(cli: &Cli) -> Result<(), String> {
    let src = dump_src(cli)?;
    // Top-level tokenization, so jq literals are off — a `{ … }` body arrives here
    // as one `Block` token whose inner text the parser re-lexes with them on.
    for (tok, off) in crate::lexer::lex(&src, false).map_err(|e| e.to_string())? {
        println!("{off}\t{tok:?}");
    }
    Ok(())
}

/// `--dump-ast`: print the parsed command tree (the spec AST — a `Vec<Command>`).
fn dump_ast(cli: &Cli) -> Result<(), String> {
    let src = dump_src(cli)?;
    let cmds = crate::parser::parse(&src).map_err(|e| e.to_string())?;
    println!("{cmds:#?}");
    Ok(())
}

/// `--dump-bytecode`: build the spec and print its compiled query pipelines — the
/// `out { … }` pipeline and each widget's `source` pipeline as their `QueryOp` op
/// vectors. This is arb's compiled form; there is no separate fusevm program (only
/// the expression layer inside `where`/`map` lowers to fusevm), so the op vectors
/// are the bytecode the runtime evaluates. The pretty-printed twin of `--disasm`.
fn dump_bytecode(cli: &Cli) -> Result<(), String> {
    let spec = build_dump_spec(cli)?;
    if let Some(ops) = &spec.out {
        println!("== out ==\n{ops:#?}");
    }
    for w in &spec.widgets {
        match &w.source {
            Some(s) => println!("== {} ({}) ==\n{:#?}", w.path, w.kind.label(), s.pipeline),
            None => println!(
                "== {} ({}) ==\n(no source pipeline)",
                w.path,
                w.kind.label()
            ),
        }
    }
    Ok(())
}

/// `--disasm`: build the spec and print a flat, numbered disassembly of every
/// compiled pipeline (`out` + each widget `source`), one `NNNN  Op` per line — the
/// listing view of the same `QueryOp` op vectors `--dump-bytecode` pretty-prints.
fn disasm(cli: &Cli) -> Result<(), String> {
    let spec = build_dump_spec(cli)?;
    if let Some(ops) = &spec.out {
        println!("; arb pipeline — out");
        disasm_ops(ops);
    }
    for w in &spec.widgets {
        println!("; arb pipeline — {} ({})", w.path, w.kind.label());
        match &w.source {
            Some(s) => disasm_ops(&s.pipeline),
            None => println!("  (no source pipeline)"),
        }
    }
    Ok(())
}

/// Parse + build the spec from the resolved dump source (shared by the two
/// bytecode-level dumps), stringifying either stage's error.
fn build_dump_spec(cli: &Cli) -> Result<Spec, String> {
    let src = dump_src(cli)?;
    let cmds = parser::parse(&src).map_err(|e| e.to_string())?;
    spec::build(&cmds).map_err(|e| e.to_string())
}

/// Print one compiled pipeline as a numbered op listing.
fn disasm_ops(ops: &[QueryOp]) {
    for (i, op) in ops.iter().enumerate() {
        println!("{i:04}  {op:?}");
    }
}

fn load_spec(cli: &Cli) -> Result<Spec, String> {
    let src = if let Some(p) = &cli.preset {
        format!("import {p}")
    } else if let Some(e) = &cli.eval {
        e.clone()
    } else if let Some(path) = &cli.spec {
        std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?
    } else {
        // Zero-config default: a select list under `--fzf`, else a stream tail.
        default_spec_src(cli.fzf).to_string()
    };
    build_spec(&src)
}

/// Parse and build a spec from its source text. The rkyv script cache skips
/// lex+parse for a previously-seen source.
fn build_spec(src: &str) -> Result<Spec, String> {
    spec::build(&cache::parse_cached(src).map_err(String::from)?).map_err(String::from)
}

/// The synthesized spec source when the user gave no spec/`-e`/`-p`. `--fzf`
/// yields a one-widget `select` list (fzf as a DSL spec); otherwise a full-screen
/// tail of stdin. Both bind `in` so the shared stream feeds the widget.
/// How many lines to peek for zero-config sniffing, and how long to wait for
/// them — sniffing must never delay startup or hang on an idle producer.
const SNIFF_LINES: usize = 8;
const SNIFF_DEADLINE_MS: i32 = 150;

/// True if stdin (fd 0) has data ready to read within `timeout_ms` — so peeking
/// never blocks on an idle producer (e.g. `tail -f empty.log | arb`).
fn stdin_ready(timeout_ms: i32) -> bool {
    let mut pfd = libc::pollfd {
        fd: 0,
        events: libc::POLLIN,
        revents: 0,
    };
    // SAFETY: single valid pollfd, count 1.
    unsafe { libc::poll(&mut pfd, 1, timeout_ms) > 0 && (pfd.revents & libc::POLLIN) != 0 }
}

/// Peek up to `max` lines from stdin for sniffing, without ever blocking on an
/// idle producer. Consumed lines are returned so the caller replays them into
/// the stream (the rest stay buffered in the global stdin for the feed thread).
fn peek_lines(max: usize, deadline_ms: i32) -> Vec<String> {
    use std::io::BufRead;
    let mut out = Vec::new();
    let stdin = io::stdin();
    let mut lock = stdin.lock();
    for _ in 0..max {
        if !stdin_ready(deadline_ms) {
            break; // no data ready — don't block
        }
        let mut line = String::new();
        match lock.read_line(&mut line) {
            Ok(0) => break, // EOF
            Ok(_) => out.push(line.trim_end_matches(['\n', '\r']).to_string()),
            Err(_) => break,
        }
    }
    out
}

fn default_spec_src(fzf: bool) -> &'static str {
    if fzf {
        "select .sel\nsource .sel { in }"
    } else {
        "tail .stream\nsource .stream { in }"
    }
}

/// Read stdin into the shared stream for the TUI. When `tee`, each line is also
/// written to stdout immediately (a live passthrough for a downstream consumer),
/// so `find / | arb | consumer` feeds `consumer` continuously while the TUI
/// renders to /dev/tty — arb never blocks the pipeline. A closed consumer stops
/// the passthrough but the TUI keeps updating.
/// Whether a string is an arb pipeline: it has a bare `_` stage (the marker for
/// "arb goes here"), e.g. `sudo find / | _ | perl -pe '…'`.
fn is_arb_pipeline(s: &str) -> bool {
    s.split('|').any(|seg| seg.trim() == "_")
}

/// Split an arb pipeline on the `_` stage marker into (producer, consumer).
/// `find / | _ | grep x` -> ("find /", Some("grep x")); no `_` marker -> the
/// whole string is the producer. (Segments are shelled out per-stage; a zshrs
/// lexer can replace that later without changing arb's fd orchestration.)
fn parse_pipeline(s: &str) -> (String, Option<String>) {
    let segs: Vec<&str> = s.split('|').map(str::trim).collect();
    match segs.iter().position(|seg| *seg == "_") {
        Some(p) => {
            let producer = segs[..p].join(" | ");
            let consumer = segs[p + 1..].join(" | ");
            (
                producer,
                if consumer.is_empty() {
                    None
                } else {
                    Some(consumer)
                },
            )
        }
        None => (s.trim().to_string(), None),
    }
}

/// Drain any reader (a spawned command's stdout or stderr) line-by-line into a
/// `StreamState` — used to feed arb's stream from the producer's stdout and the
/// error pane from its stderr.
fn spawn_source_reader<R: io::Read + Send + 'static>(reader: R, state: Arc<Mutex<StreamState>>) {
    thread::spawn(move || {
        for line in BufReader::new(reader).lines() {
            match line {
                Ok(l) => state.lock().unwrap().push(l),
                Err(_) => break,
            }
        }
    });
}

/// Spawn the producer command (`sh -c`) with arb owning its fds: stdout streams
/// into `state`, stderr into a fresh `StreamState` returned for the error pane.
/// A background thread `wait()`s on the child so it is reaped (not zombied) when
/// it exits; it otherwise runs on its own until arb exits.
fn spawn_producer(
    producer: &str,
    state: Arc<Mutex<StreamState>>,
) -> io::Result<Arc<Mutex<StreamState>>> {
    let mut child = Command::new("sh")
        .arg("-c")
        .arg(producer)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let out = child
        .stdout
        .take()
        .ok_or_else(|| io::Error::other("no stdout"))?;
    let err = child
        .stderr
        .take()
        .ok_or_else(|| io::Error::other("no stderr"))?;
    // Reap the child when it exits (a bare `drop(child)` leaves a zombie until
    // arb itself exits — the doc's "killed when arb exits" was inaccurate).
    thread::spawn(move || {
        let _ = child.wait();
    });
    spawn_source_reader(out, state);
    let err_state = Arc::new(Mutex::new(StreamState::new()));
    spawn_source_reader(err, err_state.clone());
    Ok(err_state)
}

/// Background poll source (`! CMD every Ns`, §7): re-run CMD via `sh -c` every
/// `interval`, draining each run's stdout into `state` and stderr into the
/// returned error-pane state. Per-cycle reader threads join before the sleep so
/// a chatty command's stderr can't deadlock on a full pipe buffer. Loops until
/// arb exits; the one-shot headless twin is `read_producer_sync`.
fn poll_producer(
    cmd: &str,
    interval: Duration,
    state: Arc<Mutex<StreamState>>,
) -> Arc<Mutex<StreamState>> {
    let err_state = Arc::new(Mutex::new(StreamState::new()));
    let (cmd, es) = (cmd.to_string(), err_state.clone());
    thread::spawn(move || loop {
        if let Ok(mut child) = Command::new("sh")
            .arg("-c")
            .arg(&cmd)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
        {
            let (st, et) = (state.clone(), es.clone());
            let ho = child.stdout.take().map(|o| {
                thread::spawn(move || {
                    for l in BufReader::new(o).lines().map_while(Result::ok) {
                        st.lock().unwrap().push(l);
                    }
                })
            });
            let he = child.stderr.take().map(|e| {
                thread::spawn(move || {
                    for l in BufReader::new(e).lines().map_while(Result::ok) {
                        et.lock().unwrap().push(l);
                    }
                })
            });
            if let Some(h) = ho {
                let _ = h.join();
            }
            if let Some(h) = he {
                let _ = h.join();
            }
            let _ = child.wait();
        }
        thread::sleep(interval);
    });
    err_state
}

/// A reader over `fd` that a thread blocked on it can be told to leave.
///
/// A blocking `read(2)` cannot be interrupted from another thread, so a feed
/// thread parked in one outlives the invocation that started it. The `arb`
/// binary never notices — exiting reclaims the thread. Hosted inside
/// zshrs-native (the `arb` builtin) it stays in the shell, holding the
/// process-wide `StdinLock` and reading fd 0, which is the terminal again once
/// the builtin returns: it eats the keystrokes typed at the prompt, and the next
/// `arb --fzf` neither gets its input (the lock is taken) nor reliably its keys.
///
/// `fd` must already be non-blocking. A read that would block waits in `select`
/// for at most [`tui::STOP_POLL_MS`], then checks `stop` again; once `stop` is
/// set every read is end of input. `inner` is read directly, so for stdin the
/// `StdinLock` keeps serving the lines the sniffer buffered past what it peeked.
struct Interruptible<R> {
    inner: R,
    fd: RawFd,
    stop: Arc<AtomicBool>,
}

impl<R: io::Read> io::Read for Interruptible<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        loop {
            if self.stop.load(Ordering::Relaxed) {
                return Ok(0);
            }
            match self.inner.read(buf) {
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                    if tui::select_readable(self.fd, tui::STOP_POLL_MS).is_none() {
                        // Unrepresentable in an fd_set: sleep instead of spinning.
                        thread::sleep(Duration::from_millis(tui::STOP_POLL_MS as u64));
                    }
                }
                Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                r => return r,
            }
        }
    }
}

/// Put `fd` in non-blocking mode, returning its previous flags to restore.
/// `None` when it could not be done — the fd stays blocking.
fn set_nonblocking(fd: RawFd) -> Option<libc::c_int> {
    // SAFETY: fcntl on an fd we only query and flag; no memory is passed.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
        return None;
    }
    Some(flags)
}

/// The stdin feed thread, stopped and joined when this drops — at the end of the
/// TUI, and on every other way out of [`run`], `hosted::exit` unwinds included.
/// Only then does fd 0 get its blocking mode back, so the thread never sees a
/// blocking fd 0 it could park on.
struct StdinFeed {
    stop: Arc<AtomicBool>,
    thread: Option<thread::JoinHandle<()>>,
    /// fd 0's flags before the feed made it non-blocking. `None` if that
    /// failed: the thread may then be parked in a read nothing can end, so it
    /// is left to run rather than joined forever.
    saved_flags: Option<libc::c_int>,
}

impl Drop for StdinFeed {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        let Some(flags) = self.saved_flags else {
            return;
        };
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
        // SAFETY: restores the flags read from this same fd in `set_nonblocking`.
        unsafe { libc::fcntl(0, libc::F_SETFL, flags) };
    }
}

fn spawn_reader(
    state: Arc<Mutex<StreamState>>,
    tee: bool,
    controls: Arc<Mutex<tui::Controls>>,
    out_ops: Option<Vec<QueryOp>>,
    prelude: Vec<String>,
) -> StdinFeed {
    let stop = Arc::new(AtomicBool::new(false));
    let saved_flags = set_nonblocking(0);
    let thread_stop = stop.clone();
    let thread = thread::spawn(move || {
        let stop = thread_stop;
        // Only hold the stdout lock when actually teeing. Otherwise (e.g. --fzf,
        // which emits its selection from `main` after the TUI exits) this thread
        // would keep stdout locked for its whole life and deadlock `main`'s final
        // `println!` — the process would never terminate after selection.
        let mut out = if tee { Some(io::stdout().lock()) } else { None };
        let mut downstream_open = tee;
        // Megafilter/map cache: re-resolve the `out` pipeline only when the live
        // `input` values change (resolving parses the input text — cheap, but not
        // worth doing per line on a fast stream). `resolved` maps each line; it is
        // only used per-line when line-streamable (a reducer like `count` can't
        // map a single line, so we fall back to passthrough for it).
        let map = out_ops.is_some();
        let mut last_inputs: Option<Vec<(String, String)>> = None;
        let mut resolved: Vec<QueryOp> = Vec::new();
        let mut resolved_ok = false;
        // Replay any sniff-peeked lines first, then the rest of stdin. Lines are
        // read into ONE reused buffer and handed on as `Arc<str>`: `lines()`
        // would allocate a `String` per line that the stream then copies again.
        // Lock stdin ONCE: `read_until` on the unlocked handle takes the stdin
        // mutex per call, which at a million lines costs more than the read.
        let mut stdin = io::BufReader::with_capacity(
            256 * 1024,
            Interruptible {
                inner: io::stdin().lock(),
                fd: 0,
                stop: stop.clone(),
            },
        );
        let mut raw = Vec::new();
        let mut prelude = prelude.into_iter();
        let feed = std::iter::from_fn(move || -> Option<std::sync::Arc<str>> {
            if let Some(p) = prelude.next() {
                return Some(std::sync::Arc::from(p.as_str()));
            }
            raw.clear();
            match stdin.read_until(b'\n', &mut raw) {
                Ok(0) | Err(_) => None,
                Ok(_) => {
                    if raw.last() == Some(&b'\n') {
                        raw.pop();
                    }
                    // Straight from the read buffer into the shared handle: one
                    // allocation per line, no intermediate `String`.
                    Some(std::sync::Arc::from(String::from_utf8_lossy(&raw).as_ref()))
                }
            }
        });
        // Lines are handed to the shared stream in batches: one mutex round trip
        // per line costs more than the read itself on a `find /`-sized stream.
        // The batch is flushed on size or on a short idle, so a slow trickle
        // still shows up immediately.
        const BATCH: usize = 512;
        const FLUSH_AFTER: std::time::Duration = std::time::Duration::from_millis(15);
        let mut batch: Vec<std::sync::Arc<str>> = Vec::with_capacity(BATCH);
        let mut last_flush = std::time::Instant::now();
        for l in feed {
            // Up to a buffer's worth of lines is already read when the session
            // ends; none of it is wanted, and teeing it could block on a stalled
            // consumer.
            if stop.load(Ordering::Relaxed) {
                break;
            }
            if let Some(o) = out.as_mut() {
                // One lock: snapshot the live filter and input values together.
                let (filter, inputs) = {
                    let c = controls.lock().unwrap();
                    (c.filter.clone(), c.inputs.clone())
                };
                // Megafilter: only lines matching the live filter flow downstream.
                if tui::filter_matches(&l, &filter) && downstream_open {
                    if map {
                        if last_inputs.as_ref() != Some(&inputs) {
                            let imap: std::collections::HashMap<String, String> =
                                inputs.iter().cloned().collect();
                            resolved =
                                spec::resolve_pipeline(out_ops.as_deref().unwrap_or(&[]), &imap);
                            resolved_ok = query::is_line_streamable(&resolved);
                            last_inputs = Some(inputs);
                        }
                        // Map the line through the resolved pipeline (identity when
                        // it resolved to nothing); non-streamable → raw passthrough.
                        let outs = if resolved_ok {
                            tui::project_line(&resolved, &l)
                        } else {
                            vec![l.to_string()]
                        };
                        for ol in outs {
                            if writeln!(o, "{ol}").and_then(|()| o.flush()).is_err() {
                                downstream_open = false;
                                break;
                            }
                        }
                    } else if writeln!(o, "{l}").and_then(|()| o.flush()).is_err() {
                        downstream_open = false;
                    }
                }
            }
            batch.push(l);
            if batch.len() >= BATCH || last_flush.elapsed() >= FLUSH_AFTER {
                state.lock().unwrap().extend(batch.drain(..));
                last_flush = std::time::Instant::now();
            }
        }
        if !batch.is_empty() {
            state.lock().unwrap().extend(batch.drain(..));
        }
    });
    StdinFeed {
        stop,
        thread: Some(thread),
        saved_flags,
    }
}

/// `arb -- CMD` preview: re-run the command chain over arb's CURRENT post-filter
/// output whenever the filter or the stream changes, capturing its stdout+stderr
/// into `dstate` for the pane. The chain always sees the filtered lines, and the
/// pane stays in sync with the filter — no stale pre-filter accumulation, and the
/// command's output never touches the terminal.
fn spawn_preview(
    cmd: Vec<String>,
    state: Arc<Mutex<StreamState>>,
    controls: Arc<Mutex<tui::Controls>>,
    dstate: Arc<Mutex<StreamState>>,
) {
    thread::spawn(move || {
        let mut last: Option<(String, u64)> = None;
        loop {
            thread::sleep(Duration::from_millis(250));
            let (filter, quit) = {
                let c = controls.lock().unwrap();
                (c.filter.clone(), c.quit)
            };
            if quit {
                break;
            }
            // Re-run only when the filter or the line count changed.
            let key = (filter.clone(), state.lock().unwrap().total);
            if last.as_ref() == Some(&key) {
                continue;
            }
            last = Some(key);
            let input: Vec<String> = {
                let s = state.lock().unwrap();
                s.lines
                    .iter()
                    .filter(|l| tui::filter_matches(l, &filter))
                    .map(|l| l.to_string())
                    .collect()
            };
            let output = run_capture(&cmd, &input);
            let mut d = dstate.lock().unwrap();
            *d = StreamState::new();
            for l in output {
                d.push(l);
            }
        }
    });
}

/// Single-quote a string for safe `sh -c` substitution of `{}` (a line may hold
/// spaces or shell metacharacters — e.g. a path). `'` -> `'\''`.
fn shell_escape(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// fzf `--preview`: run `template` (with `{}` replaced by the line under the
/// cursor) whenever the cursor moves, capturing its output into `pstate` for the
/// preview pane. Debounced; skips re-running on an unchanged line.
fn spawn_item_preview(
    template: String,
    shell: Vec<String>,
    delimiter: Option<String>,
    scroll: Option<crate::fzf::PreviewScroll>,
    controls: Arc<Mutex<tui::Controls>>,
    pstate: Arc<Mutex<StreamState>>,
) {
    thread::spawn(move || {
        let mut last = String::from("\u{0}");
        loop {
            thread::sleep(Duration::from_millis(120));
            let (cur, quit) = {
                let c = controls.lock().unwrap();
                (c.current.clone(), c.quit)
            };
            if quit {
                break;
            }
            if cur == last {
                continue;
            }
            last = cur.clone();
            if cur.is_empty() {
                continue;
            }
            let cmd =
                crate::fzf::expand_preview(&template, &cur, delimiter.as_deref(), shell_escape);
            // fzf starts children with `$SHELL -c`; a preview using the user's
            // shell (zsh's `print`, one of their functions) needs that shell.
            let mut argv = shell.clone();
            argv.push(cmd);
            let output = run_capture(&argv, &[]);
            let mut p = pstate.lock().unwrap();
            *p = StreamState::new();
            for l in output {
                p.push(l);
            }
            drop(p);
            // `--preview-window +SCROLL`: hand the start line to the run loop,
            // which knows the pane's height. Only if the cursor is still here.
            let target = scroll
                .as_ref()
                .and_then(|s| Some((s.target(&cur, delimiter.as_deref())?, s.denom)));
            let mut c = controls.lock().unwrap();
            if c.current == cur {
                c.preview_start = target;
            }
        }
    });
}

/// Run `cmd`, feeding `input` on its stdin, and collect its stdout then stderr as
/// lines. A spawn/exec error becomes a single diagnostic line so it shows in the
/// pane rather than crashing arb.
fn run_capture(cmd: &[String], input: &[String]) -> Vec<String> {
    let child = Command::new(&cmd[0])
        .args(&cmd[1..])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn();
    let mut child = match child {
        Ok(c) => c,
        Err(e) => return vec![format!("arb: {}: {e}", cmd[0])],
    };
    if let Some(mut si) = child.stdin.take() {
        for l in input {
            if writeln!(si, "{l}").is_err() {
                break; // consumer closed its stdin early (e.g. `head`)
            }
        }
    }
    match child.wait_with_output() {
        Ok(o) => {
            let mut v: Vec<String> = String::from_utf8_lossy(&o.stdout)
                .lines()
                .map(String::from)
                .collect();
            v.extend(String::from_utf8_lossy(&o.stderr).lines().map(String::from));
            v
        }
        Err(e) => vec![format!("arb: {}: {e}", cmd[0])],
    }
}

fn read_stdin_sync<R: Read>(state: &Arc<Mutex<StreamState>>, prelude: &[String], input: R) {
    for l in prelude {
        state.lock().unwrap().push(l.clone());
    }
    for line in BufReader::new(input).lines() {
        match line {
            Ok(l) => state.lock().unwrap().push(l),
            Err(_) => break,
        }
    }
}

fn dump<W: Write>(spec: &Spec, state: &Arc<Mutex<StreamState>>, mut out: W) -> io::Result<()> {
    let st = state.lock().unwrap();
    let raw: Vec<String> = st.lines.iter().map(|l| l.to_string()).collect();
    let elapsed = st.start.elapsed().as_secs_f64();
    writeln!(
        out,
        "arb: spec — {} widget(s) (no terminal; render skipped)",
        spec.widgets.len()
    )?;
    for w in &spec.widgets {
        let (src, res) = match &w.source {
            Some(s) => {
                let r = match query::eval(&s.pipeline, &raw, elapsed) {
                    QueryResult::Scalar(v) => format!("= {v}"),
                    QueryResult::Lines(ls) => format!("-> {} line(s)", ls.len()),
                    QueryResult::Pairs(p) => format!("-> {} group(s)", p.len()),
                    QueryResult::Error(e) => format!("! {e}"),
                };
                (format!("stdin[{} op]", s.pipeline.len()), r)
            }
            None => ("-".to_string(), String::new()),
        };
        writeln!(
            out,
            "  {:<10} {:<6} source={:<12} {:<16} opts={:?}",
            w.path,
            w.kind.label(),
            src,
            res,
            w.opts
        )?;
    }
    writeln!(out, "stream: {} lines", st.total)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::fzf_compat_args;

    fn run(args: &[&str]) -> Vec<String> {
        fzf_compat_args(args.iter().map(|s| s.to_string()))
    }

    #[test]
    fn presentation_flags_are_parsed_then_kept_from_clap() {
        // These now DRIVE the picker (via `fzf::Look`) but clap must never see
        // them — an undeclared flag would abort the whole run, which is exactly
        // what a real `$FZF_DEFAULT_OPTS` would trigger.
        let argv = [
            "arb",
            "--fzf",
            "--layout=reverse",
            "--info",
            "inline",
            "--pointer",
            ">",
            "--marker",
            "+",
            "--color=dark,hl:2",
            "--bind",
            "tab:toggle+down",
            "--scroll-off",
            "0",
            "--ellipsis",
            "~",
            "--tac",
            "--no-scrollbar",
            "--prompt",
            "P> ",
        ];
        let look = crate::fzf::Look::parse(&argv.iter().map(|s| s.to_string()).collect::<Vec<_>>());
        assert_eq!(look.layout, crate::fzf::Layout::Reverse);
        assert_eq!(look.pointer, ">");
        assert_eq!(look.scroll_off, 0);
        assert_eq!(look.ellipsis, "~");
        assert!(look.tac && !look.scrollbar);
        let out = run(&argv);
        for a in [
            "--layout=reverse",
            "--info",
            "inline",
            "--pointer",
            "--marker",
            "--color=dark,hl:2",
            "--bind",
            "tab:toggle+down",
            "--scroll-off",
            "--ellipsis",
            "--tac",
            "--no-scrollbar",
        ] {
            assert!(!out.iter().any(|o| o == a), "{a} reached clap");
        }
        // arb's own flags still pass through untouched.
        assert!(out.iter().any(|o| o == "--prompt"));
        assert!(out.iter().any(|o| o == "P> "));
    }

    #[test]
    fn strips_cosmetic_fzf_flags_keeps_honored() {
        let out = run(&[
            "arb",
            "--fzf",
            "--ansi",
            "--border",
            "--reverse",
            "--preview-window",
            "down:3",
            "--min-height",
            "15",
            "--no-sort",
            "--query",
            "foo",
        ]);
        // Cosmetic bool + value flags gone; honored ones remain.
        assert!(!out
            .iter()
            .any(|a| a == "--ansi" || a == "--border" || a == "--reverse"));
        assert!(!out.iter().any(|a| a == "--preview-window" || a == "down:3"));
        assert!(!out.iter().any(|a| a == "--min-height" || a == "15"));
        assert!(out.iter().any(|a| a == "--no-sort"));
        assert_eq!(
            out.iter().position(|a| a == "--query").map(|i| &out[i + 1]),
            Some(&"foo".to_string())
        );
        assert!(out.iter().any(|a| a == "--fzf"));
    }

    #[test]
    fn translates_fzf_plus_and_exact_shorthands() {
        // `+m` drops (arb is single-select by default); `+s` -> --no-sort.
        let out = run(&["arb", "--fzf", "+m", "+s", "-e"]);
        assert!(!out.iter().any(|a| a == "+m" || a == "+s"));
        assert!(out.iter().any(|a| a == "--no-sort"));
        assert!(out.iter().any(|a| a == "--exact"));
        // Outside fzf mode, `-e` is left alone (it's arb's --eval).
        let out2 = run(&["arb", "-e", "gauge .g"]);
        assert!(out2.iter().any(|a| a == "-e"));
        assert!(!out2.iter().any(|a| a == "--exact"));
    }

    #[test]
    fn drops_fzf_short_value_flags() {
        // `-n2..,..` (attached) and `-n 2..` (separate) and `-d:` are dropped.
        let out = run(&["arb", "--fzf", "-n2..,..", "-d", ":", "--query", "q"]);
        assert!(!out
            .iter()
            .any(|a| a.starts_with("-n") || a.starts_with("-d")));
        assert!(!out.iter().any(|a| a == "2.." || a == ":"));
        assert_eq!(
            out.iter().position(|a| a == "--query").map(|i| &out[i + 1]),
            Some(&"q".to_string())
        );
    }

    #[test]
    fn preview_window_equals_form_drops_cleanly() {
        // `--flag=val` carries its value, so nothing after it should be consumed.
        let out = run(&["arb", "--fzf", "--preview-window=right:50%", "--query", "q"]);
        assert!(!out.iter().any(|a| a.starts_with("--preview-window")));
        assert_eq!(
            out.iter().position(|a| a == "--query").map(|i| &out[i + 1]),
            Some(&"q".to_string())
        );
    }

    #[test]
    fn a_no_flag_cancels_the_arb_option_it_negates() {
        // fzf's `--no-X` is last-one-wins over an earlier `--X`, so for the
        // options arb declares the negation has to REMOVE the flag (and its
        // separate value) instead of being dropped on the floor. Dropping it is
        // what made `--no-preview` reach clap and abort the whole run.
        let out = run(&[
            "arb",
            "--fzf",
            "--preview",
            "cat {}",
            "--no-preview",
            "--height",
            "40%",
            "--no-height",
            "--header=H",
            "--no-header",
            "-m",
            "--no-multi",
            "--exact",
            "--no-exact",
            "--query",
            "q",
        ]);
        for a in ["--preview", "cat {}", "--height", "40%", "--exact", "-m"] {
            assert!(!out.iter().any(|o| o == a), "{a} survived its --no- form");
        }
        assert!(!out.iter().any(|o| o.starts_with("--header")));
        assert!(!out.iter().any(|o| o.starts_with("--no-")));
        // Everything else still lands.
        assert_eq!(
            out.iter().position(|a| a == "--query").map(|i| &out[i + 1]),
            Some(&"q".to_string())
        );
    }

    #[test]
    fn sort_and_multi_take_their_optional_count_back() {
        // `--sort[=MAX]` puts the score sort back after `--no-sort`, and both it
        // and `--multi[=MAX]` swallow a SEPARATE count — but only a numeric one.
        let out = run(&["arb", "--fzf", "--no-sort", "--sort", "20", "--multi=5"]);
        assert!(!out.iter().any(|a| a == "--no-sort" || a == "20"));
        assert_eq!(out.iter().filter(|a| *a == "--multi").count(), 1);
        // A non-numeric word after `--sort` is the next argument, not its count.
        let out = run(&["arb", "--fzf", "--sort", "--query", "q"]);
        assert_eq!(
            out.iter().position(|a| a == "--query").map(|i| &out[i + 1]),
            Some(&"q".to_string())
        );
        // `+m`/`+s` are the same negations in fzf's short spelling.
        let out = run(&["arb", "--fzf", "-m5", "+m", "-s", "+s"]);
        assert!(!out.iter().any(|a| a == "--multi" || a == "5"));
        assert_eq!(out, vec!["arb", "--fzf", "--no-sort"]);
    }

    #[test]
    fn an_optional_value_flag_only_eats_a_real_value() {
        // `--border[=STYLE]` takes the next word only when it isn't a flag —
        // fzf's own rule. Consuming unconditionally ate the flag behind it, so
        // `--color --preview CMD` silently lost the preview.
        let out = run(&[
            "arb",
            "--fzf",
            "--color",
            "--preview",
            "cat {}",
            "--border",
            "rounded",
            "--gap",
            "--query",
            "q",
        ]);
        assert_eq!(
            out.iter()
                .position(|a| a == "--preview")
                .map(|i| &out[i + 1]),
            Some(&"cat {}".to_string())
        );
        assert!(!out.iter().any(|a| a == "rounded" || a == "--border"));
        assert_eq!(
            out.iter().position(|a| a == "--query").map(|i| &out[i + 1]),
            Some(&"q".to_string())
        );
        // `--gap[=N]` is numeric, so it eats `2` but never a word.
        let out = run(&["arb", "--fzf", "--gap", "2", "--query", "q"]);
        assert!(!out.iter().any(|a| a == "2"));
    }

    #[test]
    fn fzf_short_flags_translate_or_drop() {
        // `-q` is fzf's short --query, attached or separate.
        assert_eq!(
            run(&["arb", "--fzf", "-qfoo"]),
            vec!["arb", "--fzf", "--query", "foo"]
        );
        assert_eq!(
            run(&["arb", "--fzf", "-q", "foo"]),
            vec!["arb", "--fzf", "--query", "foo"]
        );
        // Case mode reaches the picker through `fzf::Look`; `-x`/`+x` switch
        // extended-search operators arb's matcher doesn't have; `+c` is fzf's
        // legacy no-color. None of them may reach clap.
        assert_eq!(
            run(&["arb", "--fzf", "-i", "+i", "-x", "+x", "+c"]),
            vec!["arb", "--fzf"]
        );
        // Outside fzf mode the same words are arb's own and pass through.
        assert!(run(&["arb", "-e", "gauge .g"]).iter().any(|a| a == "-e"));
    }

    #[test]
    fn case_flags_drive_the_matcher() {
        use crate::fzf::{Case, Look};
        let look = |args: &[&str]| {
            Look::parse(&args.iter().map(|s| s.to_string()).collect::<Vec<_>>()).case
        };
        assert_eq!(look(&["arb", "--fzf"]), Case::Smart);
        assert_eq!(look(&["arb", "--fzf", "-i"]), Case::Ignore);
        assert_eq!(look(&["arb", "--fzf", "--ignore-case"]), Case::Ignore);
        assert_eq!(look(&["arb", "--fzf", "+i"]), Case::Respect);
        // Later wins, so `--smart-case` at the call site undoes an `-i` that
        // came in from `$FZF_DEFAULT_OPTS`.
        assert_eq!(look(&["arb", "--fzf", "-i", "--smart-case"]), Case::Smart);
        // A lowercase query is case-blind under smart-case, sensitive under +i.
        use crate::tui::fuzzy_score_case;
        assert!(fuzzy_score_case("README", "read", Case::Smart).is_some());
        assert!(fuzzy_score_case("README", "read", Case::Respect).is_none());
        assert!(fuzzy_score_case("readme", "READ", Case::Smart).is_none());
        assert!(fuzzy_score_case("readme", "READ", Case::Ignore).is_some());
    }

    /// A feed on an input that never ends — the producer still running when the
    /// user picks — has to leave when told. A blocking read never does, and
    /// hosted in zshrs-native that reader outlived the `arb` call, holding the
    /// stdin lock and eating the keystrokes typed at the shell prompt.
    #[test]
    fn an_interruptible_reader_leaves_an_open_idle_pipe_when_stopped() {
        use super::{set_nonblocking, Interruptible};
        use std::io::{BufRead, BufReader, Write};
        use std::os::unix::io::FromRawFd;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::{mpsc, Arc};
        use std::time::Duration;

        let mut fds = [0; 2];
        assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
        let (rfd, wfd) = (fds[0], fds[1]);
        set_nonblocking(rfd).expect("a pipe goes non-blocking");
        // SAFETY: both fds are fresh from pipe(2) and each is owned exactly once.
        let (read_end, mut writer) = unsafe {
            (
                std::fs::File::from_raw_fd(rfd),
                std::fs::File::from_raw_fd(wfd),
            )
        };

        let stop = Arc::new(AtomicBool::new(false));
        let reader = Interruptible {
            inner: read_end,
            fd: rfd,
            stop: stop.clone(),
        };
        let (tx, rx) = mpsc::channel();
        std::thread::spawn(move || {
            for line in BufReader::new(reader).lines() {
                tx.send(Some(line.unwrap())).unwrap();
            }
            tx.send(None).unwrap();
        });
        let next = || rx.recv_timeout(Duration::from_secs(5)).unwrap();

        // Lines written while the reader waits are still delivered.
        writeln!(writer, "a\nb").unwrap();
        assert_eq!(next().as_deref(), Some("a"));
        assert_eq!(next().as_deref(), Some("b"));
        // The write end stays open: nothing ends this read but the stop.
        assert!(rx.recv_timeout(Duration::from_millis(200)).is_err());
        stop.store(true, Ordering::Relaxed);
        assert_eq!(next(), None);
    }
}