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
//! Interpreter: command tree -> a `Spec`. Recognizes the widget verbs,
//! `source .x { … }` whose body compiles to a query pipeline (see `query`), and
//! the `.x <- in` bind shorthand. Unknown widget verbs are ignored so specs stay
//! forward-compatible.

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use regex::Regex;

use crate::actor::ActorDef;
use crate::ast::{Arg, Command};
use crate::query::{FieldSel, QueryOp};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WidgetKind {
    Text,
    Tail,
    List,
    Gauge,
    Bars,
    Histo,
    Spark,
    Chart,
    Table,
    Tabs,
    Block,
    Frame,
    /// A thin single-line progress bar (ratatui `LineGauge`) — a compact `gauge`
    /// for tight grid cells. Same scalar source + `-max` as `gauge`.
    LineGauge,
    /// A braille scatter/line plot (ratatui `Canvas`) of a numeric series — a
    /// higher-resolution `chart` drawn with braille dots. `-mode line|points`.
    Scatter,
    /// A block-bar sparkline (ratatui `Sparkline`) of the numeric series — the
    /// classic fixed-height bar sparkline (distinct from `spark`'s braille line).
    Sparkline,
    /// A braille world map (ratatui `Canvas` + `Map`) plotting `lon lat` points
    /// parsed from the stream — geo scatter (IP geolocation, GPS traces). `-res
    /// high|low`.
    Map,
    /// A month calendar (ratatui `Monthly`) for the current month, highlighting
    /// days that appear as `YYYY-MM-DD` in the stream (activity by day).
    Calendar,
    /// A level-colored log tail: like `tail`, but each line is tinted by its log
    /// level (ERROR/WARN/INFO/DEBUG) detected in the text — theme-aware.
    LogView,
    /// A heatmap grid (GitHub-contribution-style): the numeric series laid out as
    /// colored cells, each cell's shade scaled from the value across the palette.
    Heatmap,
    /// A treemap (slice-and-dice): `tally`/`count_by` pairs as proportional
    /// labeled rectangles filling the pane, colored across the palette.
    Treemap,
    /// A Gantt/timeline: `label start end` lines drawn as horizontal bars on a
    /// shared time axis (min start → max end).
    Gantt,
    /// A diff-colored view: each line tinted by its leading char — `+` add (green),
    /// `-` remove (red), `@` hunk (accent) — for `git diff`/patch streams.
    Diff,
    /// The ratatui logo (braille wordmark), centered — a decorative splash.
    Logo,
    /// A blank spacer (ratatui `Clear`) — occupies a grid cell without drawing, to
    /// open space in a layout.
    Blank,
    /// A horizontal (or `-dir vertical`) divider rule in the theme accent.
    Rule,
    /// An in-dashboard selection list over its own `source` (per-widget), with a
    /// moveable cursor. Its highlighted row is published as the control value
    /// `.<path>.sel`, readable from `where`/`apply`/`tell`/`ask` (SPEC §14). E.g.
    /// `ps aux | arb` with `sel .ps { in }` exposes `.ps.sel` = the current row.
    Sel,
    /// An editable text field. Its live value is bound into pipelines via
    /// `apply .name` (parse the value as a query pipeline) — the megafilter/map.
    Input,
    /// An interactive fuzzy-select list over the stream (the fzf surface as a
    /// widget). Its presence puts the TUI in select mode: type to fuzzy-filter,
    /// arrows/Ctrl-N/P move the cursor, Tab marks, Enter emits the picked lines.
    /// `-prompt`/`-header` opts set the prompt line and a header above the list.
    Select,
    /// A text box whose value drives `where match(.name)` / `apply` — a labelled
    /// filter control (a specialised `input`).
    Filter,
    /// A multi-select of candidate values (`-opts {a b c}`, else distinct stream
    /// `-field` values). Its value is the comma-joined selected set for
    /// `where <field> in .name`.
    Facet,
    /// A numeric control (`-min`/`-max`/`-step`) whose value drives
    /// `where <field> < .name`; arrows/`+`/`-` adjust it.
    Slider,
    /// A boolean toggle (`-label`); its value is `"1"`/`"0"`.
    Check,
}

impl WidgetKind {
    pub(crate) fn from(verb: &str) -> Option<WidgetKind> {
        Some(match verb {
            "text" => WidgetKind::Text,
            "tail" => WidgetKind::Tail,
            "list" => WidgetKind::List,
            "gauge" => WidgetKind::Gauge,
            "bars" => WidgetKind::Bars,
            "histo" => WidgetKind::Histo,
            "spark" => WidgetKind::Spark,
            "chart" => WidgetKind::Chart,
            "table" => WidgetKind::Table,
            "tabs" => WidgetKind::Tabs,
            "block" => WidgetKind::Block,
            "frame" => WidgetKind::Frame,
            "linegauge" => WidgetKind::LineGauge,
            "scatter" => WidgetKind::Scatter,
            "sparkline" => WidgetKind::Sparkline,
            "map" => WidgetKind::Map,
            "calendar" => WidgetKind::Calendar,
            "logview" => WidgetKind::LogView,
            "heatmap" => WidgetKind::Heatmap,
            "treemap" => WidgetKind::Treemap,
            "gantt" => WidgetKind::Gantt,
            "diff" => WidgetKind::Diff,
            "logo" => WidgetKind::Logo,
            "clear" | "blank" | "spacer" => WidgetKind::Blank,
            "rule" | "divider" => WidgetKind::Rule,
            "sel" => WidgetKind::Sel,
            "input" => WidgetKind::Input,
            "select" => WidgetKind::Select,
            "filter" => WidgetKind::Filter,
            "facet" => WidgetKind::Facet,
            "slider" => WidgetKind::Slider,
            "check" => WidgetKind::Check,
            _ => return None,
        })
    }

    pub fn label(&self) -> &'static str {
        match self {
            WidgetKind::Text => "text",
            WidgetKind::Tail => "tail",
            WidgetKind::List => "list",
            WidgetKind::Gauge => "gauge",
            WidgetKind::Bars => "bars",
            WidgetKind::Histo => "histo",
            WidgetKind::Spark => "spark",
            WidgetKind::Chart => "chart",
            WidgetKind::Table => "table",
            WidgetKind::Tabs => "tabs",
            WidgetKind::Block => "block",
            WidgetKind::Frame => "frame",
            WidgetKind::LineGauge => "linegauge",
            WidgetKind::Scatter => "scatter",
            WidgetKind::Sparkline => "sparkline",
            WidgetKind::Map => "map",
            WidgetKind::Calendar => "calendar",
            WidgetKind::LogView => "logview",
            WidgetKind::Heatmap => "heatmap",
            WidgetKind::Treemap => "treemap",
            WidgetKind::Gantt => "gantt",
            WidgetKind::Diff => "diff",
            WidgetKind::Logo => "logo",
            WidgetKind::Blank => "clear",
            WidgetKind::Rule => "rule",
            WidgetKind::Sel => "sel",
            WidgetKind::Input => "input",
            WidgetKind::Select => "select",
            WidgetKind::Filter => "filter",
            WidgetKind::Facet => "facet",
            WidgetKind::Slider => "slider",
            WidgetKind::Check => "check",
        }
    }

    /// Whether this kind is an interactive control (value lives in the input
    /// registry and drives `apply`/`where … .name`), not a stream view.
    pub fn is_control(&self) -> bool {
        matches!(
            self,
            WidgetKind::Input
                | WidgetKind::Filter
                | WidgetKind::Facet
                | WidgetKind::Slider
                | WidgetKind::Check
                | WidgetKind::Sel
        )
    }
}

/// A data source: reads stdin, then applies a query pipeline.
#[derive(Debug, Clone)]
pub struct Source {
    pub pipeline: Vec<QueryOp>,
}

#[derive(Debug, Clone)]
pub struct Widget {
    pub path: String,
    pub kind: WidgetKind,
    pub opts: BTreeMap<String, String>,
    pub source: Option<Source>,
    /// Optional search-key pipeline (`search .name { … }`), for a `select`
    /// widget: the fuzzy match runs against this derived key while the row still
    /// shows/emits the `source` display. fzf `--nth`, but pipeline-general (search
    /// a column, a lowercased key, an extracted field). `None` = search display.
    pub search: Option<Vec<QueryOp>>,
    /// Grid cell `(row, col)` set by a `grid` command; `None` = auto-stacked.
    pub grid: Option<(usize, usize)>,
    /// Grid span `(rows, cols)` from `grid -rowspan`/`-colspan` (`-span` = colspan);
    /// `(1, 1)` = a single cell. Lets a chart span multiple cells while gauges take one.
    pub span: (usize, usize),
}

/// A key binding: a control key that triggers a [`BindAction`] in the TUI.
/// Declared `bind C-<letter> <action>` — the arb-native way to drive the spec's
/// own state from the keyboard (set a control, quit), foundation for reactions.
#[derive(Debug, Clone)]
pub struct Bind {
    /// The raw control byte (e.g. Ctrl-U = 0x15).
    pub key: u8,
    pub action: BindAction,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BindAction {
    /// Set an `input .name` widget's value — with `out { … apply .name }` this
    /// reshapes the live pipe on a keystroke (a keyboard-driven megafilter/map).
    SetInput { name: String, value: String },
    /// Quit the TUI.
    Quit,
    /// Ring the terminal bell (write 0x07 after the next draw).
    Beep,
    /// Flash a message in the status bar for a few seconds.
    Alert(String),
    /// Tint a widget's border/accent for a few seconds. `widget` is the path
    /// without the leading dot; `color` is a color name (green/red/…).
    Flash { widget: String, color: String },
    /// Run a shell command, fire-and-forget (never waits, never blocks the loop).
    Exec(String),
    /// Write text to a `spawn -pty` child's stdin — the Expect `send`. No-op
    /// unless the stream source is a PTY. Include `\n` to submit a line.
    Send(String),
    /// `tell REF MSG(args)` — post a message to a session actor/pool, fire-and-
    /// forget (SPEC §15). `call` is the raw `MSG(args)` text, parsed + evaluated
    /// (with live control substitution) when the action fires.
    ActorTell { refname: String, call: String },
    /// `ask .CTRL REF MSG(args)` — ask a session actor/pool and store the reply
    /// into control `ctrl` (so a widget bound to it shows the result).
    ActorAsk {
        ctrl: String,
        refname: String,
        call: String,
    },
    /// Run several actions in order (block form `{ alert "x"; beep }`).
    Seq(Vec<BindAction>),
}

/// A mouse trigger for a `bind <…> ACTION` (Tk-style events). Extensible; only
/// `Click` (any button press) ships today.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseTrigger {
    Click,
}

/// Parse a key spec to its raw byte. Accepts control-key forms (`C-u`, `c-u`,
/// `^u`) and the Tk named keys `<Enter>`/`<Esc>`/`<Tab>` and `<Key-X>` (a single
/// letter). Only these forms bind, so a bind never shadows plain filter typing.
pub fn parse_key(spec: &str) -> Option<u8> {
    match spec {
        "<Enter>" | "<Return>" => return Some(0x0d),
        "<Esc>" | "<Escape>" => return Some(0x1b),
        "<Tab>" => return Some(0x09),
        _ => {}
    }
    // `<Key-x>` -> the literal letter byte.
    if let Some(inner) = spec.strip_prefix("<Key-").and_then(|s| s.strip_suffix('>')) {
        let ch = inner.chars().next()?;
        if inner.chars().count() == 1 && ch.is_ascii_alphabetic() {
            return Some(ch as u8);
        }
        return None;
    }
    let letter = spec
        .strip_prefix("C-")
        .or_else(|| spec.strip_prefix("c-"))
        .or_else(|| spec.strip_prefix('^'))?;
    let ch = letter.chars().next()?;
    if letter.chars().count() != 1 || !ch.is_ascii_alphabetic() {
        return None;
    }
    Some((ch.to_ascii_uppercase() as u8) & 0x1f)
}

/// Parse a `Ns`/`Nms`/`Nm` duration literal (SPEC §3) into a `Duration`.
/// `ms` is matched before the bare `s` so `500ms` is not read as `500` seconds.
pub fn parse_duration(s: &str) -> Option<Duration> {
    let s = s.trim();
    if let Some(n) = s.strip_suffix("ms") {
        return n.trim().parse::<u64>().ok().map(Duration::from_millis);
    }
    if let Some(n) = s.strip_suffix('s') {
        return n.trim().parse::<f64>().ok().map(Duration::from_secs_f64);
    }
    if let Some(n) = s.strip_suffix('m') {
        return n
            .trim()
            .parse::<f64>()
            .ok()
            .map(|m| Duration::from_secs_f64(m * 60.0));
    }
    None
}

/// An event-driven reaction: when a stream line matches `pattern`, fire `action`.
/// Declared `expect /regex/ <action>` — the "react" half of Expect. Reuses
/// [`BindAction`], so a matching line can set a control or quit.
#[derive(Debug, Clone)]
pub struct Expect {
    pub pattern: Regex,
    pub action: BindAction,
}

/// An idle reaction (SPEC §13): when the input stream produces no new line for
/// `dur`, fire `action`. Latched once per idle span, re-armed on the next line.
/// Reuses [`BindAction`] exactly like [`Expect`], so `timeout 5s quit` works.
#[derive(Debug, Clone)]
pub struct Timeout {
    pub dur: Duration,
    pub action: BindAction,
}

/// Parse an action clause (`set .name VALUE…` | `quit`) shared by `bind` and
/// `expect`. `params` is the args AFTER the action verb.
fn parse_action(verb: &str, params: &[Arg]) -> Result<BindAction, String> {
    // The space-joined string params (used by alert/exec/set values).
    let joined = || {
        params
            .iter()
            .filter_map(Arg::as_str)
            .collect::<Vec<_>>()
            .join(" ")
    };
    match verb {
        "quit" => Ok(BindAction::Quit),
        "beep" => Ok(BindAction::Beep),
        "alert" => Ok(BindAction::Alert(joined())),
        "exec" => {
            let cmd = joined();
            if cmd.is_empty() {
                return Err("exec: missing command".into());
            }
            Ok(BindAction::Exec(cmd))
        }
        "send" => {
            let text = joined();
            if text.is_empty() {
                return Err("send: missing text".into());
            }
            // The lexer already turns `\n`/`\t` in a quoted string into the real
            // char, and (like Expect) `send` never auto-appends — so `send "y\n"`
            // submits a line, `send "y"` leaves the cursor on the same line.
            Ok(BindAction::Send(text))
        }
        "flash" => {
            let widget = params
                .first()
                .and_then(Arg::as_str)
                .ok_or("flash: missing widget (.name)")?;
            let widget = widget.strip_prefix('.').unwrap_or(widget).to_string();
            let color = params
                .get(1)
                .and_then(Arg::as_str)
                .unwrap_or("yellow")
                .to_string();
            Ok(BindAction::Flash { widget, color })
        }
        "set" => {
            let name = params
                .first()
                .and_then(Arg::as_str)
                .ok_or("set: missing input name (.name)")?;
            let name = name.strip_prefix('.').unwrap_or(name).to_string();
            let value = params[1..]
                .iter()
                .filter_map(Arg::as_str)
                .collect::<Vec<_>>()
                .join(" ");
            Ok(BindAction::SetInput { name, value })
        }
        "tell" => {
            // `tell REF MSG(args)` — the message tell of the actor system (§15).
            // `send` stays the Expect PTY action; `tell` avoids the collision.
            let refname = params
                .first()
                .and_then(Arg::as_str)
                .ok_or("tell: expected `tell REF MSG(args)`")?
                .to_string();
            let call = params[1..]
                .iter()
                .filter_map(Arg::as_str)
                .collect::<Vec<_>>()
                .join(" ");
            if call.trim().is_empty() {
                return Err("tell: missing message (`tell REF MSG(args)`)".into());
            }
            // Validate the call shape now so a typo is a build error, not silent.
            crate::actor::parse_call(&call)?;
            Ok(BindAction::ActorTell { refname, call })
        }
        "ask" => {
            // `ask .CTRL REF MSG(args)` — ask a ref, store the reply into control CTRL.
            let ctrl = params
                .first()
                .and_then(Arg::as_str)
                .ok_or("ask: expected `ask .CTRL REF MSG(args)`")?;
            let ctrl = ctrl.strip_prefix('.').unwrap_or(ctrl).to_string();
            let refname = params
                .get(1)
                .and_then(Arg::as_str)
                .ok_or("ask: missing ref (`ask .CTRL REF MSG(args)`)")?
                .to_string();
            let call = params[2..]
                .iter()
                .filter_map(Arg::as_str)
                .collect::<Vec<_>>()
                .join(" ");
            if call.trim().is_empty() {
                return Err("ask: missing message (`ask .CTRL REF MSG(args)`)".into());
            }
            crate::actor::parse_call(&call)?;
            Ok(BindAction::ActorAsk {
                ctrl,
                refname,
                call,
            })
        }
        other => Err(format!(
            "unknown action `{other}` (set | quit | beep | alert | flash | exec | tell | ask)"
        )),
    }
}

/// Parse a `spawn NAME = ACTOR(init)` or `pool NAME = ACTOR * N` binding into a
/// [`crate::actor::RefDecl`]. `verb` is `spawn`/`pool`; the actor must already be
/// declared. Both forms share `NAME = RHS`; a `pool` (or `RHS` with `* N`) sets
/// the pool width.
fn parse_actor_ref(
    verb: &str,
    args: &[Arg],
    actors: &BTreeMap<String, Arc<ActorDef>>,
) -> Result<crate::actor::RefDecl, String> {
    let name = args
        .first()
        .and_then(Arg::as_str)
        .ok_or_else(|| format!("{verb}: expected `{verb} NAME = ACTOR…`"))?
        .to_string();
    if args.get(1).and_then(Arg::as_str) != Some("=") {
        return Err(format!("{verb}: expected `=` (`{verb} NAME = ACTOR…`)"));
    }
    // RHS: `ACTOR(init)` and/or `* N`, joined so spaces don't matter.
    let rhs = args[2..]
        .iter()
        .filter_map(Arg::as_str)
        .collect::<Vec<_>>()
        .join(" ");
    if rhs.trim().is_empty() {
        return Err(format!("{verb}: missing actor (`{verb} {name} = ACTOR…`)"));
    }
    // Split off a `* N` pool width (from the verb or the RHS).
    let (head, pool) = match rhs.split_once('*') {
        Some((h, n)) => {
            let n = n
                .trim()
                .parse::<usize>()
                .map_err(|_| format!("{verb}: `* {}` is not a pool size", n.trim()))?;
            (h.trim().to_string(), Some(n.min(1024)))
        }
        None => (rhs.trim().to_string(), None),
    };
    // `pool NAME = ACTOR` (no explicit `* N`) still means a pool — default width
    // is filled in at spawn time (one per hardware thread) via `pool: Some(0)`.
    let pool = match (verb, pool) {
        (_, Some(n)) => Some(n),
        ("pool", None) => Some(0),
        _ => None,
    };
    // `head` is `ACTOR(init)` — reuse the actor-call splitter for name + init.
    let (actor, init_exprs) = crate::actor::parse_call(&head)?;
    if !actors.contains_key(&actor) {
        return Err(format!(
            "{verb}: no actor named `{actor}` in scope (declare `actor {actor}(state) {{ … }}` first)"
        ));
    }
    // Initial state is a constant expression evaluated now (`worker(3)` -> 3).
    let init = match init_exprs.as_slice() {
        [] => 0.0,
        [e] => crate::expr::eval(e, 0.0).unwrap_or(0.0),
        _ => return Err(format!("{verb}: `{actor}(…)` takes a single init value")),
    };
    Ok(crate::actor::RefDecl {
        name,
        actor,
        init,
        pool,
        restart: true,
    })
}

/// Apply a `supervise NAME { on crash { restart | stop } }` policy to an already-
/// declared ref: `stop` turns off respawn (fail-stop), `restart` (the default)
/// leaves it on.
fn apply_supervise(args: &[Arg], refs: &mut [crate::actor::RefDecl]) -> Result<(), String> {
    let name = args
        .first()
        .and_then(Arg::as_str)
        .ok_or("supervise: expected `supervise NAME { on crash { restart | stop } }`")?;
    let body = match args.get(1) {
        Some(Arg::Block(b)) => b,
        _ => return Err("supervise: expected `{ on crash { restart | stop } }`".into()),
    };
    let decl = refs
        .iter_mut()
        .find(|r| r.name == name)
        .ok_or_else(|| format!("supervise: no ref named `{name}` (spawn/pool it first)"))?;
    for clause in body {
        if clause.name != "on" || clause.args.first().and_then(Arg::as_str) != Some("crash") {
            return Err("supervise: only `on crash { … }` is supported".into());
        }
        let policy = match clause.args.get(1) {
            Some(Arg::Block(b)) => b
                .first()
                .map(|c| c.name.as_str())
                .ok_or("supervise: `on crash { }` needs `restart` or `stop`")?,
            _ => return Err("supervise: `on crash` needs a `{ restart | stop }` body".into()),
        };
        match policy {
            "restart" => decl.restart = true,
            "stop" => decl.restart = false,
            other => {
                return Err(format!(
                    "supervise: unknown crash policy `{other}` (restart | stop)"
                ))
            }
        }
    }
    Ok(())
}

/// Parse a block-form action body (`{ alert "x"; beep; flash .w red }`) into a
/// `Seq` — each top-level command is one action, run in order.
fn parse_action_block(cmds: &[Command]) -> Result<BindAction, String> {
    let actions = cmds
        .iter()
        .map(|c| parse_action(&c.name, &c.args))
        .collect::<Result<Vec<_>, _>>()?;
    Ok(BindAction::Seq(actions))
}

/// Parse the action clause of a `bind`/`expect`: either a `{ … }` block (→ Seq)
/// or the single-line `verb params…` form. `rest` is the args after the key/regex.
fn parse_bind_or_expect_action(rest: &[Arg]) -> Result<BindAction, String> {
    match rest.first() {
        Some(Arg::Block(cmds)) => parse_action_block(cmds),
        Some(_) => {
            let verb = rest[0].as_str().unwrap_or("");
            parse_action(verb, &rest[1..])
        }
        None => Err("missing action (set | quit | beep | alert | flash | exec | { … })".into()),
    }
}

#[derive(Debug, Default)]
pub struct Spec {
    pub widgets: Vec<Widget>,
    /// Downstream output pipeline (`out { … }`): applied to the stream and
    /// written to stdout, so arb can *modify* a pipe, not just visualize it.
    pub out: Option<Vec<QueryOp>>,
    /// Key bindings (`bind C-<letter> <action>`).
    pub binds: Vec<Bind>,
    /// Event-driven reactions (`expect /re/ <action>`).
    pub expects: Vec<Expect>,
    /// Idle reactions (`timeout Ns <action>`).
    pub timeouts: Vec<Timeout>,
    /// Mouse reactions (`bind <Click> <action>`).
    pub mouse_binds: Vec<(MouseTrigger, BindAction)>,
    /// Terminal-resize reactions (`bind <Resize> <action>`).
    pub resize_binds: Vec<BindAction>,
    /// Input-source command (`spawn CMD` / `spawn { CMD }`, SPEC §7): arb
    /// launches CMD via `sh -c` and feeds its stdout into the stream in place of
    /// stdin (fire-and-forget; child detached, dies with arb). CLI `--run` wins
    /// if both are given. The interactive `send`/PTY react leg + `.ps.sel`
    /// selection widget are deferred. `None` = read stdin.
    pub spawn: Option<String>,
    /// Input-source file (`< FILE`, SPEC §7): read FILE as the stream in place
    /// of stdin. Folded into the producer as `cat -- FILE` in main. Mutually
    /// exclusive with `spawn` (and `--run`). `None` = read stdin.
    pub source_file: Option<String>,
    /// Poll source (`! CMD every Ns`, SPEC §7): re-run CMD via `sh -c` every
    /// interval, feeding each run's stdout into the stream. The interactive/serve
    /// loop runs in a background thread; the headless path runs CMD once (a
    /// reducer over an endless source can't terminate). `None` = read stdin.
    pub poll: Option<(String, Duration)>,
    /// In-language unit tests (`test "NAME" { given …; run { … }; want … }`):
    /// feed sample lines through a query pipeline and assert the output. Run
    /// headlessly by `arb --test`; ignored by every other mode.
    pub tests: Vec<TestCase>,
    /// `spawn -pty CMD`: run the spawn command on a pseudo-terminal (so it acts
    /// interactive) and keep a writer to its stdin for the `send` action. Only
    /// meaningful with `spawn` set and in the interactive TUI.
    pub spawn_pty: bool,
    /// `actor NAME(state) { on MSG { … } }` declarations, by name. A `via NAME`
    /// pipeline op resolves against this registry at build time (SPEC §15).
    pub actors: BTreeMap<String, Arc<ActorDef>>,
    /// `spawn NAME = ACTOR(init)` / `pool NAME = ACTOR * N` session bindings, in
    /// declaration order. The TUI spawns these once at startup; `tell`/`ask` bind
    /// actions drive them (SPEC §15).
    pub actor_refs: Vec<crate::actor::RefDecl>,
    /// `rows "1 2 1"` — the grid's row track sizes (`None` = uniform). A track is
    /// `N` (fixed cells), `N%` (percentage), or `N*`/`*` (weight, proportional).
    pub row_tracks: Option<Vec<Track>>,
    /// `cols "20 * 2*"` — the grid's column track sizes (`None` = uniform).
    pub col_tracks: Option<Vec<Track>>,
    /// `gap N` — blank cells between grid rows/columns (default 0).
    pub gap: u16,
    /// `layout horizontal|vertical` — the no-grid auto-tile direction (default
    /// vertical). Ignored once any widget declares a grid cell.
    pub flow: Flow,
    /// `theme NAME` / `theme custom c1..c6` — the active color palette (one of the
    /// 31 built-ins or a custom 6-index palette). `None` = no directive: `main`
    /// resolves the default (`--theme` → `~/.arb` config → baked `neon-sprawl`).
    pub theme: Option<crate::theme::Palette>,
    /// `theme off`/`none` — opt out of theming to the classic cyan scheme; stops
    /// `main` from applying the config/baked default.
    pub theme_off: bool,
}

/// A layout track size (a grid row/column). Maps to a ratatui `Constraint`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Track {
    /// `N` — a fixed cell count (`Constraint::Length`).
    Length(u16),
    /// `N%` — a percentage of the axis (`Constraint::Percentage`).
    Percentage(u16),
    /// `N*` / `*` — a proportional weight; remaining space splits by weight
    /// (`Constraint::Fill`). Bare `*` is weight 1.
    Fill(u16),
}

/// The auto-tile direction when no widget declares a grid cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Flow {
    #[default]
    Vertical,
    Horizontal,
}

/// Parse a track spec (`"1 2 1"` / `"20c * 2*"`) into a track list. A **bare
/// integer is a proportional weight** (`1 2 1` = a 1:2:1 split — the common case);
/// `N*` / `*` is the same explicit weight; `N%` is a percentage of the axis; and
/// `Nc` is a fixed cell count. Empty/invalid tokens are an error.
pub fn parse_tracks(spec: &str) -> Result<Vec<Track>, String> {
    let mut out = Vec::new();
    for tok in spec.split_whitespace() {
        let track = if let Some(pct) = tok.strip_suffix('%') {
            Track::Percentage(
                pct.parse::<u16>()
                    .map_err(|_| format!("track: bad percentage `{tok}`"))?
                    .min(100),
            )
        } else if let Some(cells) = tok.strip_suffix('c') {
            Track::Length(
                cells
                    .parse::<u16>()
                    .map_err(|_| format!("track: bad cell count `{tok}`"))?,
            )
        } else {
            // Bare `N`, `N*`, or `*` — a proportional weight (`*` = 1).
            let w = tok.strip_suffix('*').unwrap_or(tok);
            let weight = if w.is_empty() {
                1
            } else {
                w.parse::<u16>()
                    .map_err(|_| format!("track: bad weight `{tok}` (use N, N%, N*, or Nc)"))?
                    .max(1)
            };
            Track::Fill(weight)
        };
        out.push(track);
    }
    if out.is_empty() {
        return Err("track spec is empty".into());
    }
    Ok(out)
}

/// One in-language test case: feed `given` lines through the `run` pipeline
/// (`ops`) and assert the flattened output equals `want`. Purely headless —
/// evaluated via [`crate::query::eval`], the same path the widgets use.
#[derive(Debug, Clone)]
pub struct TestCase {
    pub name: String,
    pub given: Vec<String>,
    pub ops: Vec<QueryOp>,
    pub want: Vec<String>,
}

/// True if any single-stream input source (`spawn`/`< file`/`! poll`) is already
/// set — only one may feed the stream.
fn stream_source_set(s: &Spec) -> bool {
    s.spawn.is_some() || s.source_file.is_some() || s.poll.is_some()
}

/// Build a `Spec` from a parsed command tree.
pub fn build(cmds: &[Command]) -> Result<Spec, crate::err::SpecError> {
    let mut spec = Spec::default();
    build_into(&mut spec, cmds, 0)?;
    Ok(spec)
}

/// Resolve `apply .name` placeholders against live `input` widget values: each
/// `Apply(name)` is replaced by the query pipeline parsed from that input's
/// current text (empty/invalid → dropped). Called every render frame so a
/// before/after transform pane updates as the user edits the input.
pub fn resolve_pipeline(
    ops: &[QueryOp],
    inputs: &std::collections::HashMap<String, String>,
) -> Vec<QueryOp> {
    // Resolve a control name to its live numeric value (empty/non-numeric -> None)
    // or its raw string value (for `match`/`in .set` string predicates).
    let num = |n: &str| -> Option<f64> { inputs.get(n).and_then(|v| v.trim().parse::<f64>().ok()) };
    let strv = |n: &str| -> Option<String> { inputs.get(n).cloned() };
    let mut out = Vec::with_capacity(ops.len());
    for op in ops {
        match op {
            QueryOp::Apply(name) => {
                if let Some(val) = inputs.get(name).filter(|v| !v.trim().is_empty()) {
                    // Parse the input text as a pipeline body (prefix `in;` so it
                    // is a valid source body) and splice its ops in.
                    // A live `apply` input is typed at render time, before any
                    // actor is in scope — `via` there resolves against an empty
                    // registry (unknown-actor errors just drop the transform).
                    if let Ok(cmds) = crate::parser::parse(&format!("in; {val}")) {
                        if let Ok(sub) = pipeline_from_body(&cmds, &BTreeMap::new()) {
                            out.extend(sub);
                        }
                    }
                }
            }
            // `where lat < .th` (numeric) / `where match(.q)` / `where lvl in .lv`
            // (string). Numeric controls must all resolve or the filter is dropped
            // (unset threshold = no filter); string controls with an empty value
            // simply match everything, so they never force a drop.
            QueryOp::Where(e) => {
                let (mut nums, mut strs) = (Vec::new(), Vec::new());
                crate::expr::control_names_typed(e, &mut nums, &mut strs);
                if nums.is_empty() && strs.is_empty() {
                    out.push(op.clone());
                } else if nums.iter().all(|n| num(n).is_some()) {
                    out.push(QueryOp::Where(crate::expr::substitute_controls(
                        e, &num, &strv,
                    )));
                }
                // else: a numeric control is unset -> drop this `where`.
            }
            // `map(x * .k)`: substitute resolvable controls; an unresolved one
            // stays a control (-> NaN) rather than dropping the transform.
            QueryOp::Map(e) => {
                out.push(QueryOp::Map(crate::expr::substitute_controls(
                    e, &num, &strv,
                )));
            }
            other => out.push(other.clone()),
        }
    }
    out
}

// ---- `import X as Y` namespacing ------------------------------------------
// A module built into a fresh sub-Spec has its render-time NAME references
// (widget paths, `apply`, control refs, `set`/`flash` targets) prefixed with the
// alias, then merged in. Intra-module by-path refs (source/search/grid/configure)
// already resolved during the fresh build, so only these string names remain.

/// Namespace a control/input name: `cpu` -> `g.cpu`.
fn prefix_name(name: &str, ns: &str) -> String {
    format!("{ns}.{name}")
}

/// Namespace `apply`/`where`/`map`/`calc` references in a query pipeline.
fn prefix_pipeline(ops: &mut [QueryOp], ns: &str) {
    for op in ops {
        match op {
            QueryOp::Apply(n) => *n = prefix_name(n, ns),
            QueryOp::Where(e) | QueryOp::Map(e) | QueryOp::Calc(e) => {
                crate::expr::prefix_controls(e, ns)
            }
            _ => {}
        }
    }
}

/// Namespace the widget/control names an action targets.
fn prefix_action(a: &mut BindAction, ns: &str) {
    match a {
        BindAction::SetInput { name, .. } => *name = prefix_name(name, ns),
        BindAction::Flash { widget, .. } => *widget = prefix_name(widget, ns),
        // A module's `tell`/`ask` targets its own (now-namespaced) ref; `ask` also
        // writes a namespaced control.
        BindAction::ActorTell { refname, .. } => *refname = prefix_name(refname, ns),
        BindAction::ActorAsk { ctrl, refname, .. } => {
            *ctrl = prefix_name(ctrl, ns);
            *refname = prefix_name(refname, ns);
        }
        BindAction::Seq(v) => v.iter_mut().for_each(|x| prefix_action(x, ns)),
        _ => {}
    }
}

/// Prefix every render-time name in a freshly-built module Spec with `ns`.
fn prefix_spec(sub: &mut Spec, ns: &str) {
    for w in &mut sub.widgets {
        w.path = format!(".{ns}.{}", w.path.trim_start_matches('.'));
        if let Some(s) = &mut w.source {
            prefix_pipeline(&mut s.pipeline, ns);
        }
        if let Some(p) = &mut w.search {
            prefix_pipeline(p, ns);
        }
    }
    for b in &mut sub.binds {
        prefix_action(&mut b.action, ns);
    }
    for e in &mut sub.expects {
        prefix_action(&mut e.action, ns);
    }
    for t in &mut sub.timeouts {
        prefix_action(&mut t.action, ns);
    }
    for (_, a) in &mut sub.mouse_binds {
        prefix_action(a, ns);
    }
    for a in &mut sub.resize_binds {
        prefix_action(a, ns);
    }
    if let Some(out) = &mut sub.out {
        prefix_pipeline(out, ns);
    }
    // Session refs: namespace the binding name and the actor it runs, so `.ns.w`
    // is distinct and its (also-prefixed) actor resolves after merge.
    for r in &mut sub.actor_refs {
        r.name = prefix_name(&r.name, ns);
        r.actor = prefix_name(&r.actor, ns);
    }
}

/// Merge a namespaced module Spec into `dst`.
fn merge_spec(dst: &mut Spec, src: Spec, ns: &str) -> Result<(), String> {
    dst.widgets.extend(src.widgets);
    dst.binds.extend(src.binds);
    dst.expects.extend(src.expects);
    dst.timeouts.extend(src.timeouts);
    dst.mouse_binds.extend(src.mouse_binds);
    dst.resize_binds.extend(src.resize_binds);
    dst.tests.extend(src.tests);
    // A namespaced module's `via` ops already embed their resolved `Arc<ActorDef>`
    // (bound during the fresh sub-build), so they work post-merge. Carry the defs
    // under `ns.NAME` keys so they don't collide with the host's actors.
    for (name, def) in src.actors {
        dst.actors.insert(prefix_name(&name, ns), def);
    }
    // Session refs already namespaced by `prefix_spec`; carry them over.
    dst.actor_refs.extend(src.actor_refs);
    // A module's `theme` applies only when the host hasn't set one (host wins).
    if dst.theme.is_none() {
        dst.theme = src.theme;
    }
    if let Some(out) = src.out {
        if dst.out.is_some() {
            return Err(format!(
                "import: `{ns}` defines `out`, but one is already set"
            ));
        }
        dst.out = Some(out);
    }
    if let Some(sp) = src.spawn {
        if stream_source_set(dst) {
            return Err(format!(
                "import: `{ns}` defines a spawn source, but one is already set"
            ));
        }
        dst.spawn = Some(sp);
        dst.spawn_pty = src.spawn_pty;
    }
    if let Some(f) = src.source_file {
        if stream_source_set(dst) {
            return Err(format!(
                "import: `{ns}` defines a `<` file source, but one is already set"
            ));
        }
        dst.source_file = Some(f);
    }
    if let Some(p) = src.poll {
        if stream_source_set(dst) {
            return Err(format!(
                "import: `{ns}` defines a `!` poll source, but one is already set"
            ));
        }
        dst.poll = Some(p);
    }
    Ok(())
}

/// Process `cmds` into `spec`. `import NAME` resolves and inlines a module
/// (stdlib preset or user file); `depth` guards against import cycles.
fn build_into(
    spec: &mut Spec,
    cmds: &[Command],
    depth: usize,
) -> Result<(), crate::err::SpecError> {
    if depth > 16 {
        return Err("import: module nesting too deep (cycle?)".into());
    }
    for c in cmds {
        // Process one command; a returned error with no span yet is anchored to
        // this command's verb (its char offset) so the LSP points at the line.
        let res: Result<(), crate::err::SpecError> = (|| -> Result<(), crate::err::SpecError> {
            if c.name == "import" {
                let name = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or("import: missing module name")?;
                // `import X as Y`: build the module into a fresh sub-Spec (so its
                // intra-module by-path refs resolve), namespace every render-time
                // name with `Y`, then merge — so `.Y.foo` and its controls resolve.
                if c.args.get(1).and_then(Arg::as_str) == Some("as") {
                    let alias = c
                        .args
                        .get(2)
                        .and_then(Arg::as_str)
                        .ok_or("import: `as` requires an alias (import X as Y)")?;
                    if alias.is_empty() || alias.contains(['.', '/', ' ']) {
                        return Err(format!("import: invalid namespace alias `{alias}`").into());
                    }
                    let src = resolve_module(name)?;
                    let sub_cmds = crate::parser::parse(&src)?;
                    let mut sub = Spec::default();
                    build_into(&mut sub, &sub_cmds, depth + 1)?;
                    prefix_spec(&mut sub, alias);
                    merge_spec(spec, sub, alias)?;
                } else {
                    let src = resolve_module(name)?;
                    let sub = crate::parser::parse(&src)?;
                    build_into(spec, &sub, depth + 1)?;
                }
            } else if c.name == "actor" {
                // `actor NAME(state) { on MSG(p) { … } }` — a message-handling
                // behavior (SPEC §15). Stored by name; a `via NAME` pipeline op
                // fans the stream across a pool of it.
                let def = crate::actor::parse_actor(&c.args)?;
                spec.actors.insert(def.name.clone(), Arc::new(def));
            } else if c.name == "__rust_compile" {
                // Desugared `rust { ... }` block (see `rust_ffi`): compile the
                // base64 body to a cached cdylib and register its exports, so a
                // later `name(args)` call in a where/map/calc expression resolves.
                // Runs at build time, before any render-time expression eval.
                let b64 = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or("__rust_compile: missing block body")?;
                fusevm::ffi::compile_and_register(b64).map_err(crate::err::SpecError::from)?;
            } else if let Some(kind) = WidgetKind::from(&c.name) {
                let path = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or_else(|| format!("{}: missing widget path", c.name))?;
                if !path.starts_with('.') {
                    return Err(format!(
                        "{}: widget path must start with '.', got `{path}`",
                        c.name
                    )
                    .into());
                }
                spec.widgets.push(Widget {
                    path: path.to_string(),
                    kind,
                    opts: parse_opts(&c.args[1..]),
                    source: None,
                    search: None,
                    grid: None,
                    span: (1, 1),
                });
            } else if c.name == "source" {
                let path = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or("source: missing path")?;
                let body = match c.args.get(1) {
                    Some(Arg::Block(b)) => b,
                    _ => return Err("source: expected `{ body }`".into()),
                };
                let pipeline = pipeline_from_body(body, &spec.actors)?;
                set_source(spec, path, Source { pipeline })?;
            } else if c.name == "search" {
                // `search .name { in; … }` — a select widget's fuzzy-match key
                // pipeline (fzf --nth). The row still shows/emits its `source`.
                let path = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or("search: missing path")?;
                let body = match c.args.get(1) {
                    Some(Arg::Block(b)) => b,
                    _ => return Err("search: expected `{ body }`".into()),
                };
                let pipeline = pipeline_from_body(body, &spec.actors)?;
                set_search(spec, path, pipeline)?;
            } else if c.name == "bind" {
                // `bind KEY ACTION` — KEY is a control key (`C-<letter>`, `<Enter>`…),
                // a mouse event (`<Click>`), or `<Resize>`; ACTION is a single verb or
                // a `{ … }` block.
                let keyspec = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or("bind: missing key (e.g. C-u, <Click>)")?;
                let action =
                    parse_bind_or_expect_action(&c.args[1..]).map_err(|e| format!("bind: {e}"))?;
                match keyspec {
                    "<Click>" | "<Button-1>" => {
                        spec.mouse_binds.push((MouseTrigger::Click, action))
                    }
                    "<Resize>" | "<Configure>" => spec.resize_binds.push(action),
                    _ => {
                        let key = parse_key(keyspec).ok_or_else(|| {
                        format!("bind: `{keyspec}` is not a bindable key (use C-<letter>, <Enter>/<Esc>/<Tab>/<Key-x>, <Click>, <Resize>)")
                    })?;
                        spec.binds.push(Bind { key, action });
                    }
                }
            } else if c.name == "expect" {
                match c.args.first() {
                    // Block form `expect { /re/ ACTION; /re2/ ACTION }` (Tcl Expect's
                    // multi-pattern block): each inner command is one clause — its
                    // NAME is the /regex/, its args are the ACTION. Emit one Expect
                    // per clause; all fire live per line (tui.rs loops every entry).
                    Some(Arg::Block(clauses)) => {
                        for clause in clauses {
                            let pattern =
                                compile_regex(&clause.name).map_err(|e| format!("expect: {e}"))?;
                            let action = parse_bind_or_expect_action(&clause.args)
                                .map_err(|e| format!("expect: {e}"))?;
                            spec.expects.push(Expect { pattern, action });
                        }
                    }
                    // Single-clause form `expect /regex/ ACTION` — ACTION as for `bind`.
                    _ => {
                        let pattern = regex_arg(c)?;
                        let action = parse_bind_or_expect_action(&c.args[1..])
                            .map_err(|e| format!("expect: {e}"))?;
                        spec.expects.push(Expect { pattern, action });
                    }
                }
            } else if c.name == "timeout" {
                // `timeout Ns ACTION` — fire ACTION when the stream goes idle for Ns.
                let dspec = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or("timeout: missing duration (e.g. 5s, 500ms)")?;
                let dur = parse_duration(dspec).ok_or_else(|| {
                    format!("timeout: `{dspec}` is not a duration (use Ns/Nms/Nm)")
                })?;
                let action = parse_bind_or_expect_action(&c.args[1..])
                    .map_err(|e| format!("timeout: {e}"))?;
                spec.timeouts.push(Timeout { dur, action });
            } else if c.name == "out" {
                let body = match c.args.first() {
                    Some(Arg::Block(b)) => b,
                    _ => return Err("out: expected `{ body }`".into()),
                };
                let pipeline = pipeline_from_body(body, &spec.actors)?;
                spec.out = Some(pipeline);
            } else if c.name == "test" {
                // `test "NAME" { given …; run { in; … }; want … }` — an
                // in-language unit test, run headlessly by `arb --test`.
                let name = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or("test: expected a name — `test \"NAME\" { … }`")?
                    .to_string();
                let body = match c.args.get(1) {
                    Some(Arg::Block(b)) => b,
                    _ => return Err("test: expected `{ given …; run { … }; want … }`".into()),
                };
                let tc = parse_test_case(name, body, &spec.actors)?;
                spec.tests.push(tc);
            } else if c.name == "spawn" && c.args.get(1).and_then(Arg::as_str) == Some("=") {
                // `spawn NAME = ACTOR(init)` — a session actor binding (§15),
                // distinct from the `spawn CMD` process source (disambiguated by
                // the `=` second token). `tell`/`ask` drive it.
                let decl = parse_actor_ref(&c.name, &c.args, &spec.actors)?;
                spec.actor_refs.push(decl);
            } else if c.name == "pool" {
                // `pool NAME = ACTOR * N` — a supervised session pool binding.
                let decl = parse_actor_ref(&c.name, &c.args, &spec.actors)?;
                spec.actor_refs.push(decl);
            } else if c.name == "supervise" {
                // `supervise NAME { on crash { restart | stop } }` — set a ref's
                // restart policy. Default is restart (respawn a dead worker); a
                // `stop` clause makes the pool fail-stop.
                apply_supervise(&c.args, &mut spec.actor_refs)?;
            } else if c.name == "spawn" {
                // `spawn CMD…` or `spawn { CMD }`: launch CMD via `sh -c` and use
                // its stdout as the stream (input source, in place of stdin). A
                // leading `-pty` runs CMD on a pseudo-terminal so it behaves as if
                // interactive and `send "…"` can drive its stdin (Expect).
                let args = c.args.as_slice();
                let (pty, args) = match args.first().and_then(Arg::as_str) {
                    Some("-pty") => (true, &args[1..]),
                    _ => (false, args),
                };
                let cmd = match args.first() {
                    Some(Arg::Block(b)) => block_to_shell(b),
                    _ => args
                        .iter()
                        .filter_map(Arg::as_str)
                        .collect::<Vec<_>>()
                        .join(" "),
                };
                if cmd.trim().is_empty() {
                    return Err("spawn: missing command".into());
                }
                if stream_source_set(spec) {
                    return Err("spawn: a stream source is already declared".into());
                }
                spec.spawn = Some(cmd);
                spec.spawn_pty = pty;
            } else if c.name == "<" {
                // `< FILE`: read FILE as the stream (input source, in place of stdin).
                // An unquoted absolute path (`/var/log/x`) is truncated by the lexer's
                // `/…/` regex branch — quote it (`< "/var/log/x"`).
                let file = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .filter(|f| !f.trim().is_empty())
                    .ok_or("`<`: missing file path")?;
                if stream_source_set(spec) {
                    return Err("`<`: a stream source is already declared".into());
                }
                spec.source_file = Some(file.to_string());
            } else if c.name == "!" {
                // `! CMD every Ns`: re-run CMD every interval. CMD may be bare words
                // or a `{ … }` block; the interval follows the `every` keyword.
                let evy = c
                    .args
                    .iter()
                    .position(|a| a.as_str() == Some("every"))
                    .ok_or("`!` source: expected `CMD every Ns`")?;
                let dspec = c
                    .args
                    .get(evy + 1)
                    .and_then(Arg::as_str)
                    .ok_or("`!` source: `every` needs a duration (e.g. 1s, 500ms)")?;
                let dur = parse_duration(dspec).ok_or_else(|| {
                    format!("`!` source: `{dspec}` is not a duration (use Ns/Nms/Nm)")
                })?;
                let cmd = match c.args.first() {
                    Some(Arg::Block(b)) => block_to_shell(b),
                    _ => c.args[..evy]
                        .iter()
                        .filter_map(Arg::as_str)
                        .collect::<Vec<_>>()
                        .join(" "),
                };
                if cmd.trim().is_empty() {
                    return Err("`!` source: missing command".into());
                }
                if stream_source_set(spec) {
                    return Err("`!`: a stream source is already declared".into());
                }
                spec.poll = Some((cmd, dur));
            } else if c.name == "rows" || c.name == "cols" {
                // `rows "1 2 1"` / `cols "20 * 2*"` — proportional grid track sizes.
                let spec_str = c
                    .args
                    .iter()
                    .filter_map(Arg::as_str)
                    .collect::<Vec<_>>()
                    .join(" ");
                let tracks = parse_tracks(&spec_str)?;
                if c.name == "rows" {
                    spec.row_tracks = Some(tracks);
                } else {
                    spec.col_tracks = Some(tracks);
                }
            } else if c.name == "gap" {
                // `gap N` — blank cells between grid rows/columns.
                let n = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .and_then(|s| s.parse::<u16>().ok())
                    .ok_or("gap: expected a cell count (`gap 1`)")?;
                spec.gap = n.min(64);
            } else if c.name == "theme" {
                // `theme NAME` — one of the 31 built-in palettes; or
                // `theme custom c1 c2 c3 c4 c5 c6` — a 6-index custom palette.
                let first =
                    c.args.first().and_then(Arg::as_str).ok_or(
                        "theme: expected a name (`theme neon-noir`) or `theme custom c1..c6`",
                    )?;
                if first == "off" || first == "none" {
                    // Opt out to the classic cyan scheme; block the default resolver.
                    spec.theme = None;
                    spec.theme_off = true;
                } else if first == "custom" {
                    let idx: Vec<u8> = c.args[1..]
                        .iter()
                        .filter_map(Arg::as_str)
                        .filter_map(|s| s.parse::<u8>().ok())
                        .collect();
                    if idx.len() != 6 {
                        return Err(
                            "theme custom: expected 6 color indices 0-255 (`theme custom c1 c2 c3 c4 c5 c6`)"
                                .into(),
                        );
                    }
                    spec.theme = Some(crate::theme::custom([
                        idx[0], idx[1], idx[2], idx[3], idx[4], idx[5],
                    ]));
                } else {
                    spec.theme = Some(crate::theme::by_name(first).ok_or_else(|| {
                        format!(
                            "theme: unknown theme `{first}` (see `arb --list-themes`; or `theme custom c1..c6`)"
                        )
                    })?);
                }
            } else if c.name == "layout" {
                // `layout horizontal|vertical` — the no-grid auto-tile direction.
                match c.args.first().and_then(Arg::as_str) {
                    Some("horizontal") | Some("h") => spec.flow = Flow::Horizontal,
                    Some("vertical") | Some("v") => spec.flow = Flow::Vertical,
                    other => {
                        return Err(format!(
                            "layout: expected `horizontal` or `vertical`, got `{}`",
                            other.unwrap_or("")
                        )
                        .into())
                    }
                }
            } else if c.name == "grid" {
                let path = c
                    .args
                    .first()
                    .and_then(Arg::as_str)
                    .ok_or("grid: missing path")?;
                let o = parse_opts(&c.args[1..]);
                // Bound every grid coordinate/span: `compute_rects` sums `row+rowspan`
                // (unguarded usize add -> overflow panic near usize::MAX) and builds a
                // per-cell layout constraint vector of that size (a huge span like
                // `-colspan 50000000` allocates millions of constraints and pegs the
                // cassowary solver -> hang). No real dashboard grid exceeds this.
                const MAX_GRID: usize = 256;
                let opt = |k: &str, d: usize| {
                    o.get(k)
                        .and_then(|s: &String| s.parse::<usize>().ok())
                        .unwrap_or(d)
                        .min(MAX_GRID)
                };
                // `-span` is a colspan shorthand; `-rowspan`/`-colspan` are explicit.
                let colspan = opt("colspan", opt("span", 1)).max(1);
                let rowspan = opt("rowspan", 1).max(1);
                set_grid(
                    spec,
                    path,
                    (opt("row", 0), opt("col", 0)),
                    (rowspan, colspan),
                )?;
            } else if c.name.starts_with('.') {
                if c.args.first().and_then(Arg::as_str) == Some("<-")
                    && c.args.get(1).and_then(Arg::as_str) == Some("in")
                {
                    // `.path <- in` bind shorthand (empty pipeline).
                    let path = c.name.clone();
                    set_source(spec, &path, Source { pipeline: vec![] })?;
                } else if c.args.first().and_then(Arg::as_str) == Some("configure") {
                    // `.path configure -max 200`: merge new opts into the target
                    // widget (build-time; later keys win). Runtime reconfigure via a
                    // bind/expect mutating live opts is a separate, larger feature.
                    let opts = parse_opts(&c.args[1..]);
                    configure_widget(spec, &c.name, opts)?;
                }
            }
            // Unknown verbs are ignored.
            Ok(())
        })();
        res.map_err(|e| e.or_span(c.pos, c.name.chars().count()))?;
    }
    Ok(())
}

/// Resolve a module name to its source: a local `NAME.arb`, then
/// `~/.arb/lib/NAME.arb`, then a bundled stdlib preset.
fn resolve_module(name: &str) -> Result<String, String> {
    // A path-like or already-suffixed name (`import "./lib.arb"`, `import
    // "/abs/lib.arb"`) is read verbatim — don't double up the extension.
    if name.ends_with(".arb") || name.contains('/') {
        if let Ok(s) = std::fs::read_to_string(name) {
            return Ok(s);
        }
    }
    let local = format!("{name}.arb");
    if let Ok(s) = std::fs::read_to_string(&local) {
        return Ok(s);
    }
    if let Some(dir) = lib_dir() {
        if let Ok(s) = std::fs::read_to_string(dir.join(format!("{name}.arb"))) {
            return Ok(s);
        }
    }
    // Installed registry packages (`~/.arb/pkg`) — the SPEC §17 `pkg` tier.
    if let Some(dir) = crate::pkg::pkg_dir() {
        if let Some(s) = crate::pkg::read_pkg_module(&dir, name) {
            return Ok(s);
        }
    }
    bundled_module(name)
        .map(str::to_string)
        .ok_or_else(|| format!("import: module `{name}` not found"))
}

/// Names of the bundled stdlib presets.
pub const STDLIB_NAMES: &[&str] = &[
    "nums",
    "logs",
    "http",
    "json",
    "table",
    "top",
    "docker",
    "k8s",
    "nginx",
    "git",
    "systemd",
    "redis",
    "postgres",
    "mysql",
    "mongodb",
    "kafka",
    "prometheus",
    "elasticsearch",
    "rabbitmq",
    "apache",
    "haproxy",
    "journalctl",
    "dmesg",
    "ps",
    "htop",
    "iostat",
    "vmstat",
    "ss",
    "dig",
    "curl",
    "gh",
    "terraform",
    "aws",
    "gcloud",
    "azure",
    "ansible",
    "consul",
    "vault",
    "etcd",
    "nomad",
    "envoy",
    "memcached",
    "varnish",
    "pgbouncer",
    "celery",
    "sidekiq",
    "gunicorn",
    "supervisor",
    "fail2ban",
    "iptables",
    "conntrack",
    "sar",
    "nats",
    "tomcat",
    "puma",
    "lighttpd",
    "helm",
    "podman",
    "containerd",
    "crictl",
    "istioctl",
    "linkerd",
    "cilium",
    "argocd",
    "fluxcd",
    "velero",
    "kustomize",
    "skopeo",
    "buildah",
    "stern",
    "kubectx",
    "jenkins",
    "gitlabrunner",
    "circleci",
    "drone",
    "buildkite",
    "concourse",
    "woodpecker",
    "spinnaker",
    "tekton",
    "teamcity",
    "packer",
    "vagrant",
    "pulumi",
    "chef",
    "puppet",
    "salt",
    "cloudformation",
    "cdk",
    "doctl",
    "hcloud",
    "fly",
    "heroku",
    "linode",
    "vultr",
    "scaleway",
    "cassandra",
    "scylla",
    "cockroachdb",
    "clickhouse",
    "influxdb",
    "neo4j",
    "couchdb",
    "dynamodb",
    "mariadb",
    "duckdb",
    "sqlite",
    "mssql",
    "timescaledb",
    "arangodb",
    "tidb",
    "victoriametrics",
    "questdb",
    "riak",
    "dgraph",
    "opensearch",
    "grafana",
    "loki",
    "tempo",
    "jaeger",
    "zipkin",
    "datadog",
    "newrelic",
    "sentry",
    "statsd",
    "telegraf",
    "collectd",
    "netdata",
    "zabbix",
    "nagios",
    "icinga",
    "pulsar",
    "activemq",
    "nsq",
    "beanstalkd",
    "caddy",
    "traefik",
    "uwsgi",
    "phpfpm",
    "tcpdump",
    "tshark",
    "nmap",
    "netstat",
    "iftop",
    "nethogs",
    "vnstat",
    "mtr",
    "zfs",
    "btrfs",
    "smartctl",
    "nvme",
    "rclone",
];

fn bundled_module(name: &str) -> Option<&'static str> {
    Some(match name {
        "nums" => include_str!("../stdlib/nums.arb"),
        "logs" => include_str!("../stdlib/logs.arb"),
        "http" => include_str!("../stdlib/http.arb"),
        "json" => include_str!("../stdlib/json.arb"),
        "table" => include_str!("../stdlib/table.arb"),
        "top" => include_str!("../stdlib/top.arb"),
        "docker" => include_str!("../stdlib/docker.arb"),
        "k8s" => include_str!("../stdlib/k8s.arb"),
        "nginx" => include_str!("../stdlib/nginx.arb"),
        "git" => include_str!("../stdlib/git.arb"),
        "systemd" => include_str!("../stdlib/systemd.arb"),
        "redis" => include_str!("../stdlib/redis.arb"),
        "postgres" => include_str!("../stdlib/postgres.arb"),
        "mysql" => include_str!("../stdlib/mysql.arb"),
        "mongodb" => include_str!("../stdlib/mongodb.arb"),
        "kafka" => include_str!("../stdlib/kafka.arb"),
        "prometheus" => include_str!("../stdlib/prometheus.arb"),
        "elasticsearch" => include_str!("../stdlib/elasticsearch.arb"),
        "rabbitmq" => include_str!("../stdlib/rabbitmq.arb"),
        "apache" => include_str!("../stdlib/apache.arb"),
        "haproxy" => include_str!("../stdlib/haproxy.arb"),
        "journalctl" => include_str!("../stdlib/journalctl.arb"),
        "dmesg" => include_str!("../stdlib/dmesg.arb"),
        "ps" => include_str!("../stdlib/ps.arb"),
        "htop" => include_str!("../stdlib/htop.arb"),
        "iostat" => include_str!("../stdlib/iostat.arb"),
        "vmstat" => include_str!("../stdlib/vmstat.arb"),
        "ss" => include_str!("../stdlib/ss.arb"),
        "dig" => include_str!("../stdlib/dig.arb"),
        "curl" => include_str!("../stdlib/curl.arb"),
        "gh" => include_str!("../stdlib/gh.arb"),
        "terraform" => include_str!("../stdlib/terraform.arb"),
        "aws" => include_str!("../stdlib/aws.arb"),
        "gcloud" => include_str!("../stdlib/gcloud.arb"),
        "azure" => include_str!("../stdlib/azure.arb"),
        "ansible" => include_str!("../stdlib/ansible.arb"),
        "consul" => include_str!("../stdlib/consul.arb"),
        "vault" => include_str!("../stdlib/vault.arb"),
        "etcd" => include_str!("../stdlib/etcd.arb"),
        "nomad" => include_str!("../stdlib/nomad.arb"),
        "envoy" => include_str!("../stdlib/envoy.arb"),
        "memcached" => include_str!("../stdlib/memcached.arb"),
        "varnish" => include_str!("../stdlib/varnish.arb"),
        "pgbouncer" => include_str!("../stdlib/pgbouncer.arb"),
        "celery" => include_str!("../stdlib/celery.arb"),
        "sidekiq" => include_str!("../stdlib/sidekiq.arb"),
        "gunicorn" => include_str!("../stdlib/gunicorn.arb"),
        "supervisor" => include_str!("../stdlib/supervisor.arb"),
        "fail2ban" => include_str!("../stdlib/fail2ban.arb"),
        "iptables" => include_str!("../stdlib/iptables.arb"),
        "conntrack" => include_str!("../stdlib/conntrack.arb"),
        "sar" => include_str!("../stdlib/sar.arb"),
        "nats" => include_str!("../stdlib/nats.arb"),
        "tomcat" => include_str!("../stdlib/tomcat.arb"),
        "puma" => include_str!("../stdlib/puma.arb"),
        "lighttpd" => include_str!("../stdlib/lighttpd.arb"),
        "helm" => include_str!("../stdlib/helm.arb"),
        "podman" => include_str!("../stdlib/podman.arb"),
        "containerd" => include_str!("../stdlib/containerd.arb"),
        "crictl" => include_str!("../stdlib/crictl.arb"),
        "istioctl" => include_str!("../stdlib/istioctl.arb"),
        "linkerd" => include_str!("../stdlib/linkerd.arb"),
        "cilium" => include_str!("../stdlib/cilium.arb"),
        "argocd" => include_str!("../stdlib/argocd.arb"),
        "fluxcd" => include_str!("../stdlib/fluxcd.arb"),
        "velero" => include_str!("../stdlib/velero.arb"),
        "kustomize" => include_str!("../stdlib/kustomize.arb"),
        "skopeo" => include_str!("../stdlib/skopeo.arb"),
        "buildah" => include_str!("../stdlib/buildah.arb"),
        "stern" => include_str!("../stdlib/stern.arb"),
        "kubectx" => include_str!("../stdlib/kubectx.arb"),
        "jenkins" => include_str!("../stdlib/jenkins.arb"),
        "gitlabrunner" => include_str!("../stdlib/gitlabrunner.arb"),
        "circleci" => include_str!("../stdlib/circleci.arb"),
        "drone" => include_str!("../stdlib/drone.arb"),
        "buildkite" => include_str!("../stdlib/buildkite.arb"),
        "concourse" => include_str!("../stdlib/concourse.arb"),
        "woodpecker" => include_str!("../stdlib/woodpecker.arb"),
        "spinnaker" => include_str!("../stdlib/spinnaker.arb"),
        "tekton" => include_str!("../stdlib/tekton.arb"),
        "teamcity" => include_str!("../stdlib/teamcity.arb"),
        "packer" => include_str!("../stdlib/packer.arb"),
        "vagrant" => include_str!("../stdlib/vagrant.arb"),
        "pulumi" => include_str!("../stdlib/pulumi.arb"),
        "chef" => include_str!("../stdlib/chef.arb"),
        "puppet" => include_str!("../stdlib/puppet.arb"),
        "salt" => include_str!("../stdlib/salt.arb"),
        "cloudformation" => include_str!("../stdlib/cloudformation.arb"),
        "cdk" => include_str!("../stdlib/cdk.arb"),
        "doctl" => include_str!("../stdlib/doctl.arb"),
        "hcloud" => include_str!("../stdlib/hcloud.arb"),
        "fly" => include_str!("../stdlib/fly.arb"),
        "heroku" => include_str!("../stdlib/heroku.arb"),
        "linode" => include_str!("../stdlib/linode.arb"),
        "vultr" => include_str!("../stdlib/vultr.arb"),
        "scaleway" => include_str!("../stdlib/scaleway.arb"),
        "cassandra" => include_str!("../stdlib/cassandra.arb"),
        "scylla" => include_str!("../stdlib/scylla.arb"),
        "cockroachdb" => include_str!("../stdlib/cockroachdb.arb"),
        "clickhouse" => include_str!("../stdlib/clickhouse.arb"),
        "influxdb" => include_str!("../stdlib/influxdb.arb"),
        "neo4j" => include_str!("../stdlib/neo4j.arb"),
        "couchdb" => include_str!("../stdlib/couchdb.arb"),
        "dynamodb" => include_str!("../stdlib/dynamodb.arb"),
        "mariadb" => include_str!("../stdlib/mariadb.arb"),
        "duckdb" => include_str!("../stdlib/duckdb.arb"),
        "sqlite" => include_str!("../stdlib/sqlite.arb"),
        "mssql" => include_str!("../stdlib/mssql.arb"),
        "timescaledb" => include_str!("../stdlib/timescaledb.arb"),
        "arangodb" => include_str!("../stdlib/arangodb.arb"),
        "tidb" => include_str!("../stdlib/tidb.arb"),
        "victoriametrics" => include_str!("../stdlib/victoriametrics.arb"),
        "questdb" => include_str!("../stdlib/questdb.arb"),
        "riak" => include_str!("../stdlib/riak.arb"),
        "dgraph" => include_str!("../stdlib/dgraph.arb"),
        "opensearch" => include_str!("../stdlib/opensearch.arb"),
        "grafana" => include_str!("../stdlib/grafana.arb"),
        "loki" => include_str!("../stdlib/loki.arb"),
        "tempo" => include_str!("../stdlib/tempo.arb"),
        "jaeger" => include_str!("../stdlib/jaeger.arb"),
        "zipkin" => include_str!("../stdlib/zipkin.arb"),
        "datadog" => include_str!("../stdlib/datadog.arb"),
        "newrelic" => include_str!("../stdlib/newrelic.arb"),
        "sentry" => include_str!("../stdlib/sentry.arb"),
        "statsd" => include_str!("../stdlib/statsd.arb"),
        "telegraf" => include_str!("../stdlib/telegraf.arb"),
        "collectd" => include_str!("../stdlib/collectd.arb"),
        "netdata" => include_str!("../stdlib/netdata.arb"),
        "zabbix" => include_str!("../stdlib/zabbix.arb"),
        "nagios" => include_str!("../stdlib/nagios.arb"),
        "icinga" => include_str!("../stdlib/icinga.arb"),
        "pulsar" => include_str!("../stdlib/pulsar.arb"),
        "activemq" => include_str!("../stdlib/activemq.arb"),
        "nsq" => include_str!("../stdlib/nsq.arb"),
        "beanstalkd" => include_str!("../stdlib/beanstalkd.arb"),
        "caddy" => include_str!("../stdlib/caddy.arb"),
        "traefik" => include_str!("../stdlib/traefik.arb"),
        "uwsgi" => include_str!("../stdlib/uwsgi.arb"),
        "phpfpm" => include_str!("../stdlib/phpfpm.arb"),
        "tcpdump" => include_str!("../stdlib/tcpdump.arb"),
        "tshark" => include_str!("../stdlib/tshark.arb"),
        "nmap" => include_str!("../stdlib/nmap.arb"),
        "netstat" => include_str!("../stdlib/netstat.arb"),
        "iftop" => include_str!("../stdlib/iftop.arb"),
        "nethogs" => include_str!("../stdlib/nethogs.arb"),
        "vnstat" => include_str!("../stdlib/vnstat.arb"),
        "mtr" => include_str!("../stdlib/mtr.arb"),
        "zfs" => include_str!("../stdlib/zfs.arb"),
        "btrfs" => include_str!("../stdlib/btrfs.arb"),
        "smartctl" => include_str!("../stdlib/smartctl.arb"),
        "nvme" => include_str!("../stdlib/nvme.arb"),
        "rclone" => include_str!("../stdlib/rclone.arb"),
        _ => return None,
    })
}

/// List available presets as `(name, description, example)` — bundled stdlib
/// plus any user modules in `~/.arb/lib`. The description is the preset's first
/// `#` line, the example its second (empty when the header has none).
pub fn list_presets() -> Vec<(String, String, String)> {
    let mut out: Vec<(String, String, String)> = STDLIB_NAMES
        .iter()
        .map(|n| {
            let src = bundled_module(n).unwrap_or("");
            (n.to_string(), first_comment(src), example_comment(src))
        })
        .collect();
    if let Some(dir) = lib_dir() {
        out.extend(list_user_presets(&dir));
    }
    out
}

fn first_comment(src: &str) -> String {
    src.lines()
        .find_map(|l| l.trim().strip_prefix('#'))
        .map(|s| s.trim().to_string())
        .unwrap_or_default()
}

/// The invocation a spec documents in its own header — the second `#` line of
/// every stdlib preset, e.g. `#   git log --oneline | arb -p git`. Every preset
/// carries one, but until it is printed the user has to open the file to find
/// out what feeds it, which is the whole failure mode of "spec reads stdin but
/// nothing is piped".
///
/// Taken from the leading comment block only, and only from a line that names
/// `arb` — a spec whose header is prose, not a command line, has no example
/// rather than a wrong one.
pub fn example_comment(src: &str) -> String {
    src.lines()
        .map_while(|l| l.trim().strip_prefix('#'))
        .skip(1)
        .map(str::trim)
        .find(|l| l.contains("arb"))
        .unwrap_or_default()
        .to_string()
}

/// The documented invocation for a preset NAME, resolved the way `import` would
/// resolve it — so a user's `~/.arb/lib/NAME.arb` shadows the bundled preset's
/// example just as it shadows its body.
pub fn preset_example(name: &str) -> String {
    resolve_module(name)
        .map(|src| example_comment(&src))
        .unwrap_or_default()
}

/// Canonical accent color for a widget's `-color NAME` opt, as a `#rrggbb` hex —
/// the single source of truth shared by the TUI (parsed to an RGB color) and the
/// web dashboard (used directly in CSS/SVG). Unknown/absent names default to cyan.
/// Parse a scalar control bound (`-min`/`-max`/`-step`): a plain number, a
/// duration (`5s`/`500ms`/`2m`/`1h`) as seconds, or a size (`1kb`/`4mb`/`2gb`)
/// as bytes. Unparseable -> 0.
pub fn parse_scalar(s: &str) -> f64 {
    let s = s.trim();
    if let Some(d) = parse_duration(s) {
        return d.as_secs_f64();
    }
    let lower = s.to_ascii_lowercase();
    for (suf, mult) in [("kb", 1024.0), ("mb", 1048576.0), ("gb", 1073741824.0)] {
        if let Some(n) = lower.strip_suffix(suf) {
            if let Ok(v) = n.trim().parse::<f64>() {
                return v * mult;
            }
        }
    }
    s.parse::<f64>().unwrap_or(0.0)
}

/// Whether `name` is one of the fixed semantic color names (green/red/…) — an
/// explicit, theme-independent override, distinct from a theme palette slot.
pub fn is_named_color(name: &str) -> bool {
    matches!(
        name.trim().to_ascii_lowercase().as_str(),
        "green"
            | "red"
            | "yellow"
            | "orange"
            | "magenta"
            | "pink"
            | "blue"
            | "white"
            | "gray"
            | "grey"
            | "cyan"
    )
}

pub fn color_hex(name: Option<&str>) -> &'static str {
    match name.map(|s| s.trim().to_ascii_lowercase()).as_deref() {
        Some("green") => "#00e676",
        Some("red") => "#ff5252",
        Some("yellow") => "#ffd740",
        Some("orange") => "#ffab40",
        Some("magenta") | Some("pink") => "#e040fb",
        Some("blue") => "#40c4ff",
        Some("white") => "#e0e0e0",
        Some("gray") | Some("grey") => "#9e9e9e",
        _ => "#00e5ff", // cyan (default)
    }
}

/// The user preset library directory: `$ARB_LIB` when set (used by tests and for
/// relocating the library), else `$HOME/.arb/lib`. `None` if neither is set.
pub fn lib_dir() -> Option<std::path::PathBuf> {
    if let Some(d) = std::env::var_os("ARB_LIB") {
        return Some(std::path::PathBuf::from(d));
    }
    std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".arb/lib"))
}

/// Install a spec `src` into `dir` as `NAME.arb` — the shareable-package unit.
/// The spec is validated (parse + build) first; an invalid package is rejected
/// so the library only ever holds runnable dashboards. Returns the written path.
pub fn install_preset(
    dir: &std::path::Path,
    name: &str,
    src: &str,
) -> Result<std::path::PathBuf, String> {
    if name.is_empty() || name.contains(['/', '\\', '.']) {
        return Err(format!("install: invalid preset name `{name}`"));
    }
    let cmds = crate::parser::parse(src).map_err(|e| format!("install: invalid spec: {e}"))?;
    build(&cmds).map_err(|e| format!("install: invalid spec: {e}"))?;
    std::fs::create_dir_all(dir).map_err(|e| format!("install: {e}"))?;
    let path = dir.join(format!("{name}.arb"));
    std::fs::write(&path, src).map_err(|e| format!("install: {e}"))?;
    Ok(path)
}

/// Remove `NAME.arb` from `dir`. Returns whether a preset was actually removed.
pub fn uninstall_preset(dir: &std::path::Path, name: &str) -> std::io::Result<bool> {
    let path = dir.join(format!("{name}.arb"));
    if path.exists() {
        std::fs::remove_file(&path)?;
        Ok(true)
    } else {
        Ok(false)
    }
}

/// List installed user presets in `dir` as `(name, description, example)`,
/// sorted by name. The description is the preset's first `#` comment line, the
/// example its second.
pub fn list_user_presets(dir: &std::path::Path) -> Vec<(String, String, String)> {
    let mut out = Vec::new();
    if let Ok(entries) = std::fs::read_dir(dir) {
        for e in entries.flatten() {
            let path = e.path();
            if path.extension().and_then(|s| s.to_str()) == Some("arb") {
                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                    let src = std::fs::read_to_string(&path).unwrap_or_default();
                    out.push((stem.to_string(), first_comment(&src), example_comment(&src)));
                }
            }
        }
    }
    out.sort_by(|a, b| a.0.cmp(&b.0));
    out
}

/// Collect `-flag value` pairs into an options map.
fn parse_opts(args: &[Arg]) -> BTreeMap<String, String> {
    let mut m = BTreeMap::new();
    let mut i = 0;
    while i < args.len() {
        if let Some(flag) = args[i].as_str().and_then(|w| w.strip_prefix('-')) {
            // A block value (`-tabs {a b}`) becomes a comma-joined word list:
            // each top-level command contributes its name plus its word args
            // (Tcl-flavored `{a b}` is one command `a b`), so `{a b}` -> "a,b".
            let val = match args.get(i + 1) {
                Some(Arg::Block(cmds)) => {
                    let mut words = Vec::new();
                    for c in cmds {
                        words.push(c.name.clone());
                        words.extend(c.args.iter().filter_map(|a| a.as_str().map(str::to_string)));
                    }
                    words.join(",")
                }
                Some(a) => a.as_str().unwrap_or("").to_string(),
                None => String::new(),
            };
            m.insert(flag.to_string(), val);
            i += 2;
        } else {
            i += 1;
        }
    }
    m
}

/// Parse a `test "NAME" { … }` body into a [`TestCase`]. Clauses: `given LINES…`
/// (input, one line per arg), `run { in; … }` (the pipeline, required), and
/// `want LINES…` (expected output). Unknown clauses / a missing `run` error.
fn parse_test_case(
    name: String,
    body: &[Command],
    actors: &BTreeMap<String, Arc<ActorDef>>,
) -> Result<TestCase, String> {
    let str_args = |c: &Command| -> Vec<String> {
        c.args
            .iter()
            .filter_map(Arg::as_str)
            .map(String::from)
            .collect()
    };
    let mut given = Vec::new();
    let mut want = Vec::new();
    let mut ops = None;
    for c in body {
        match c.name.as_str() {
            "given" => given = str_args(c),
            "want" => want = str_args(c),
            "run" => {
                let b = match c.args.first() {
                    Some(Arg::Block(b)) => b,
                    _ => return Err(format!("test `{name}`: `run` expects `{{ in; … }}`")),
                };
                // Reuse the real body compiler, so a test can exercise native
                // verbs and the jq/xpath front-ends alike.
                ops = Some(pipeline_from_body(b, actors).map_err(|e| e.msg)?);
            }
            other => {
                return Err(format!(
                    "test `{name}`: unknown clause `{other}` (use given / run / want)"
                ))
            }
        }
    }
    let ops = ops.ok_or_else(|| format!("test `{name}`: missing `run {{ … }}`"))?;
    Ok(TestCase {
        name,
        given,
        ops,
        want,
    })
}

/// Reconstruct the source text of a braced argument. The lexer reads `{ div.card
/// h2 }` as a BLOCK of commands, because braces are how arb spells every other
/// nested body — but `sel`'s brace holds a CSS selector, not commands, so the
/// words have to be put back together. Command separators (`;`/newline) inside
/// the brace become spaces, which is what a multi-line selector list means.
fn block_text(cmds: &[Command]) -> String {
    cmds.iter()
        .map(|c| {
            std::iter::once(c.name.clone())
                .chain(c.args.iter().map(|a| match a {
                    Arg::Block(inner) => format!("{{{}}}", block_text(inner)),
                    // A QUOTED arg keeps its quotes. Dropping them turned
                    // `sel { a[href="/x"] }` into `a[href=/x]`, which is not a
                    // legal CSS selector — and the parse failure then read as
                    // "no matches", so a selector the docs advertise silently
                    // selected nothing.
                    Arg::Str(v) => quote_arg(v),
                    other => other.as_str().unwrap_or_default().to_string(),
                }))
                .collect::<Vec<_>>()
                .join(" ")
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Compile a `source { … }` body into a query pipeline. Must start with `in`.
fn pipeline_from_body(
    cmds: &[Command],
    actors: &BTreeMap<String, Arc<ActorDef>>,
) -> Result<Vec<QueryOp>, crate::err::SpecError> {
    let mut ops = Vec::new();
    let mut saw_in = false;
    // The stream holds JSON VALUES rather than markup: a JSON-family reader
    // opened it and no HTML/XML step (`sel`, `find`, an xpath step) has run
    // since. Over such a stream a leading `@` cannot be an attribute step.
    let mut json_values = false;
    for c in cmds {
        // Process one op; on error, anchor the diagnostic to THIS (nested) verb's
        // source position, not the outer `source`/`out` command (the IIFE lets the
        // arms' `return Err` unwind to the per-command span attach below).
        let step = (|| -> Result<(), crate::err::SpecError> {
            // jq front-end: a body command whose first token is a jq literal (starts
            // with `.`, or a `select(…)`/`map(…)` stage) is translated to arb ops.
            // Inside a `source` body a leading `.` is unambiguous — widget-path decls
            // never appear here. The whole command text (verb + args) is reconstructed
            // so the jq `|` pipe, which is not an arb separator, can be split by `jq`.
            // `has(…)` is the jq CALL form and routes here; arb's native
            // space-separated `has KEY` filter is a different verb and still
            // matches below. `to_entries`/`values` are jq builtin names the spec
            // lists as supported but that have no native spelling, so without
            // this arm they died as `unknown verb`.
            if c.name.starts_with('.')
                || c.name.starts_with("select(")
                || c.name.starts_with("map(")
                || c.name.starts_with("has(")
                || matches!(c.name.as_str(), "to_entries" | "values")
                // A jq `@format` string. A leading `@` otherwise means an XPATH
                // attribute step, so only the nine format NAMES are claimed —
                // `@href` still selects an attribute.
                || opens_jq_format(&c.name)
                // Over JSON values a leading `@` is jq's whatever the name: an
                // xpath `@attr` step there would parse each JSON line as HTML and
                // select nothing, so `@base32` (not a format in jq 1.8) or
                // `@foo` printed nothing and exited 0 where jq raises
                // `foo is not a valid format`.
                || (json_values && c.name.starts_with('@'))
            {
                let mut parts = vec![c.name.clone()];
                parts.extend(c.args.iter().filter_map(Arg::as_str).map(str::to_string));
                let src = parts.join(" ");
                match crate::jq::translate(&src) {
                    Ok(jq_ops) => ops.extend(jq_ops),
                    // Outside the translatable subset. That used to be the end of
                    // it — SPEC §8 listed ~120 constructs as hard errors purely
                    // because a `Vec<QueryOp>` cannot express them. It compiles as
                    // a real jq program instead, and only a program that is not
                    // valid jq EITHER keeps the original refusal.
                    Err(sub_err) => match crate::query::jq_program(&src) {
                        Ok(_) => ops.push(QueryOp::JqProgram(src)),
                        Err(_) => return Err(sub_err.into()),
                    },
                }
                return Ok(());
            }
            // xpath front-end: a body command whose first token is an xpath literal
            // (`/…`, `//…`, or `@…`) translates to arb's Find/Attr/Text ops. Disjoint
            // from the jq test above (`.`/`select(`/`map(`) and from native verbs
            // (alnum), so the three coexist in one body unambiguously.
            if c.name.starts_with('/') || c.name.starts_with('@') {
                json_values = false;
                let mut parts = vec![c.name.clone()];
                parts.extend(c.args.iter().filter_map(Arg::as_str).map(str::to_string));
                let xp_ops = crate::xpath::translate(&parts.join(" "))?;
                ops.extend(xp_ops);
                return Ok(());
            }
            match c.name.as_str() {
                "in" | "in.html" | "in.xml" | "in.logfmt" => {
                    saw_in = true;
                    json_values = false;
                }
                "in.json" => {
                    saw_in = true;
                    json_values = true;
                    ops.push(QueryOp::JsonDocs);
                }
                "in.csv" => {
                    saw_in = true;
                    json_values = true;
                    ops.push(QueryOp::Csv);
                }
                "in.tsv" => {
                    saw_in = true;
                    json_values = true;
                    ops.push(QueryOp::Tsv);
                }
                "in.yaml" | "in.yml" => {
                    saw_in = true;
                    json_values = true;
                    ops.push(QueryOp::Yaml);
                }
                // `out.FORMAT [INDENT]` — yq's `-o=` / `-I` in arb's spelling.
                //
                // The default rendering stays one compact JSON line per
                // document, which is what every existing pipeline and the whole
                // `yq_probe` corpus expects. `out.yaml` is what turns the node
                // metadata the YAML reader kept back into YAML, so
                // `in.yaml; out.yaml` gives the file back — comments, anchors,
                // tags, quoting and all.
                "out.yaml" | "out.yml" | "out.json" | "out.props" | "out.xml" | "out.csv"
                | "out.tsv" => {
                    let fmt = match c.name.as_str() {
                        "out.yaml" | "out.yml" => crate::query::OutFmt::Yaml,
                        "out.json" => crate::query::OutFmt::Json,
                        "out.props" => crate::query::OutFmt::Props,
                        "out.xml" => crate::query::OutFmt::Xml,
                        "out.csv" => crate::query::OutFmt::Csv,
                        _ => crate::query::OutFmt::Tsv,
                    };
                    let indent = match c.args.first().and_then(Arg::as_str) {
                        Some(n) => n
                            .parse::<usize>()
                            .map_err(|_| format!("{}: expected an indent width", c.name))?,
                        None => 2,
                    };
                    ops.push(QueryOp::Emit(fmt, indent));
                }
                "in.toml" => {
                    saw_in = true;
                    json_values = true;
                    ops.push(QueryOp::Toml);
                }
                "sel" => {
                    // `sel { div.card h2 }` is the spelling SPEC §8 and the README
                    // both show, and it is the one that did NOT work: a braced
                    // argument lexes to `Arg::Block`, `as_str` drops it, and the
                    // verb then reported "expected a CSS selector" for the exact
                    // form the docs advertise. The block's source text is
                    // reconstructed here so both spellings compile to the same op.
                    let flat: Vec<String> = c
                        .args
                        .iter()
                        .map(|a| match a {
                            Arg::Block(cmds) => block_text(cmds),
                            other => other.as_str().unwrap_or_default().to_string(),
                        })
                        .collect();
                    let words: Vec<&str> = flat.iter().map(String::as_str).collect();
                    let mut css_parts = Vec::new();
                    let mut attr = None;
                    let mut i = 0;
                    while i < words.len() {
                        if words[i] == "-attr" {
                            attr = words.get(i + 1).map(|s| s.to_string());
                            i += 2;
                        } else {
                            css_parts.push(words[i]);
                            i += 1;
                        }
                    }
                    let css = css_parts.join(" ");
                    if css.trim().is_empty() {
                        return Err("sel: expected a CSS selector".into());
                    }
                    // A MALFORMED selector is a hard error here, before any input
                    // is read. The evaluator used to map a parse failure to an
                    // EMPTY result, which made `sel { a[href=/x] }` — a selector
                    // no CSS engine accepts — indistinguishable from one that
                    // legitimately matches nothing. That is the silent
                    // reinterpretation SPEC §8 rules out, and it is the same
                    // failure the xpath leg had.
                    check_css(&css, "sel")?;
                    json_values = false;
                    ops.push(QueryOp::Sel { css, attr });
                }
                "find" => {
                    let css = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .collect::<Vec<_>>()
                        .join(" ");
                    if css.trim().is_empty() {
                        return Err("find: expected a tag/selector".into());
                    }
                    check_css(&css, "find")?;
                    json_values = false;
                    ops.push(QueryOp::Find(css));
                }
                "attr" => {
                    let name = str_arg(c);
                    if name.is_empty() {
                        return Err("attr: expected an attribute name".into());
                    }
                    ops.push(QueryOp::Attr(name));
                }
                "text" => ops.push(QueryOp::Text),
                "match" | "grep" => ops.push(QueryOp::Match(regex_arg(c)?)),
                "reject" | "grepv" => ops.push(QueryOp::Reject(regex_arg(c)?)),
                "field" => ops.push(QueryOp::Field(field_sel(&c.args)?)),
                "fields" => {
                    let cols: Vec<usize> = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .filter_map(|s| s.parse::<usize>().ok())
                        .collect();
                    if cols.is_empty() {
                        return Err("fields: expected column numbers (e.g. fields 1 3)".into());
                    }
                    ops.push(QueryOp::Fields(cols));
                }
                "each" => ops.push(QueryOp::Each),
                "count" => ops.push(QueryOp::Count),
                "rate" => ops.push(QueryOp::Rate),
                "tally" => ops.push(QueryOp::Tally),
                "sum" => ops.push(QueryOp::Sum),
                "min" => ops.push(QueryOp::Min),
                "max" => ops.push(QueryOp::Max),
                "avg" => ops.push(QueryOp::Avg),
                // `names` is the NATIVE line-per-key verb. It is deliberately not
                // spelled `keys`: `keys` is jq's canonical name for the sorted
                // array, and the native table is matched before the jq
                // fall-through, so claiming that spelling would shadow jq's
                // builtin and break the superset contract (SPEC §8).
                "names" => ops.push(QueryOp::Keys),
                "vals" => ops.push(QueryOp::Vals),
                "pick" => {
                    let keys: Vec<String> = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .map(str::to_string)
                        .collect();
                    if keys.is_empty() {
                        return Err("pick: expected one or more key names".into());
                    }
                    ops.push(QueryOp::Pick(keys));
                }
                "sort" => {
                    let flags: Vec<&str> = c.args.iter().filter_map(Arg::as_str).collect();
                    ops.push(QueryOp::Sort {
                        numeric: flags.contains(&"-n"),
                        reverse: flags.contains(&"-r"),
                    });
                }
                "uniq" => ops.push(QueryOp::Uniq),
                "rev" => ops.push(QueryOp::Rev),
                "first" => ops.push(QueryOp::First),
                "last" => ops.push(QueryOp::Last),
                "upper" => ops.push(QueryOp::Upper),
                "lower" => ops.push(QueryOp::Lower),
                "trim" => ops.push(QueryOp::Trim),
                "replace" => {
                    let re = regex_arg(c)?;
                    let to = c
                        .args
                        .get(1)
                        .and_then(Arg::as_str)
                        .unwrap_or("")
                        .to_string();
                    ops.push(QueryOp::Replace(re, to));
                }
                "join" => {
                    let sep = c
                        .args
                        .first()
                        .and_then(Arg::as_str)
                        .unwrap_or(" ")
                        .to_string();
                    ops.push(QueryOp::Join(sep));
                }
                "nth" => ops.push(QueryOp::Nth(count_arg(c, "nth")?)),
                "take" => ops.push(QueryOp::Take(count_arg(c, "take")?)),
                "drop" => ops.push(QueryOp::Drop(count_arg(c, "drop")?)),
                "calc" => {
                    let src = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .collect::<Vec<_>>()
                        .join(" ");
                    ops.push(QueryOp::Calc(crate::expr::parse(&src)?));
                }
                "where" => {
                    let src = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .collect::<Vec<_>>()
                        .join(" ");
                    ops.push(QueryOp::Where(crate::expr::parse(&src)?));
                }
                "map" => {
                    let src = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .collect::<Vec<_>>()
                        .join(" ");
                    ops.push(QueryOp::Map(crate::expr::parse(&src)?));
                }
                "via" => {
                    // `via NAME` / `via NAME * N` — fan the stream across a pool of
                    // actor NAME. Tokens join then split on `*`: left = actor name,
                    // right = optional worker count (0 = one per hardware thread).
                    let joined = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .collect::<Vec<_>>()
                        .join(" ");
                    let (name, workers) = match joined.split_once('*') {
                        Some((n, w)) => {
                            let count = w.trim().parse::<usize>().map_err(|_| {
                                format!("via: `* {}` is not a worker count", w.trim())
                            })?;
                            // Cap the pool so `via NAME * 9999999` can't spawn a
                            // runaway number of threads.
                            (n.trim().to_string(), count.min(1024))
                        }
                        None => (joined.trim().to_string(), 0),
                    };
                    if name.is_empty() {
                        return Err("via: expected an actor name (`via NAME [* N]`)".into());
                    }
                    let def = actors
                        .get(&name)
                        .ok_or_else(|| format!("via: no actor named `{name}` in scope (declare `actor {name}(state) {{ … }}` before this `via`)"))?
                        .clone();
                    ops.push(QueryOp::Via(def, workers));
                }
                "sort_by" => {
                    let field = str_arg(c);
                    if field.is_empty() {
                        return Err("sort_by: expected a field name".into());
                    }
                    ops.push(QueryOp::SortBy(field));
                }
                "unique_by" => {
                    let field = str_arg(c);
                    if field.is_empty() {
                        return Err("unique_by: expected a field name".into());
                    }
                    ops.push(QueryOp::UniqueBy(field));
                }
                "count_by" => {
                    let field = str_arg(c);
                    if field.is_empty() {
                        return Err("count_by: expected a field name".into());
                    }
                    ops.push(QueryOp::CountBy(field));
                }
                "group_by" => {
                    let field = str_arg(c);
                    if field.is_empty() {
                        return Err("group_by: expected a field name".into());
                    }
                    ops.push(QueryOp::GroupBy(field));
                }
                "min_by" => {
                    let field = str_arg(c);
                    if field.is_empty() {
                        return Err("min_by: expected a field name".into());
                    }
                    ops.push(QueryOp::MinBy(field));
                }
                "max_by" => {
                    let field = str_arg(c);
                    if field.is_empty() {
                        return Err("max_by: expected a field name".into());
                    }
                    ops.push(QueryOp::MaxBy(field));
                }
                "has" => {
                    let key = str_arg(c);
                    if key.is_empty() {
                        return Err("has: expected a key name".into());
                    }
                    ops.push(QueryOp::Has(key));
                }
                "entries" => {
                    if !c.args.is_empty() {
                        return Err("entries: takes no arguments".into());
                    }
                    ops.push(QueryOp::Entries);
                }
                "flatten" => ops.push(QueryOp::Flatten),
                "add" => ops.push(QueryOp::Add),
                "over" => {
                    let n = c
                        .args
                        .first()
                        .and_then(Arg::as_str)
                        .and_then(|s| s.parse::<f64>().ok())
                        .ok_or_else(|| "over: expected a numeric threshold".to_string())?;
                    ops.push(QueryOp::Over(n));
                }
                "under" => {
                    let n: f64 = str_arg(c)
                        .parse()
                        .map_err(|_| "under: expected a number".to_string())?;
                    ops.push(QueryOp::Under(n));
                }
                "between" => {
                    let lo = c
                        .args
                        .first()
                        .and_then(Arg::as_str)
                        .and_then(|s| s.parse::<f64>().ok())
                        .ok_or_else(|| "between: expected two numbers A B".to_string())?;
                    let hi = c
                        .args
                        .get(1)
                        .and_then(Arg::as_str)
                        .and_then(|s| s.parse::<f64>().ok())
                        .ok_or_else(|| "between: expected two numbers A B".to_string())?;
                    ops.push(QueryOp::Between(lo, hi));
                }
                "enumerate" => {
                    ops.push(QueryOp::Enumerate);
                }
                "words" => {
                    if !c.args.is_empty() {
                        return Err("words: takes no arguments".into());
                    }
                    ops.push(QueryOp::Words);
                }
                "dedup" => ops.push(QueryOp::Dedup),
                "tailn" => ops.push(QueryOp::Tailn(count_arg(c, "tailn")?)),
                "pad" => {
                    let n = count_arg(c, "pad")?;
                    ops.push(QueryOp::Pad(n));
                }
                "lpad" => ops.push(QueryOp::Lpad(count_arg(c, "lpad")?)),
                "grepf" => {
                    let field = c
                        .args
                        .first()
                        .and_then(Arg::as_str)
                        .ok_or_else(|| "grepf: expected FIELD and /re/".to_string())?
                        .to_string();
                    let raw = c
                        .args
                        .get(1)
                        .and_then(Arg::as_str)
                        .ok_or_else(|| "grepf: expected a pattern".to_string())?;
                    let pat = raw
                        .strip_prefix('/')
                        .and_then(|s| s.strip_suffix('/'))
                        .unwrap_or(raw);
                    let re =
                        regex::Regex::new(pat).map_err(|e| format!("grepf: bad regex: {e}"))?;
                    ops.push(QueryOp::Grepf(field, re));
                }
                "apply" => {
                    let name = str_arg(c);
                    let name = name.strip_prefix('.').unwrap_or(&name).to_string();
                    ops.push(QueryOp::Apply(name));
                }
                "basename" => ops.push(QueryOp::Basename),
                "dirname" => ops.push(QueryOp::Dirname),
                "commafy" => ops.push(QueryOp::Commafy),
                "bytes" => ops.push(QueryOp::Bytes),
                "duration" => ops.push(QueryOp::Duration),
                "flip" => {
                    ops.push(QueryOp::Flip);
                }
                "b64" => {
                    ops.push(QueryOp::B64);
                }
                "b64d" => {
                    ops.push(QueryOp::B64d);
                }
                "hex" => ops.push(QueryOp::Hex),
                "unhex" => {
                    ops.push(QueryOp::Unhex);
                }
                "urlenc" => {
                    ops.push(QueryOp::Urlenc);
                }
                "urldec" => {
                    ops.push(QueryOp::Urldec);
                }
                "extract" => {
                    ops.push(QueryOp::Extract(regex_arg(c)?));
                }
                "split" => {
                    let delim = str_arg(c);
                    if delim.is_empty() {
                        return Err("split: expected a non-empty delimiter".into());
                    }
                    ops.push(QueryOp::Split(delim));
                }
                "substr" => {
                    let args: Vec<usize> = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .filter_map(|s| s.parse::<usize>().ok())
                        .collect();
                    if args.len() != 2 {
                        return Err("substr: expected two non-negative integer args A B".into());
                    }
                    ops.push(QueryOp::Substr(args[0], args[1]));
                }
                "chars" => ops.push(QueryOp::Chars),
                "title" => {
                    ops.push(QueryOp::Title);
                }
                "repeat" => {
                    let n = count_arg(c, "repeat")?;
                    ops.push(QueryOp::Repeat(n));
                }
                "set" => {
                    let key = str_arg(c);
                    if key.is_empty() {
                        return Err("set: expected key and value".into());
                    }
                    let val = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .nth(1)
                        .unwrap_or("")
                        .to_string();
                    ops.push(QueryOp::Set(key, val));
                }
                "del" => {
                    let key = str_arg(c);
                    if key.is_empty() {
                        return Err("del: expected a key name".into());
                    }
                    ops.push(QueryOp::Del(key));
                }
                "rename" => {
                    let args: Vec<String> = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .map(str::to_string)
                        .collect();
                    if args.len() != 2 || args[0].is_empty() || args[1].is_empty() {
                        return Err("rename: expected OLD NEW key names".into());
                    }
                    ops.push(QueryOp::Rename(args[0].clone(), args[1].clone()));
                }
                "default" => {
                    let args: Vec<String> = c
                        .args
                        .iter()
                        .filter_map(Arg::as_str)
                        .map(str::to_string)
                        .collect();
                    if args.len() != 2 {
                        return Err("default: expected exactly two args: key value".into());
                    }
                    ops.push(QueryOp::Default(args[0].clone(), args[1].clone()));
                }
                "merge" => {
                    ops.push(QueryOp::Merge);
                }
                "floor" => {
                    ops.push(QueryOp::Floor);
                }
                "ceil" => {
                    ops.push(QueryOp::Ceil);
                }
                "clamp" => {
                    let mut it = c.args.iter().filter_map(Arg::as_str);
                    let lo = it.next().and_then(|s| s.parse::<f64>().ok());
                    let hi = it.next().and_then(|s| s.parse::<f64>().ok());
                    match (lo, hi) {
                        (Some(lo), Some(hi)) => ops.push(QueryOp::Clamp(lo, hi)),
                        _ => return Err("clamp: expected LO HI numeric args".into()),
                    }
                }
                "contains" => ops.push(QueryOp::Contains(str_arg(c))),
                "starts" => ops.push(QueryOp::Starts(str_arg(c))),
                "ends" => ops.push(QueryOp::Ends(str_arg(c))),
                "nonempty" => ops.push(QueryOp::Nonempty),
                "numeric" => ops.push(QueryOp::Numeric),
                "len" => ops.push(QueryOp::Len),
                // jq `length`: JSON-aware (array/object/string/number), vs `len`
                // which is the raw char count.
                "length" => ops.push(QueryOp::JsonLen),
                "wc" => ops.push(QueryOp::Wc),
                "abs" => ops.push(QueryOp::Abs),
                "round" => ops.push(QueryOp::Round),
                "delta" => ops.push(QueryOp::Delta),
                "cumsum" => ops.push(QueryOp::Cumsum),
                "sma" => ops.push(QueryOp::Sma(count_arg(c, "sma")?)),
                "ewma" => {
                    let a = str_arg(c).parse::<f64>().map_err(|_| {
                        "ewma: expected a smoothing factor 0–1 (e.g. 0.3)".to_string()
                    })?;
                    ops.push(QueryOp::Ewma(a));
                }
                "prepend" => ops.push(QueryOp::Prepend(str_arg(c))),
                "append" => ops.push(QueryOp::Append(str_arg(c))),
                "cut" => {
                    let delim = str_arg(c);
                    let n = c
                        .args
                        .get(1)
                        .and_then(Arg::as_str)
                        .and_then(|s| s.parse::<usize>().ok())
                        .unwrap_or(0);
                    ops.push(QueryOp::Cut(delim, n));
                }
                "median" => ops.push(QueryOp::Median),
                "percentile" => {
                    let p = str_arg(c)
                        .parse::<f64>()
                        .map_err(|_| "percentile: expected a number 0–100 (e.g. 99)".to_string())?;
                    ops.push(QueryOp::Percentile(p));
                }
                "p50" => ops.push(QueryOp::Percentile(50.0)),
                "p90" => ops.push(QueryOp::Percentile(90.0)),
                "p95" => ops.push(QueryOp::Percentile(95.0)),
                "p99" => ops.push(QueryOp::Percentile(99.0)),
                "stddev" => ops.push(QueryOp::Stddev),
                "range" => ops.push(QueryOp::Range),
                "product" => ops.push(QueryOp::Product),
                "distinct" => ops.push(QueryOp::Distinct),
                "sample" => ops.push(QueryOp::Sample(count_arg(c, "sample")?)),
                "bins" => ops.push(QueryOp::Bins(count_arg(c, "bins")?)),
                "index" => ops.push(QueryOp::Index(count_arg(c, "index")?)),
                "slice" => {
                    let a = c
                        .args
                        .first()
                        .and_then(Arg::as_str)
                        .and_then(|s| s.parse::<usize>().ok())
                        .unwrap_or(1);
                    let b = c
                        .args
                        .get(1)
                        .and_then(Arg::as_str)
                        .and_then(|s| s.parse::<usize>().ok())
                        .unwrap_or(usize::MAX);
                    ops.push(QueryOp::Slice(a, b));
                }
                // Not an arb verb. Before reporting one, try the whole command
                // as a jq PROGRAM: `crate::jq` translates the subset that maps
                // onto arb's line-stream ops, and `crate::jqlang` runs everything
                // else as real jq. The native table is matched FIRST and wins
                // every shared spelling, which is exactly the context rule SPEC
                // §8 states — a bare alphanumeric word is arb's native verb, and
                // only what arb has no verb for reaches jq.
                other => {
                    let mut parts = vec![other.to_string()];
                    parts.extend(c.args.iter().map(|a| match a {
                        Arg::Block(inner) => format!("{{{}}}", block_text(inner)),
                        // A QUOTED arg must be handed on still quoted. `as_str`
                        // flattens `Arg::Str` and `Arg::Word` to the same text,
                        // so `string-length("abcd")` was reconstructed as
                        // `string-length(abcd)` — where `abcd` reads as a
                        // location path, and the answer came back 0 instead of
                        // 4. The same loss reaches jq, where `select(.a == "x")`
                        // became `select(.a == x)`.
                        Arg::Str(v) => quote_arg(v),
                        x => x.as_str().unwrap_or_default().to_string(),
                    }));
                    let src = parts.join(" ");
                    match crate::query::jq_program(&src) {
                        Ok(_) => ops.push(QueryOp::JqProgram(src)),
                        // A program that opens with a double-quoted string is
                        // jq's even when jq refuses it. XPath spells a string
                        // literal the same way but has no escapes, so the
                        // fallback below read `"\(1;2)"` — a jq syntax error —
                        // as the literal text `\(1;2)` and printed it.
                        Err(e) if src.starts_with('"') => {
                            return Err(format!("jq: {}", e.trim_start_matches("jq: ")).into())
                        }
                        // Not a native verb and not a jq program: try XPath, but
                        // only HERE, as the LAST resort.
                        //
                        // XPath's core library shares spellings with jq and with
                        // arb's own verbs, and a language matched BEFORE another
                        // does not merely win a word — it SHADOWS it. That is
                        // what made a native verb named `keys` break the jq
                        // superset, and the fix is not to repeat it. Being last
                        // means XPath can never take a spelling another engine
                        // answers: `contains("a","b")` stays jq's, and XPath's
                        // two-argument `contains` is still reachable where it is
                        // actually used, inside an expression
                        // (`//p[contains(@class,'a')]`).
                        //
                        // Measured on this corpus: of the 27 core functions,
                        // `contains` is the only spelling jq claims.
                        Err(_) => match crate::xpath::translate(&src) {
                            Ok(xops) => ops.extend(xops),
                            // Report arb's own diagnostic, not a parse error from
                            // either guest language: a typo'd arb verb is far
                            // likelier, and "unknown verb" points at the real
                            // mistake.
                            Err(_) => return Err(format!("source: unknown verb `{other}`").into()),
                        },
                    }
                }
            }
            Ok(())
        })();
        step.map_err(|e| e.or_span(c.pos, c.name.chars().count()))?;
    }
    if !saw_in {
        return Err("source: pipeline must start with `in`".into());
    }
    Ok(ops)
}

/// Compile a `/pattern/` (or bare `pattern`) literal into a `Regex`. Shared by
/// the arg form (`match /re/`, single-clause `expect /re/ …`) and the
/// `expect { }` block-clause form, where the `/re/` arrives as the clause
/// command's *name*.
fn compile_regex(raw: &str) -> Result<Regex, String> {
    let pat = raw
        .strip_prefix('/')
        .and_then(|s| s.strip_suffix('/'))
        .unwrap_or(raw);
    Regex::new(pat).map_err(|e| format!("bad regex: {e}"))
}

/// Refuse a CSS selector `scraper` cannot parse.
///
/// Reported at BUILD time so it can never be mistaken for an empty match at run
/// time — the message names the verb and the selector, which is what points at
/// the mistake in a spec file.
fn check_css(css: &str, verb: &str) -> Result<(), crate::err::SpecError> {
    match scraper::Selector::parse(css) {
        Ok(_) => Ok(()),
        Err(e) => Err(format!("{verb}: `{css}` is not a valid CSS selector ({e})").into()),
    }
}

/// Re-quote a string argument for a reconstructed command.
///
/// Double quotes are the default because that is what jq needs; a value that
/// itself contains one is wrapped in single quotes instead, which both jq and
/// XPath accept. A value containing BOTH has no quoting that is literal in
/// XPath 1.0 (its Literal production has no escape sequence at all), so it is
/// escaped for jq and that limitation is stated rather than papered over.
fn quote_arg(v: &str) -> String {
    if v.contains('"') && !v.contains('\'') {
        format!("'{v}'")
    } else {
        format!("\"{}\"", v.replace('\\', "\\\\").replace('"', "\\\""))
    }
}

/// Reconstruct a shell string from a `{ … }` block body: each top-level command
/// contributes its verb + word args, commands joined by `; ` (`{ ps aux }` ->
/// "ps aux"; `{ tail -f a.log; grep err }` -> "tail -f a.log; grep err").
fn block_to_shell(cmds: &[Command]) -> String {
    cmds.iter()
        .map(|c| {
            let mut w = vec![c.name.clone()];
            w.extend(c.args.iter().filter_map(|a| a.as_str().map(str::to_string)));
            w.join(" ")
        })
        .collect::<Vec<_>>()
        .join("; ")
}

/// Read a regex argument, stripping optional `/…/` delimiters. The error carries
/// this command's source span so a bad regex anchors to the offending verb (e.g.
/// `match` inside a `source { … }` body), not the enclosing directive.
fn regex_arg(c: &Command) -> Result<Regex, crate::err::SpecError> {
    let span =
        |msg: String| crate::err::SpecError::from(msg).or_span(c.pos, c.name.chars().count());
    let raw = c
        .args
        .first()
        .and_then(Arg::as_str)
        .ok_or_else(|| span(format!("{}: expected a pattern", c.name)))?;
    compile_regex(raw).map_err(|e| span(format!("{}: {e}", c.name)))
}

/// Parse a required count argument for `take`/`drop`.
/// The first arg as a string (empty if absent) — for verbs taking a literal.
fn str_arg(c: &Command) -> String {
    c.args
        .first()
        .and_then(Arg::as_str)
        .unwrap_or("")
        .to_string()
}

fn count_arg(c: &Command, verb: &str) -> Result<usize, String> {
    c.args
        .first()
        .and_then(Arg::as_str)
        .and_then(|s| s.parse::<usize>().ok())
        .ok_or_else(|| format!("{verb}: expected a count"))
}

/// A single numeric arg selects a whitespace column; anything else is a JSON
/// key path (`field a b c` -> a.b.c).
fn field_sel(args: &[Arg]) -> Result<FieldSel, String> {
    let words: Vec<&str> = args.iter().filter_map(Arg::as_str).collect();
    if words.is_empty() {
        return Err("field: expected a column number or key path".into());
    }
    if words.len() == 1 {
        if let Ok(n) = words[0].parse::<usize>() {
            return Ok(FieldSel::Col(n));
        }
    }
    Ok(FieldSel::Key(words.iter().map(|s| s.to_string()).collect()))
}

fn set_source(spec: &mut Spec, path: &str, src: Source) -> Result<(), String> {
    for w in &mut spec.widgets {
        if w.path == path {
            w.source = Some(src);
            return Ok(());
        }
    }
    Err(format!("source: no widget named `{path}`"))
}

/// `.path configure -k v …`: merge `opts` into the named widget's options
/// (later keys win), so a spec can retune a widget after declaring it.
fn configure_widget(
    spec: &mut Spec,
    path: &str,
    opts: BTreeMap<String, String>,
) -> Result<(), String> {
    for w in &mut spec.widgets {
        if w.path == path {
            w.opts.extend(opts);
            return Ok(());
        }
    }
    Err(format!("configure: no widget named `{path}`"))
}

fn set_search(spec: &mut Spec, path: &str, pipeline: Vec<QueryOp>) -> Result<(), String> {
    for w in &mut spec.widgets {
        if w.path == path {
            w.search = Some(pipeline);
            return Ok(());
        }
    }
    Err(format!("search: no widget named `{path}`"))
}

fn set_grid(
    spec: &mut Spec,
    path: &str,
    cell: (usize, usize),
    span: (usize, usize),
) -> Result<(), String> {
    for w in &mut spec.widgets {
        if w.path == path {
            w.grid = Some(cell);
            w.span = span;
            return Ok(());
        }
    }
    Err(format!("grid: no widget named `{path}`"))
}

/// Whether a command's first token opens a jq `@format`.
///
/// A leading `@` otherwise means an XPATH attribute step, so only the nine
/// format names are claimed and `@href` still selects an attribute. What decides
/// is where the NAME ends — any character that could not continue an identifier
/// — not whether a space follows it.
///
/// That distinction is the bug this replaced. The test used to be
/// `starts_with("@base64 ")`, so `@base64|length` matched nothing here and fell
/// through to the xpath front-end below, where `@base64` is an attribute step
/// and `|` is the union operator. It parsed, ran against JSON, and printed
/// NOTHING — and `@base64|.` printed the input unencoded. A jq program silently
/// answering as xpath is the worst shape of divergence, because both engines are
/// real and neither reports a problem. `@base64d ` was also absent from that
/// list, so the trailing-space form of it had the same fate.
///
/// Any NAME followed by a string is a jq format string too (`@foo "lit"`): jq
/// decides at run time whether it knows the format, and an xpath attribute
/// step is never followed by a string.
fn opens_jq_format(name: &str) -> bool {
    let Some(rest) = name.strip_prefix('@') else {
        return false;
    };
    let after = rest.trim_start_matches(|c: char| c.is_alphanumeric() || c == '_');
    if after.len() < rest.len() && after.trim_start().starts_with('"') {
        return true;
    }
    crate::jqlang::FORMAT_NAMES.iter().any(|f| {
        rest.strip_prefix(f)
            .is_some_and(|tail| !tail.starts_with(|c: char| c.is_alphanumeric() || c == '_'))
    })
}