mq-run 0.8.4

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

// Tracks whether any non-falsy value has been printed during a run.
// Used by --exit-status / -e to decide the process exit code. A plain
// AtomicBool (rather than a thread_local) is required because batch
// processing can fan out across rayon worker threads.
static HAD_TRUTHY_OUTPUT: AtomicBool = AtomicBool::new(false);

// Tracks whether --diff found any changed input, for the exit-code-1 CI check below.
static HAD_DIFF: AtomicBool = AtomicBool::new(false);

use crate::grep;
use mq_help as help;

#[derive(Parser, Debug, Default)]
#[command(name = "mq")]
#[command(author = env!("CARGO_PKG_AUTHORS"))]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(after_help = "# Examples\n\n\
    mq 'query' file.md\n\n\
    Run `mq help examples` for more usage examples, or `mq help <name>` for\n\
    function/selector/module docs.\n")]
#[command(
    about = "mq is a markdown processor that can filter markdown nodes by using jq-like syntax.",
    long_about = None,
    disable_help_subcommand = true
)]
pub struct Cli {
    #[clap(flatten)]
    input: InputArgs,

    #[clap(flatten)]
    output: OutputArgs,

    #[clap(subcommand)]
    commands: Option<Commands>,

    /// List all available subcommands (built-in and external)
    #[arg(long)]
    list: bool,

    /// Number of files to process before switching to parallel processing
    #[arg(short = 'P', default_value_t = 10)]
    parallel_threshold: usize,

    #[arg(value_name = "QUERY OR FILE")]
    query: Option<String>,
    files: Option<Vec<PathBuf>>,

    /// Positional string arguments, available as ARGS."positional" in queries.
    #[arg(long = "argv", num_args = 0..)]
    argv: Option<Vec<String>>,

    /// Optimization level for AST transformations (none = no changes, basic = constant folding and dead-branch elimination, full = all passes).
    #[arg(short='O', long = "optimize-level", value_enum, default_value_t = OptimizeLevel::None)]
    optimize_level: OptimizeLevel,

    /// Maximum time in seconds allowed for query evaluation before aborting (e.g. 0.5, 5).
    /// No timeout by default.
    #[arg(long, value_name = "SECONDS")]
    timeout: Option<f64>,

    /// Enter the interactive debugger when an uncaught error occurs (mq-dbg only).
    #[cfg(feature = "debugger")]
    #[arg(long = "stop-on-error", default_value_t = false)]
    stop_on_error: bool,
}

#[cfg(unix)]
const UNIX_EXECUTABLE_BITS: u32 = 0o111;

/// Represents the input format for processing.
///
/// Native formats (no module import):
/// - Markdown: Standard Markdown parsing.
/// - Mdx: MDX parsing.
/// - Html: HTML parsing.
/// - Text: Treats input as plain text.
/// - Null: No input.
/// - Raw: Treats all input as a single string, without parsing.
/// - Bytes: Reads input as raw bytes (`RuntimeValue::Bytes`), without any parsing.
///
/// Module-backed formats (auto-import and parse, sorted alphabetically):
/// - Cbor: Reads input as raw bytes and parses via the `cbor` module.
/// - Csv/Gron/Json/Psv/Toml/Toon/Tsv/Xml/Yaml: Auto-import the matching module and parse.
#[derive(Clone, Debug, Default, clap::ValueEnum, PartialEq)]
enum InputFormat {
    #[default]
    Markdown,
    Mdx,
    Html,
    Text,
    Null,
    Raw,
    Bytes,
    Cbor,
    Csv,
    Gron,
    Json,
    Psv,
    Toml,
    Toon,
    Tsv,
    Xml,
    Yaml,
}

impl InputFormat {
    fn from_extension(ext: &str) -> Self {
        match ext.to_lowercase().as_str() {
            "md" | "markdown" => Self::Markdown,
            "mdx" => Self::Mdx,
            "html" | "htm" => Self::Html,
            "txt" | "log" => Self::Raw,
            "jsonl" | "ndjson" => Self::Text,
            "cbor" => Self::Cbor,
            "csv" => Self::Csv,
            "gron" => Self::Gron,
            "json" => Self::Json,
            "psv" => Self::Psv,
            "toml" => Self::Toml,
            "toon" => Self::Toon,
            "tsv" => Self::Tsv,
            "xml" => Self::Xml,
            "yaml" | "yml" => Self::Yaml,
            _ => Self::Markdown,
        }
    }

    fn needs_binary_read(&self) -> bool {
        matches!(self, Self::Bytes | Self::Cbor)
    }

    fn module_query_prefix(&self) -> Option<&'static str> {
        match self {
            // Module-backed formats (alphabetical order)
            Self::Cbor => Some(r#"import "cbor" | cbor::cbor_parse()"#),
            Self::Csv => Some(r#"import "csv" | csv::csv_parse(true)"#),
            Self::Gron => Some(r#"import "gron" | gron::gron_parse()"#),
            Self::Json => Some(r#"import "json" | json::json_parse()"#),
            Self::Psv => Some(r#"import "csv" | csv::psv_parse(true)"#),
            Self::Toml => Some(r#"import "toml" | toml::toml_parse()"#),
            Self::Toon => Some(r#"import "toon" | toon::toon_parse()"#),
            Self::Tsv => Some(r#"import "csv" | csv::tsv_parse(true)"#),
            Self::Xml => Some(r#"import "xml" | xml::xml_parse()"#),
            Self::Yaml => Some(r#"import "yaml" | yaml::yaml_parse()"#),
            _ => None,
        }
    }
}

/// Holds file/stdin content as either UTF-8 text or raw bytes.
enum ContentData {
    Text(String),
    Bytes(Vec<u8>),
}

impl ContentData {
    fn empty() -> Self {
        ContentData::Text(String::new())
    }

    fn as_str(&self) -> Option<&str> {
        match self {
            ContentData::Text(s) => Some(s),
            ContentData::Bytes(_) => None,
        }
    }

    fn as_bytes(&self) -> &[u8] {
        match self {
            ContentData::Text(s) => s.as_bytes(),
            ContentData::Bytes(b) => b,
        }
    }
}

impl From<String> for ContentData {
    fn from(s: String) -> Self {
        ContentData::Text(s)
    }
}

impl From<Vec<u8>> for ContentData {
    fn from(b: Vec<u8>) -> Self {
        ContentData::Bytes(b)
    }
}

#[derive(Clone, Debug, Default, clap::ValueEnum)]
enum OptimizeLevel {
    #[default]
    None,
    Basic,
    Full,
}

impl From<OptimizeLevel> for mq_lang::OptimizationLevel {
    fn from(level: OptimizeLevel) -> Self {
        match level {
            OptimizeLevel::None => mq_lang::OptimizationLevel::None,
            OptimizeLevel::Basic => mq_lang::OptimizationLevel::Basic,
            OptimizeLevel::Full => mq_lang::OptimizationLevel::Full,
        }
    }
}

#[derive(Clone, Debug, Default, clap::ValueEnum)]
enum OutputFormat {
    #[default]
    Markdown,
    Html,
    Text,
    Json,
    Table,
    Grep,
    Gron,
    Raw,
    Csv,
    Toml,
    Toon,
    Xml,
    Yaml,
    Shell,
    None,
}

#[derive(Debug, Clone, Default, clap::ValueEnum)]
pub enum ListStyle {
    #[default]
    Dash,
    Plus,
    Star,
}

#[derive(Debug, Clone, PartialEq, Default, clap::ValueEnum)]
pub enum LinkTitleStyle {
    #[default]
    Double,
    Single,
    Paren,
}

#[derive(Debug, Clone, PartialEq, Default, clap::ValueEnum)]
pub enum LinkUrlStyle {
    #[default]
    None,
    Angle,
}

#[derive(Clone, Debug, clap::Args, Default)]
struct InputArgs {
    /// Aggregate all input files/content into a single array
    #[arg(short = 'A', long, default_value_t = false)]
    aggregate: bool,

    /// load filter from the file
    #[arg(short, long, default_value_t = false)]
    from_file: bool,

    /// Set input format
    #[arg(short = 'I', long, value_enum)]
    input_format: Option<InputFormat>,

    /// Search modules from the directory
    #[arg(short = 'L', long = "directory")]
    module_directories: Option<Vec<PathBuf>>,

    /// Load additional modules from specified files
    #[arg(short = 'M', long)]
    module_names: Option<Vec<String>>,

    /// Import modules by name, making them available as `name::fn()` in queries
    #[arg(short = 'm', long)]
    import_module_names: Option<Vec<String>>,

    /// Sets a named string argument. NAME is accessible directly in queries, and also
    /// via ARGS."named" when --args or --argv is given.
    #[arg(long, num_args = 2, value_names = ["NAME", "VALUE"], aliases = ["arg", "define"])]
    args: Option<Vec<String>>,

    /// Sets a named JSON argument. NAME is accessible directly in queries
    #[arg(long, num_args = 2, value_names = ["NAME", "JSON_VALUE"])]
    argjson: Option<Vec<String>>,

    /// Sets file contents that can be referenced at runtime
    #[arg(long="rawfile", num_args = 2, value_names = ["NAME", "FILE"])]
    raw_file: Option<Vec<String>>,

    /// Sets a named argument from a JSON file. NAME is bound to an array of every JSON
    /// value found in FILE (jq --slurpfile compatible), so a file containing a single
    /// JSON value becomes a one-element array.
    #[arg(long = "slurpfile", num_args = 2, value_names = ["NAME", "FILE"])]
    slurp_file: Option<Vec<String>>,

    /// Enable streaming mode for processing large files line by line
    #[arg(long, default_value_t = false)]
    stream: bool,

    /// Watch the input file(s) for changes and automatically re-run the query whenever
    /// they change. Requires at least one input file (stdin cannot be watched). With
    /// --from-file, the query file is watched too. Runs until interrupted (Ctrl-C); a
    /// query error is printed to stderr and watching continues rather than exiting.
    #[cfg(feature = "watch")]
    #[arg(long, default_value_t = false)]
    watch: bool,

    /// Evaluate the query once against all input files combined (like yq's `eval-all`),
    /// instead of once per file. Enables cross-file aggregation in a single query.
    #[arg(
        long = "eval-all",
        default_value_t = false,
        conflicts_with_all = ["update", "count", "stream", "separator"]
    )]
    eval_all: bool,

    /// Allow `import`/`include` to fetch modules over HTTP(S). Disabled by default
    #[cfg(feature = "http-import")]
    #[arg(long = "allow-http-import", default_value_t = false)]
    allow_http_import: bool,

    /// Allow HTTP imports from additional domain(s) beyond the default. Has no effect
    /// unless `--allow-http-import` (or `--allow-all`) is also passed.
    /// Use `github.com/{user}/{repo}` to allow a specific repository (expanded automatically),
    /// or a plain domain like `example.com` to allow any path under that host.
    /// Repeat to allow multiple extra domains.
    #[cfg(feature = "http-import")]
    #[arg(long = "allowed-domain")]
    allowed_domains: Option<Vec<String>>,

    /// Force re-fetch of mutable-ref (HEAD/branch) HTTP-imported modules, ignoring the local cache.
    /// Versioned (tagged) modules are never re-fetched regardless of this flag.
    #[cfg(feature = "http-import")]
    #[arg(long = "refresh-modules", default_value_t = false)]
    refresh_modules: bool,

    /// Remove all HTTP module cache including versioned (tagged) modules and lock files.
    /// Use this to fully reset the cache when something goes wrong.
    #[cfg(feature = "http-import")]
    #[arg(long = "clear-cache", default_value_t = false)]
    clear_cache: bool,

    /// Disable the mq.lock integrity check for HTTP imports.
    /// By default a fetched URL's content is checked against mq.lock, and a mismatch is
    /// rejected unless --refresh-modules is also passed.
    #[cfg(feature = "http-import")]
    #[arg(long = "no-lockfile", default_value_t = false, conflicts_with_all = ["lockfile_path", "frozen"])]
    no_lockfile: bool,

    /// Fail instead of recording a new mq.lock entry.
    /// `--frozen`; use in CI so a new module's content is only ever trusted during a reviewable local run whose mq.lock diff gets committed, not silently during CI.
    #[cfg(feature = "http-import")]
    #[arg(long = "frozen", default_value_t = false)]
    frozen: bool,

    /// Path to the mq.lock file used for HTTP import integrity checks.
    /// Defaults to ./mq.lock (relative to the current directory).
    #[cfg(feature = "http-import")]
    #[arg(long = "lockfile", value_name = "PATH")]
    lockfile_path: Option<PathBuf>,

    /// Allow the `http` function to make outbound HTTPS requests. Disabled by default;
    /// requests are HTTPS-only and blocked from reaching loopback/private/link-local
    /// addresses regardless of this flag. Pass with no value to allow any domain, or
    /// `--allow-net=DOMAIN` (repeat the flag, or comma-separate, to add more) to restrict
    /// requests to just those domains (and any path under them). The `=` is required so a
    /// bare domain after the flag isn't swallowed as a query/file positional instead.
    #[cfg(feature = "http-import")]
    #[arg(short = 'N', long = "allow-net", num_args = 0.., require_equals = true, value_delimiter = ',', value_name = "DOMAIN")]
    allow_net: Option<Vec<String>>,

    /// Allow the `read_file`/`read_file_bytes`/`collection`/`file_exists`/`embed_images`
    /// functions to read from the filesystem. Disabled by default. Pass with no value to
    /// allow reading anywhere, or `--allow-read=PATH` (files or directories; repeat the
    /// flag, or comma-separate, to add more) to restrict reads to just those paths and
    /// their descendants. The `=` is required so a bare path after the flag isn't
    /// swallowed as a query/file positional instead.
    #[arg(short = 'R', long = "allow-read", num_args = 0.., require_equals = true, value_delimiter = ',', value_name = "PATH")]
    allow_read: Option<Vec<PathBuf>>,

    /// Allow the `write_file`/`extract_images` functions to write to the filesystem.
    /// Disabled by default. Pass with no value to allow writing anywhere, or
    /// `--allow-write=PATH` (files or directories; repeat the flag, or comma-separate, to
    /// add more) to restrict writes to just those paths and their descendants. The `=` is
    /// required so a bare path after the flag isn't swallowed as a query/file positional
    /// instead.
    #[arg(short = 'W', long = "allow-write", num_args = 0.., require_equals = true, value_delimiter = ',', value_name = "PATH")]
    allow_write: Option<Vec<PathBuf>>,

    /// Allow the `system` function to execute external commands. Disabled by default.
    /// Commands run directly (never through a shell), so shell metacharacters in arguments
    /// are never interpreted. Pass with no value to allow any command, or
    /// `--allow-run=COMMAND` (repeat the flag, or comma-separate, to add more) to restrict
    /// execution to just those commands. The `=` is required so a bare command after the
    /// flag isn't swallowed as a query/file positional instead.
    #[arg(long = "allow-run", num_args = 0.., require_equals = true, value_delimiter = ',', value_name = "COMMAND")]
    allow_run: Option<Vec<String>>,

    /// Allow `$VAR`/`${$VAR}` interpolation and debugger logpoints to read environment
    /// variables. Disabled by default. Pass with no value to allow reading any variable, or
    /// `--allow-env=NAME` (repeat the flag, or comma-separate, to add more) to restrict
    /// access to just those names. The `=` is required so a bare name after the flag isn't
    /// swallowed as a query/file positional instead.
    #[arg(short = 'E', long = "allow-env", num_args = 0.., require_equals = true, value_delimiter = ',', value_name = "NAME")]
    allow_env: Option<Vec<String>>,

    /// Grant every sandboxed permission at once (read/write/net/run/env), and also enable
    /// HTTP module imports as if --allow-http-import were passed. Disabled by default.
    /// Cannot be combined with the individual --allow-* flags above.
    #[arg(
        short = 'a',
        long = "allow-all",
        default_value_t = false,
        conflicts_with_all = ["allow_net", "allow_read", "allow_write", "allow_run", "allow_env", "allow_http_import"]
    )]
    allow_all: bool,
}

#[derive(Clone, Debug, clap::Args, Default)]
struct OutputArgs {
    /// Set output format
    #[arg(short = 'F', long, value_enum, default_value_t)]
    output_format: OutputFormat,

    /// Update matching Markdown nodes and write the result to stdout
    #[arg(short = 'U', long = "update", default_value_t = false)]
    update: bool,

    /// With --update, print a unified diff instead of the transformed content;
    /// nothing is written. Multiple files are diffed one at a time with their path
    /// in the headers; stdin is labeled `<stdin>`. Exits 1 if anything would change.
    #[arg(long = "diff", default_value_t = false, requires = "update")]
    diff: bool,

    /// Unbuffered output
    #[clap(long, default_value_t = false)]
    unbuffered: bool,

    /// Set the list style for markdown output
    #[clap(long, value_enum, default_value_t = ListStyle::Dash)]
    list_style: ListStyle,

    /// Set the link title surround style for markdown output
    #[clap(long, value_enum, default_value_t = LinkTitleStyle::Double)]
    link_title_style: LinkTitleStyle,

    /// Set the link URL surround style for markdown links
    #[clap(long, value_enum, default_value_t = LinkUrlStyle::None)]
    link_url_style: LinkUrlStyle,

    /// Specify a query to insert between files as a separator
    #[clap(short = 'S', long, value_name = "QUERY")]
    separator: Option<String>,

    /// Output to the specified file
    #[clap(short = 'o', long = "output", value_name = "FILE")]
    output_file: Option<PathBuf>,

    /// Colorize markdown output
    #[arg(short = 'C', long = "color-output", default_value_t = false)]
    color_output: bool,

    /// Show NUM nodes before each match. Only effective with -F grep.
    #[clap(short = 'B', long, value_name = "NUM")]
    before_context: Option<usize>,

    /// Show NUM nodes after each match. Only effective with -F grep.
    #[clap(long, value_name = "NUM")]
    after_context: Option<usize>,

    /// Show NUM nodes before and after each match. Only effective with -F grep.
    #[clap(long, value_name = "NUM")]
    context: Option<usize>,

    /// Exit with code 1 if the last output value is false, null, or the output
    /// is empty. Mirrors jq's --exit-status / -e flag.
    #[arg(short = 'e', long = "exit-status", default_value_t = false)]
    exit_status: bool,

    /// Output only the count of matching (non-None) results. Mirrors grep -c.
    /// With multiple files, prints "filename: N" per file and "total: N" at the end.
    #[arg(short = 'c', long = "count", default_value_t = false, conflicts_with_all = ["update", "stream"])]
    count: bool,

    /// Skip the first N matching results before outputting.
    #[arg(long, value_name = "N", conflicts_with = "update")]
    skip: Option<usize>,

    /// Limit output to at most N results.
    #[arg(long, value_name = "N", conflicts_with = "update")]
    limit: Option<usize>,

    /// Omit Markdown node position information from structured output
    /// (json, table, gron, csv, toml, toon, xml, yaml). Reduces output size
    /// when source line/column spans aren't needed.
    #[arg(long, default_value_t = false)]
    no_position: bool,
}

impl OutputArgs {
    /// Returns `(before, after)` node counts for grep context expansion.
    /// `--context N` sets both sides; `--before-context` / `--after-context` override each side.
    fn context_counts(&self) -> (usize, usize) {
        let base = self.context.unwrap_or(0);
        let before = self.before_context.unwrap_or(base);
        let after = self.after_context.unwrap_or(base);
        (before, after)
    }

    /// Applies skip/limit pagination to a vector of values.
    ///
    /// Call this on compact (non-empty) values so that N refers to visible results.
    fn paginate<T>(&self, values: Vec<T>) -> Vec<T> {
        let skip = self.skip.unwrap_or(0);
        let values: Vec<T> = values.into_iter().skip(skip).collect();
        if let Some(limit) = self.limit {
            values.into_iter().take(limit).collect()
        } else {
            values
        }
    }
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Start a REPL session for interactive query execution. Optional FILES are
    /// combined as the initial input (same file/format handling as `mq QUERY FILES...`).
    Repl {
        /// Markdown (or other supported format) files to load as the REPL's initial input
        files: Option<Vec<PathBuf>>,
    },
    /// Start a debug adapter for mq
    #[cfg(feature = "debugger")]
    Dap,
    /// Generate a shell completion script and print it to stdout
    Completion {
        /// Shell to generate the completion script for
        #[arg(value_enum)]
        shell: CompletionShell,
    },
    /// Show documentation for a builtin function, selector, standard module, standard-module
    /// function, or the `examples` topic.
    Help {
        /// Name of a function, selector, module, or `examples`, e.g. `map`, `.h1`, `csv_parse`,
        /// `section`, `examples`
        name: Option<String>,
        /// Print machine-readable JSON instead of formatted text
        #[arg(long, conflicts_with = "markdown")]
        json: bool,
        /// Print Markdown instead of formatted text — e.g. queryable with mq itself:
        /// `mq help section --markdown | mq 'select(.code.lang == "mq")'`
        #[arg(long)]
        markdown: bool,
    },
}

/// Shell targets supported by the `completion` subcommand.
#[derive(Clone, Debug, clap::ValueEnum)]
enum CompletionShell {
    Bash,
    Elvish,
    Fish,
    Nushell,
    #[value(name = "powershell")]
    PowerShell,
    Zsh,
}

/// Output mode for the `help` subcommand.
#[derive(Clone, Copy)]
enum HelpFormat {
    Human,
    Json,
    Markdown,
}

impl Cli {
    /// Reserved `mq help` topic name for general CLI usage examples (not a function,
    /// selector, or module).
    const EXAMPLES_TOPIC: &'static str = "examples";

    /// Get the path to the external commands directory (~/.local/bin)
    fn get_external_commands_dir() -> Option<PathBuf> {
        let home_dir = dirs::home_dir()?;
        let mq_bin_dir = home_dir.join(".local").join("bin");
        if mq_bin_dir.exists() && mq_bin_dir.is_dir() {
            Some(mq_bin_dir)
        } else {
            None
        }
    }

    /// Find all external commands (mq-* files in ~/.local/bin and PATH)
    fn find_external_commands() -> Vec<String> {
        let mut seen = std::collections::HashSet::new();

        // Search ~/.local/bin first
        if let Some(bin_dir) = Self::get_external_commands_dir() {
            Self::collect_mq_commands_from_dir(&bin_dir, &mut seen);
        }

        // Search PATH directories
        if let Ok(path_var) = std::env::var("PATH") {
            for dir in std::env::split_paths(&path_var) {
                Self::collect_mq_commands_from_dir(&dir, &mut seen);
            }
        }

        let mut commands: Vec<String> = seen.into_iter().collect();
        commands.sort();
        commands
    }

    /// Collect mq-* command names from a directory.
    fn collect_mq_commands_from_dir(dir: &Path, seen: &mut std::collections::HashSet<String>) {
        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries.flatten() {
                if let Ok(file_name) = entry.file_name().into_string()
                    && file_name.starts_with("mq-")
                    && Self::is_executable_file(&entry)
                    && let Some(subcommand) = file_name.strip_prefix("mq-")
                {
                    let subcommand = Self::strip_executable_extension(subcommand);
                    if !subcommand.is_empty() {
                        seen.insert(subcommand);
                    }
                }
            }
        }
    }

    /// Check if a directory entry is an executable file.
    /// On Windows, checks for executable extensions (.exe, .cmd, .bat, .com).
    /// On Unix, checks for the executable bit in file permissions.
    fn is_executable_file(entry: &fs::DirEntry) -> bool {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            entry
                .metadata()
                .map(|m| m.is_file() && m.permissions().mode() & UNIX_EXECUTABLE_BITS != 0)
                .unwrap_or(false)
        }
        #[cfg(windows)]
        {
            let path = entry.path();
            let is_file = entry.metadata().map(|m| m.is_file()).unwrap_or(false);
            is_file
                && path.extension().and_then(|e| e.to_str()).is_some_and(|ext| {
                    ext.eq_ignore_ascii_case("exe")
                        || ext.eq_ignore_ascii_case("cmd")
                        || ext.eq_ignore_ascii_case("bat")
                        || ext.eq_ignore_ascii_case("com")
                })
        }
        #[cfg(not(any(unix, windows)))]
        {
            entry.metadata().map(|m| m.is_file()).unwrap_or(false)
        }
    }

    /// Strip known executable extensions on Windows. On Unix, returns the name as-is.
    fn strip_executable_extension(name: &str) -> String {
        if cfg!(windows) {
            let path = Path::new(name);
            match path.extension().and_then(|e| e.to_str()) {
                Some("exe" | "cmd" | "bat" | "com") => {
                    path.file_stem().unwrap_or_default().to_string_lossy().to_string()
                }
                _ => name.to_string(),
            }
        } else {
            name.to_string()
        }
    }

    /// Execute an external subcommand
    fn execute_external_command(&self, command_path: PathBuf, args: &[String]) -> miette::Result<()> {
        if args.is_empty() {
            return Err(miette!("No subcommand specified"));
        }

        let subcommand = &args[0];

        // Check if the file is executable
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let metadata = fs::metadata(&command_path).into_diagnostic()?;
            let permissions = metadata.permissions();
            if permissions.mode() & 0o111 == 0 {
                return Err(miette!(
                    "External subcommand 'mq-{}' is not executable. Run: chmod +x {}",
                    subcommand,
                    command_path.display()
                ));
            }
        }

        // Execute the external command with remaining arguments
        let status = Command::new(&command_path).args(&args[1..]).status().map_err(|e| {
            miette!(
                "Failed to execute external subcommand 'mq-{}' at {}: {}",
                subcommand,
                command_path.display(),
                e
            )
        })?;

        if !status.success() {
            let code = status.code().unwrap_or(1);
            std::process::exit(code);
        }

        Ok(())
    }

    /// List all available subcommands (built-in and external)
    fn list_commands(&self) -> miette::Result<()> {
        let mut output = vec![
            format!("{}", "Built-in subcommands:".bold().cyan()),
            format!(
                "  {} - Start a REPL session for interactive query execution",
                "repl".green()
            ),
            format!(
                "  {} - Generate a shell completion script and print it to stdout",
                "completion".green()
            ),
        ];

        #[cfg(feature = "debugger")]
        output.push(format!("  {} - Start a debug adapter for mq", "dap".green()));

        let external_commands = Self::find_external_commands();
        if !external_commands.is_empty() {
            output.push("".to_string());
            output.push(format!(
                "{}",
                "External subcommands (from ~/.local/bin and PATH):".bold().yellow()
            ));
            for cmd in external_commands {
                output.push(format!("  {}", cmd.bright_yellow()));
            }
        }

        println!("{}", output.join("\n"));
        Ok(())
    }

    /// Generate a shell completion script for the given shell and print it to stdout.
    fn generate_completion(shell: &CompletionShell) -> miette::Result<()> {
        let mut command = Cli::command();
        let name = command.get_name().to_string();

        match shell {
            CompletionShell::Bash => {
                clap_complete::generate(clap_complete::Shell::Bash, &mut command, name, &mut io::stdout())
            }
            CompletionShell::Elvish => {
                clap_complete::generate(clap_complete::Shell::Elvish, &mut command, name, &mut io::stdout())
            }
            CompletionShell::Fish => {
                clap_complete::generate(clap_complete::Shell::Fish, &mut command, name, &mut io::stdout())
            }
            CompletionShell::Nushell => {
                clap_complete::generate(clap_complete_nushell::Nushell, &mut command, name, &mut io::stdout())
            }
            CompletionShell::PowerShell => {
                clap_complete::generate(clap_complete::Shell::PowerShell, &mut command, name, &mut io::stdout())
            }
            CompletionShell::Zsh => {
                clap_complete::generate(clap_complete::Shell::Zsh, &mut command, name, &mut io::stdout())
            }
        }

        Ok(())
    }

    /// Shows documentation for a single function/selector/module, or lists everything known
    /// when `name` is `None`. Writes the whole output in one call, not one `println!` per
    /// line — hundreds of lines otherwise means hundreds of flushed syscalls.
    fn run_help(name: Option<&str>, json: bool, markdown: bool) -> miette::Result<()> {
        let format = if json {
            HelpFormat::Json
        } else if markdown {
            HelpFormat::Markdown
        } else {
            HelpFormat::Human
        };

        let stdout = io::stdout();
        let mut handle = BufWriter::new(stdout.lock());

        let Some(name) = name else {
            let out = match format {
                HelpFormat::Json => serde_json::to_string_pretty(&help::all_names()).into_diagnostic()?,
                HelpFormat::Markdown => Self::help_index_markdown(),
                HelpFormat::Human => Self::help_index_text(),
            };
            Self::write_ignore_pipe(&mut handle, out.as_bytes())?;
            Self::write_ignore_pipe(&mut handle, b"\n")?;
            return handle.flush().into_diagnostic();
        };

        // `examples` is a reserved topic name (not a function/selector/module): general CLI
        // usage that clap's own `--help`/`after_help` intentionally keeps short.
        if name == Self::EXAMPLES_TOPIC {
            let out = match format {
                HelpFormat::Json => serde_json::to_string_pretty(&serde_json::json!({
                    "topic": Self::EXAMPLES_TOPIC,
                    "content": Self::examples_topic_markdown(),
                }))
                .into_diagnostic()?,
                HelpFormat::Markdown => Self::examples_topic_markdown(),
                HelpFormat::Human => Self::examples_topic_text(),
            };
            Self::write_ignore_pipe(&mut handle, out.as_bytes())?;
            Self::write_ignore_pipe(&mut handle, b"\n")?;
            return handle.flush().into_diagnostic();
        }

        // A bare name that's both a module and a same-named function within it (e.g.
        // `section`) resolves to the module overview; `module::function` disambiguates.
        if !name.contains("::")
            && let Some(module) = help::lookup_module(name)
        {
            // A selector can also share a module's bare name (e.g. `.table`/`table`,
            // `.toml`/`toml`, `.yaml`/`yaml`); append it after the module overview instead
            // of leaving it unreachable without the leading dot. JSON keeps the module
            // alone for output stability — pass the leading dot (`.table`) for the
            // selector's own JSON.
            let selector_entries: Vec<_> = help::lookup(name)
                .into_iter()
                .filter(|e| e.kind == "selector")
                .collect();

            let out = match format {
                HelpFormat::Json => serde_json::to_string_pretty(&module).into_diagnostic()?,
                HelpFormat::Markdown => {
                    let mut s = help::render_module_markdown(&module);
                    for entry in &selector_entries {
                        s.push('\n');
                        s.push_str(&help::render_markdown(entry));
                    }
                    s
                }
                HelpFormat::Human => {
                    let mut s = help::render_module_human(&module);
                    for entry in &selector_entries {
                        s.push('\n');
                        s.push_str(&help::render_human(entry));
                    }
                    s
                }
            };
            Self::write_ignore_pipe(&mut handle, out.as_bytes())?;
            Self::write_ignore_pipe(&mut handle, b"\n")?;
            return handle.flush().into_diagnostic();
        }

        let entries = help::lookup(name);
        if entries.is_empty() {
            return Err(match help::suggest(name) {
                Some(suggestion) => {
                    miette!("no function, selector, or module named `{name}` — did you mean `{suggestion}`?")
                }
                None => miette!("no function, selector, or module named `{name}`"),
            });
        }

        let out = match format {
            HelpFormat::Json => serde_json::to_string_pretty(&entries).into_diagnostic()?,
            HelpFormat::Markdown => entries.iter().map(help::render_markdown).collect::<Vec<_>>().join("\n"),
            HelpFormat::Human => entries.iter().map(help::render_human).collect::<Vec<_>>().join("\n"),
        };
        Self::write_ignore_pipe(&mut handle, out.as_bytes())?;
        Self::write_ignore_pipe(&mut handle, b"\n")?;
        handle.flush().into_diagnostic()
    }

    /// Sorted, deduped selector and top-level function names for the `mq help` index.
    /// Cheap: uses `top_level_entries`, which never parses standard-module sources.
    fn help_index_names() -> (Vec<String>, Vec<String>) {
        let entries = help::top_level_entries();

        let mut selectors: Vec<String> = entries
            .iter()
            .filter(|e| e.kind == "selector")
            .map(|e| e.name.clone())
            .collect();
        selectors.sort_unstable();
        selectors.dedup();

        let mut functions: Vec<String> = entries
            .iter()
            .filter(|e| e.kind == "function")
            .map(|e| e.name.clone())
            .collect();
        functions.sort_unstable();
        functions.dedup();

        (selectors, functions)
    }

    /// Builds the grouped `mq help` index text: selectors, top-level functions, and modules
    /// (each with a one-line summary), for a name-less human-readable lookup.
    fn help_index_text() -> String {
        let (selectors, functions) = Self::help_index_names();
        let mut out = String::new();

        let _ = writeln!(out, "{}", "Selectors:".bold().cyan());
        for s in selectors {
            let _ = writeln!(out, "  {s}");
        }

        let _ = writeln!(out, "\n{}", "Functions:".bold().cyan());
        for f in functions {
            let _ = writeln!(out, "  {f}");
        }

        let _ = writeln!(out, "\n{}", "Modules:".bold().cyan());
        for module in help::all_modules() {
            let summary = module.description.split(". ").next().unwrap_or_default();
            let padded_name = format!("{:<10}", module.name);
            let _ = writeln!(out, "  {} {}", padded_name.green(), summary);
        }

        let _ = write!(
            out,
            "\nRun `mq help <name>` for a function or selector, `mq help <module>` for a module \
            overview, `mq help examples` for CLI usage examples."
        );

        out
    }

    /// Same content as [`Self::help_index_text`], as Markdown — queryable with mq itself.
    fn help_index_markdown() -> String {
        let (selectors, functions) = Self::help_index_names();
        let mut out = String::new();

        let _ = writeln!(out, "# mq help");

        let _ = writeln!(out, "\n## Selectors\n");
        for s in selectors {
            let _ = writeln!(out, "- `{s}`");
        }

        let _ = writeln!(out, "\n## Functions\n");
        for f in functions {
            let _ = writeln!(out, "- `{f}`");
        }

        let _ = writeln!(out, "\n## Modules\n");
        for module in help::all_modules() {
            let summary = module.description.split(". ").next().unwrap_or_default();
            if summary.is_empty() {
                let _ = writeln!(out, "- `{}`", module.name);
            } else {
                let _ = writeln!(out, "- `{}` — {}", module.name, summary);
            }
        }

        let _ = write!(
            out,
            "\nRun `mq help <name>` for a function or selector, `mq help <module>` for a module \
            overview, `mq help examples` for CLI usage examples."
        );

        out
    }

    /// Text for the `mq help examples` topic — kept out of clap's own `after_help` so
    /// `--help` stays short; this is the fuller reference it points to.
    fn examples_topic_text() -> String {
        let mut out = String::new();

        let _ = writeln!(out, "{}", "Basic usage:".bold().cyan());
        let _ = writeln!(out, "  mq 'query' file.md");
        let _ = writeln!(out, "  mq -f 'file' file.md        # read query from file");
        let _ = writeln!(out, "  mq repl                     # start a REPL session");

        let _ = writeln!(out, "\n{}", "Auto-parsing by file extension or -I flag:".bold().cyan());
        let _ = writeln!(
            out,
            "  mq automatically imports the matching module based on the file extension."
        );
        let _ = writeln!(out, "  Use -I <format> to force a specific format:\n");
        let _ = writeln!(
            out,
            "  .cbor / -I cbor  import \"cbor\" | cbor::cbor_parse()  (reads as bytes)"
        );
        let _ = writeln!(out, "  .csv  / -I csv   import \"csv\"  | csv::csv_parse(true)");
        let _ = writeln!(out, "  .gron / -I gron  import \"gron\" | gron::gron_parse()");
        let _ = writeln!(out, "  .json / -I json  import \"json\" | json::json_parse()");
        let _ = writeln!(out, "  .psv  / -I psv   import \"csv\"  | csv::psv_parse(true)");
        let _ = writeln!(out, "  .toml / -I toml  import \"toml\" | toml::toml_parse()");
        let _ = writeln!(out, "  .toon / -I toon  import \"toon\" | toon::toon_parse()");
        let _ = writeln!(out, "  .tsv  / -I tsv   import \"csv\"  | csv::tsv_parse(true)");
        let _ = writeln!(out, "  .xml  / -I xml   import \"xml\"  | xml::xml_parse()");
        let _ = writeln!(out, "  .yaml / -I yaml  import \"yaml\" | yaml::yaml_parse()\n");
        let _ = writeln!(
            out,
            "  Use -I raw   to disable auto-parsing and receive the raw string."
        );
        let _ = writeln!(out, "  Use -I bytes to read input as raw bytes without parsing.");

        let _ = writeln!(out, "\n{}", "Output formats (-F):".bold().cyan());
        let _ = writeln!(out, "  mq -F json '.h' file.md          # headings as JSON nodes");
        let _ = writeln!(
            out,
            "  mq -F csv 'to_text()' file.md    # every node's text, one per CSV row"
        );

        let _ = writeln!(out, "\n{}", "Updating markdown in place (-U):".bold().cyan());
        let _ = writeln!(
            out,
            "  mq -U '.h1 | update(\"New title\")' file.md  # rewrite the h1, leave everything else untouched"
        );

        let _ = writeln!(out, "\n{}", "Filtering with context (-F grep):".bold().cyan());
        let _ = writeln!(
            out,
            "  mq -F grep --context 1 '.h' file.md  # matches with 1 node of context on each side"
        );
        let _ = writeln!(out, "  (also: -B/--before-context, --after-context)");

        let _ = writeln!(out, "\n{}", "Passing arguments to queries (ARGS):".bold().cyan());
        let _ = writeln!(
            out,
            "  When --args or --argv is given, ARGS = {{\"positional\": [...], \"named\": {{...}}}}\n"
        );
        let _ = writeln!(out, "  mq -I null 'name' --args name Alice");
        let _ = writeln!(out, "  mq -I null 'ARGS | .\"named\"' --args name Alice");
        let _ = writeln!(out, "  # => {{\"name\": \"Alice\"}}\n");
        let _ = writeln!(
            out,
            "  mq -I null 'ARGS | .\"positional\"' --argv x y z  # must come after query and files"
        );
        let _ = writeln!(out, "  # => [\"x\", \"y\", \"z\"]\n");
        let _ = writeln!(out, "  mq -I null 'ARGS' file.md --args name Alice --argv x y z");
        let _ = writeln!(
            out,
            "  # => {{\"positional\": [\"x\",\"y\",\"z\"], \"named\": {{\"name\": \"Alice\"}}}}"
        );

        let _ = writeln!(
            out,
            "\n{}",
            "Sandboxed capabilities (--allow-read/write/net/run/env):".bold().cyan()
        );
        let _ = writeln!(
            out,
            "  Disabled by default; each takes an optional allowlist (comma-separated)."
        );
        let _ = writeln!(out, "  mq --allow-read=. -I null 'read_file(\"notes.md\")'");
        let _ = writeln!(out, "  mq --allow-run=echo -I null 'system(\"echo\", [\"hello\"])'");
        let _ = writeln!(out, "  mq --allow-env=MY_VAR -I null '$MY_VAR'");
        let _ = writeln!(
            out,
            "  mq --allow-net=api.example.com 'http(\"get\", \"https://api.example.com/data\")' file.md"
        );

        #[cfg(feature = "http-import")]
        {
            let _ = writeln!(out, "\n{}", "HTTP module imports (--allow-http-import):".bold().cyan());
            let _ = writeln!(
                out,
                "  Separate from --allow-net above; disabled by default regardless of it."
            );
            let _ = writeln!(
                out,
                "  mq --allow-http-import 'import \"github.com/harehare/kdl.mq\"' file.md"
            );
        }

        let _ = writeln!(out, "\n{}", "Working with multiple files:".bold().cyan());
        let _ = writeln!(
            out,
            "  mq --eval-all '.h1' a.md b.md          # one query over all files combined"
        );
        let _ = writeln!(
            out,
            "  mq -S '\"---\"' '.h1' a.md b.md          # insert a separator between files"
        );

        let _ = writeln!(out, "\n{}", "Streaming large files (--stream):".bold().cyan());
        let _ = write!(out, "  mq --stream -I text 'select(contains(\"ERROR\"))' huge.log");

        out
    }

    /// Same content as [`Self::examples_topic_text`], as Markdown — queryable with mq itself
    /// via `mq help examples --markdown | mq '...'`.
    fn examples_topic_markdown() -> String {
        let mut out = String::new();

        let _ = writeln!(out, "# mq help examples");

        let _ = writeln!(out, "\n## Basic usage\n");
        let _ = writeln!(
            out,
            "```sh\nmq 'query' file.md\nmq -f 'file' file.md        # read query from file\nmq repl                     # start a REPL session\n```"
        );

        let _ = writeln!(out, "\n## Auto-parsing by file extension or -I flag\n");
        let _ = writeln!(
            out,
            "mq automatically imports the matching module based on the file extension. \
            Use `-I <format>` to force a specific format:\n"
        );
        let _ = writeln!(out, "| Extension / `-I` | Query prefix |");
        let _ = writeln!(out, "|---|---|");
        let _ = writeln!(
            out,
            "| `.cbor` / `-I cbor` | `import \"cbor\" \\| cbor::cbor_parse()` (reads as bytes) |"
        );
        let _ = writeln!(out, "| `.csv` / `-I csv` | `import \"csv\" \\| csv::csv_parse(true)` |");
        let _ = writeln!(
            out,
            "| `.gron` / `-I gron` | `import \"gron\" \\| gron::gron_parse()` |"
        );
        let _ = writeln!(
            out,
            "| `.json` / `-I json` | `import \"json\" \\| json::json_parse()` |"
        );
        let _ = writeln!(out, "| `.psv` / `-I psv` | `import \"csv\" \\| csv::psv_parse(true)` |");
        let _ = writeln!(
            out,
            "| `.toml` / `-I toml` | `import \"toml\" \\| toml::toml_parse()` |"
        );
        let _ = writeln!(
            out,
            "| `.toon` / `-I toon` | `import \"toon\" \\| toon::toon_parse()` |"
        );
        let _ = writeln!(out, "| `.tsv` / `-I tsv` | `import \"csv\" \\| csv::tsv_parse(true)` |");
        let _ = writeln!(out, "| `.xml` / `-I xml` | `import \"xml\" \\| xml::xml_parse()` |");
        let _ = writeln!(
            out,
            "| `.yaml` / `-I yaml` | `import \"yaml\" \\| yaml::yaml_parse()` |"
        );
        let _ = writeln!(
            out,
            "\nUse `-I raw` to disable auto-parsing and receive the raw string. Use `-I bytes` to \
            read input as raw bytes without parsing."
        );

        let _ = writeln!(out, "\n## Output formats (-F)\n");
        let _ = writeln!(
            out,
            "```sh\nmq -F json '.h' file.md          # headings as JSON nodes\nmq -F csv 'to_text()' file.md    # every node's text, one per CSV row\n```"
        );

        let _ = writeln!(out, "\n## Updating markdown in place (-U)\n");
        let _ = writeln!(
            out,
            "```sh\nmq -U '.h1 | update(\"New title\")' file.md  # rewrite the h1, leave everything else untouched\n```"
        );

        let _ = writeln!(out, "\n## Filtering with context (-F grep)\n");
        let _ = writeln!(
            out,
            "```sh\nmq -F grep --context 1 '.h' file.md  # matches with 1 node of context on each side\n```\n\n\
            (also: `-B`/`--before-context`, `--after-context`)"
        );

        let _ = writeln!(out, "\n## Passing arguments to queries (ARGS)\n");
        let _ = writeln!(
            out,
            "When `--args` or `--argv` is given, `ARGS = {{\"positional\": [...], \"named\": {{...}}}}`\n"
        );
        let _ = writeln!(
            out,
            "```sh\nmq -I null 'name' --args name Alice\nmq -I null 'ARGS | .\"named\"' --args name Alice\n\
            # => {{\"name\": \"Alice\"}}\n\n\
            mq -I null 'ARGS | .\"positional\"' --argv x y z  # must come after query and files\n\
            # => [\"x\", \"y\", \"z\"]\n\n\
            mq -I null 'ARGS' file.md --args name Alice --argv x y z\n\
            # => {{\"positional\": [\"x\",\"y\",\"z\"], \"named\": {{\"name\": \"Alice\"}}}}\n```"
        );

        let _ = writeln!(out, "\n## Sandboxed capabilities (--allow-read/write/net/run/env)\n");
        let _ = writeln!(
            out,
            "Disabled by default; each takes an optional allowlist (comma-separated).\n"
        );
        let _ = writeln!(
            out,
            "```sh\nmq --allow-read=. -I null 'read_file(\"notes.md\")'\n\
            mq --allow-run=echo -I null 'system(\"echo\", [\"hello\"])'\n\
            mq --allow-env=MY_VAR -I null '$MY_VAR'\n\
            mq --allow-net=api.example.com 'http(\"get\", \"https://api.example.com/data\")' file.md\n```"
        );

        #[cfg(feature = "http-import")]
        {
            let _ = writeln!(out, "\n## HTTP module imports (--allow-http-import)\n");
            let _ = writeln!(
                out,
                "Separate from --allow-net above; disabled by default regardless of it.\n"
            );
            let _ = writeln!(
                out,
                "```sh\nmq --allow-http-import 'import \"github.com/harehare/kdl.mq\"' file.md\n```"
            );
        }

        let _ = writeln!(out, "\n## Working with multiple files\n");
        let _ = writeln!(
            out,
            "```sh\nmq --eval-all '.h1' a.md b.md          # one query over all files combined\n\
            mq -S '\"---\"' '.h1' a.md b.md          # insert a separator between files\n```"
        );

        let _ = writeln!(out, "\n## Streaming large files (--stream)\n");
        let _ = write!(
            out,
            "```sh\nmq --stream -I text 'select(contains(\"ERROR\"))' huge.log\n```"
        );

        out
    }

    pub fn run(&self) -> miette::Result<()> {
        if self.list {
            return self.list_commands();
        }

        if (self.output.before_context.is_some()
            || self.output.after_context.is_some()
            || self.output.context.is_some())
            && !matches!(self.output.output_format, OutputFormat::Grep)
        {
            return Err(miette!(
                "--before-context, --after-context, and --context are only valid with -F grep"
            ));
        }

        // Check if query is actually an external subcommand
        // This handles the case where clap parses "mq test arg1" as query="test", files=["arg1"]
        if !self.input.from_file
            && self.commands.is_none()
            && let Some(query_value) = &self.query
        {
            // Only treat as external command if query_value is a valid file name
            if query_value
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
            {
                let command_path = {
                    let command_bin = format!("mq-{}", query_value);
                    let command_path = Self::get_external_commands_dir().unwrap_or_default().join(&command_bin);

                    if !command_path.exists() {
                        which(&command_bin).ok()
                    } else {
                        Some(command_path)
                    }
                };

                if let Some(command_path) = command_path {
                    let mut args = vec![query_value.clone()];
                    if let Some(files) = &self.files {
                        args.extend(files.iter().map(|p| p.to_string_lossy().to_string()));
                    }
                    return self.execute_external_command(command_path, &args);
                }
            }
        }

        if !matches!(self.input.input_format, Some(InputFormat::Markdown) | None) && self.output.update {
            return Err(miette!("The output format is not supported for the update option"));
        }

        if self.output.diff && matches!(self.output.output_format, OutputFormat::Grep) {
            return Err(miette!("--diff is not supported with -F grep"));
        }

        match &self.commands {
            Some(Commands::Repl { files }) => {
                let engine = self.create_engine()?;
                let input = match files {
                    Some(files) if !files.is_empty() => {
                        let contents = self.read_files_content(files)?;
                        let mut combined = Vec::new();
                        for (file, content) in &contents {
                            combined.extend(self.resolve_input(file, content)?);
                        }
                        combined
                    }
                    _ => vec![mq_lang::RuntimeValue::String("".to_string())],
                };
                mq_repl::Repl::with_engine(engine, input).run()
            }
            None if self.query.is_none() => {
                let engine = self.create_engine()?;
                mq_repl::Repl::with_engine(engine, vec![mq_lang::RuntimeValue::String("".to_string())]).run()
            }
            #[cfg(feature = "debugger")]
            Some(Commands::Dap) => mq_dap::start().map_err(|e| miette!(e.to_string())),
            Some(Commands::Completion { shell }) => Self::generate_completion(shell),
            Some(Commands::Help { name, json, markdown }) => Self::run_help(name.as_deref(), *json, *markdown),
            #[cfg(feature = "watch")]
            None if self.input.watch => self.run_watch(),
            None => {
                let result = self.execute_once();

                // --exit-status / -e: exit with code 1 if no truthy value was
                // produced. Mirrors jq's behaviour: false and null are falsy;
                // everything else (including empty string, 0, [], {}) is truthy.
                if self.output.exit_status {
                    let had_truthy = HAD_TRUTHY_OUTPUT.load(Ordering::Relaxed);
                    if !had_truthy {
                        result?;
                        std::process::exit(1);
                    }
                }

                // --diff: exit 1 if anything would change, for CI gating.
                if self.output.diff && HAD_DIFF.load(Ordering::Relaxed) {
                    result?;
                    std::process::exit(1);
                }

                result
            }
        }
    }

    fn create_engine(&self) -> miette::Result<DefaultEngine> {
        let sandboxed_io = mq_lang::SandboxedIo::new(mq_lang::NativeIo::default());
        let sandboxed_io = if self.input.allow_all {
            sandboxed_io.allow_all()
        } else {
            sandboxed_io
                .allow_read(self.input.allow_read.clone())
                .allow_write(self.input.allow_write.clone())
                .allow_net(self.input.allow_net.clone())
                .allow_run(self.input.allow_run.clone())
                .allow_env(self.input.allow_env.clone())
        };
        let mut engine = mq_lang::DefaultEngine::default();
        engine.set_io(Shared::new(sandboxed_io));
        engine.load_builtin_module();
        engine.set_optimization_level(self.optimize_level.clone().into());

        if self.input.aggregate {
            engine.import_module("section").map_err(|e| *e)?;
        }

        if let Some(dirs) = &self.input.module_directories {
            engine.set_search_paths(dirs.clone());
        }

        if let Some(modules) = &self.input.module_names {
            for module_name in modules {
                engine.load_module(module_name).map_err(|e| *e)?;
            }
        }

        if let Some(modules) = &self.input.import_module_names {
            for module_name in modules {
                engine.import_module(module_name).map_err(|e| *e)?;
            }
        }

        if self.input.args.is_some()
            || self.argv.is_some()
            || self.input.argjson.is_some()
            || self.input.slurp_file.is_some()
        {
            let mut named: BTreeMap<mq_lang::Ident, mq_lang::RuntimeValue> = BTreeMap::new();
            if let Some(args) = &self.input.args {
                for v in args.chunks(2) {
                    engine.define_string_value(&v[0], &v[1]);
                    named.insert(mq_lang::Ident::new(&v[0]), mq_lang::RuntimeValue::String(v[1].clone()));
                }
            }

            if let Some(argjson) = &self.input.argjson {
                for v in argjson.chunks(2) {
                    let json_value: serde_json::Value = serde_json::from_str(&v[1]).into_diagnostic()?;
                    let runtime_value: mq_lang::RuntimeValue = json_value.into();
                    engine.define_value(&v[0], runtime_value.clone());
                    named.insert(mq_lang::Ident::new(&v[0]), runtime_value);
                }
            }

            if let Some(slurp_file) = &self.input.slurp_file {
                for v in slurp_file.chunks(2) {
                    let path = PathBuf::from_str(&v[1]).into_diagnostic()?;

                    if !path.exists() {
                        return Err(miette!("File not found: {}", path.display()));
                    }

                    let content = fs::read_to_string(&path).into_diagnostic()?;
                    let json_values: Vec<serde_json::Value> = serde_json::Deserializer::from_str(&content)
                        .into_iter::<serde_json::Value>()
                        .collect::<Result<_, _>>()
                        .into_diagnostic()?;
                    let runtime_value = mq_lang::RuntimeValue::Array(mq_lang::Shared::new(
                        json_values.into_iter().map(Into::into).collect(),
                    ));
                    engine.define_value(&v[0], runtime_value.clone());
                    named.insert(mq_lang::Ident::new(&v[0]), runtime_value);
                }
            }

            let positional: Vec<mq_lang::RuntimeValue> = self
                .argv
                .as_deref()
                .unwrap_or(&[])
                .iter()
                .map(|s| mq_lang::RuntimeValue::String(s.clone()))
                .collect();
            let args_map: BTreeMap<mq_lang::Ident, mq_lang::RuntimeValue> = [
                (
                    mq_lang::Ident::new("positional"),
                    mq_lang::RuntimeValue::Array(Shared::new(positional)),
                ),
                (
                    mq_lang::Ident::new("named"),
                    mq_lang::RuntimeValue::Dict(Shared::new(named)),
                ),
            ]
            .into_iter()
            .collect();
            engine.define_value("ARGS", mq_lang::RuntimeValue::Dict(Shared::new(args_map)));
        }

        if let Some(raw_file) = &self.input.raw_file {
            for v in raw_file.chunks(2) {
                let path = PathBuf::from_str(&v[1]).into_diagnostic()?;

                if !path.exists() {
                    return Err(miette!("File not found: {}", path.display()));
                }

                let content = fs::read_to_string(&path).into_diagnostic()?;
                engine.define_string_value(&v[0], &content);
            }
        }

        #[cfg(feature = "http-import")]
        {
            engine.set_http_import_enabled(self.input.allow_http_import || self.input.allow_all);
            if let Some(domains) = &self.input.allowed_domains {
                engine.set_http_allowed_domains(domains.clone());
            }
            if self.input.no_lockfile {
                engine.set_lockfile_enabled(false);
            }
            if self.input.frozen {
                engine.set_lockfile_frozen(true);
            }
            if let Some(path) = &self.input.lockfile_path {
                engine.set_lockfile_path(path.clone());
            }
            if self.input.clear_cache {
                engine.clear_http_cache_all().map_err(|e| miette!(e.to_string()))?;
            } else if self.input.refresh_modules {
                engine.clear_http_cache().map_err(|e| miette!(e.to_string()))?;
            }
        }

        if let Some(secs) = self.timeout {
            if secs <= 0.0 {
                return Err(miette!("--timeout must be greater than 0"));
            }
            engine.set_timeout(std::time::Duration::from_secs_f64(secs));
        }

        #[cfg(feature = "debugger")]
        {
            use crate::debugger::DebuggerHandler;
            let handler = DebuggerHandler::new(engine.clone(), self.stop_on_error);
            engine.set_debugger_handler(Box::new(handler));
            engine.debugger().write().unwrap().activate();
        }

        Ok(engine)
    }

    fn get_query(&self) -> miette::Result<String> {
        let query = match self.query.as_ref() {
            Some(q) if self.input.from_file => {
                let path = PathBuf::from_str(q).into_diagnostic()?;
                fs::read_to_string(path).into_diagnostic()?
            }
            Some(q) => q.clone(),
            None => return Err(miette!("Query is required")),
        };

        let aggregate = self.input.aggregate.then_some("nodes");
        Ok(aggregate.map(|agg| format!("{} | {}", agg, query)).unwrap_or(query))
    }

    /// Returns a query prefix that auto-imports and parses a module-backed format.
    ///
    /// If an explicit `-I <format>` is given and it is a module-backed format, the prefix
    /// for that format is returned. Otherwise the file extension is used for detection.
    fn auto_query_prefix(&self, file: &Option<PathBuf>) -> Option<String> {
        if let Some(fmt) = &self.input.input_format {
            return fmt.module_query_prefix().map(str::to_string);
        }
        let ext = file.as_ref()?.extension()?.to_string_lossy().to_lowercase();
        InputFormat::from_extension(&ext)
            .module_query_prefix()
            .map(str::to_string)
    }

    fn set_file_vars(&self, engine: &mut mq_lang::DefaultEngine, file: &Path) {
        engine.define_string_value("__FILE__", file.to_string_lossy().as_ref());
        engine.define_string_value(
            "__FILE_NAME__",
            file.file_name().unwrap_or_default().to_string_lossy().as_ref(),
        );
        engine.define_string_value(
            "__FILE_STEM__",
            file.file_stem().unwrap_or_default().to_string_lossy().as_ref(),
        );
    }

    fn resolve_input(
        &self,
        file: &Option<PathBuf>,
        content: &ContentData,
    ) -> miette::Result<Vec<mq_lang::RuntimeValue>> {
        let text = content.as_str().unwrap_or("");
        Ok(
            match self.input.input_format.as_ref().cloned().unwrap_or_else(|| {
                if let Some(file) = file {
                    InputFormat::from_extension(&file.extension().unwrap_or_default().to_string_lossy())
                } else if io::stdin().is_terminal() {
                    InputFormat::Null
                } else {
                    InputFormat::Markdown
                }
            }) {
                // Native formats
                InputFormat::Markdown => mq_lang::parse_markdown_input(text)?,
                InputFormat::Mdx => mq_lang::parse_mdx_input(text)?,
                InputFormat::Html => mq_lang::parse_html_input(text)?,
                InputFormat::Text => mq_lang::parse_text_input(text)?,
                InputFormat::Null => mq_lang::null_input(),
                InputFormat::Raw => mq_lang::raw_input(text),
                // Bytes: pass raw binary content as RuntimeValue::Bytes with no further parsing.
                InputFormat::Bytes => mq_lang::bytes_input(content.as_bytes()),
                // Module-backed binary format: pass raw bytes; the cbor module handles parsing.
                InputFormat::Cbor => mq_lang::bytes_input(content.as_bytes()),
                // Module-backed text formats (alphabetical): pass raw string; the module handles parsing.
                InputFormat::Csv
                | InputFormat::Gron
                | InputFormat::Json
                | InputFormat::Psv
                | InputFormat::Toml
                | InputFormat::Toon
                | InputFormat::Tsv
                | InputFormat::Xml
                | InputFormat::Yaml => mq_lang::raw_input(text),
            },
        )
    }

    fn apply_update(
        &self,
        input: Vec<mq_lang::RuntimeValue>,
        results: mq_lang::RuntimeValues,
    ) -> miette::Result<mq_lang::RuntimeValues> {
        let current_values: mq_lang::RuntimeValues = input.into();
        if current_values.len() != results.len() {
            return Err(miette!("The number of input and output values do not match"));
        }
        Ok(current_values.update_with(results))
    }

    fn emit_results(
        &self,
        runtime_values: mq_lang::RuntimeValues,
        grep_input: Option<Vec<mq_lang::RuntimeValue>>,
        file: &Option<PathBuf>,
    ) -> miette::Result<()> {
        let runtime_values = if self.output.skip.is_some() || self.output.limit.is_some() {
            let compact = runtime_values.compact();
            let had_empties = compact.len() < runtime_values.len();
            let paginated: Vec<mq_lang::RuntimeValue> = self
                .output
                .paginate(compact)
                .into_iter()
                .map(|v| {
                    if had_empties {
                        match v {
                            mq_lang::RuntimeValue::Markdown(mut node, meta) => {
                                node.set_position(None);
                                mq_lang::RuntimeValue::Markdown(node, meta)
                            }
                            other => other,
                        }
                    } else {
                        v
                    }
                })
                .collect();
            paginated.into()
        } else {
            runtime_values
        };

        if let Some(input) = grep_input {
            let (before, after) = self.output.context_counts();
            grep::print_grep(
                runtime_values,
                &input,
                file,
                &self.output.output_file,
                self.output.unbuffered,
                before,
                after,
            )
        } else {
            self.print(runtime_values)
        }
    }

    fn execute(
        &self,
        engine: &mut mq_lang::DefaultEngine,
        query: &str,
        file: &Option<PathBuf>,
        content: &ContentData,
    ) -> miette::Result<()> {
        let effective_query;
        let query = match self.auto_query_prefix(file) {
            Some(prefix) => {
                effective_query = format!("{} | {}", prefix, query);
                effective_query.as_str()
            }
            None => query,
        };

        if let Some(f) = file {
            self.set_file_vars(engine, f);
        }

        let input = self.resolve_input(file, content)?;
        let is_grep = matches!(self.output.output_format, OutputFormat::Grep);
        let grep_input: Option<Vec<mq_lang::RuntimeValue>> = is_grep.then(|| input.clone());

        let runtime_values = if self.output.update {
            let results = engine.eval(query, input.clone().into_iter()).map_err(|e| *e)?;
            self.apply_update(input, results)?
        } else {
            engine.eval(query, input.into_iter()).map_err(|e| *e)?
        };

        if self.output.update && self.output.diff {
            return self.emit_diff(&runtime_values, file, content);
        }

        if let Some(separator) = &self.output.separator {
            let separator = engine
                .eval(
                    separator,
                    vec![mq_lang::RuntimeValue::String("".to_string())].into_iter(),
                )
                .map_err(|e| *e)?;
            self.print(separator)?;
        }

        self.emit_results(runtime_values, grep_input, file)
    }

    /// Returns the effective query string combining any auto-prefix with the base query.
    fn effective_query(&self, query: &str, file: &Option<PathBuf>) -> String {
        match self.auto_query_prefix(file) {
            Some(prefix) => format!("{} | {}", prefix, query),
            None => query.to_string(),
        }
    }

    /// Returns true if all files would produce the same effective query prefix.
    fn all_files_same_prefix(&self, files: &[(Option<PathBuf>, ContentData)]) -> bool {
        if files.is_empty() {
            return true;
        }
        let first = self.auto_query_prefix(&files[0].0);
        files[1..].iter().all(|(f, _)| self.auto_query_prefix(f) == first)
    }

    fn execute_once(&self) -> miette::Result<()> {
        if self.input.stream {
            self.process_streaming()
        } else {
            self.process_batch()
        }
    }

    #[cfg(feature = "watch")]
    fn watch_targets(&self) -> miette::Result<Vec<PathBuf>> {
        let mut targets = self.files.clone().unwrap_or_default();

        if targets.is_empty() {
            return Err(miette!(
                "--watch requires at least one input file; stdin cannot be watched"
            ));
        }

        if self.input.from_file
            && let Some(query_path) = &self.query
        {
            targets.push(PathBuf::from(query_path));
        }

        Ok(targets)
    }

    #[cfg(feature = "watch")]
    fn canonical_parent_dir(path: &Path) -> PathBuf {
        let dir = path
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."));
        fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf())
    }

    /// Errors go to stderr instead of ending the loop, so one bad query doesn't stop watching.
    #[cfg(feature = "watch")]
    fn run_once_watch(&self) {
        if let Err(err) = self.execute_once() {
            eprintln!("{:?}", err);
        }
    }

    /// A `[filename]` tag for status lines, so they're never mistaken for query output
    /// interleaved on the same terminal. Colorized when possible, plain text otherwise.
    #[cfg(feature = "watch")]
    fn watch_badge(watch_paths: &[PathBuf]) -> String {
        let names: Vec<String> = watch_paths
            .iter()
            .map(|p| {
                p.file_name()
                    .map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().to_string())
            })
            .collect();
        let label = if names.len() <= 3 {
            names.join(",")
        } else {
            format!("{} files", names.len())
        };
        let tag = format!("[{label}]");

        if io::stderr().is_terminal() && !Self::is_no_color() {
            tag.cyan().bold().to_string()
        } else {
            tag
        }
    }

    #[cfg(feature = "watch")]
    fn watch_divider() -> String {
        let line = "─".repeat(40);
        if io::stderr().is_terminal() && !Self::is_no_color() {
            line.dimmed().to_string()
        } else {
            line
        }
    }

    /// Watches each target's parent dir (not the file itself) and filters by filename,
    /// since editors that save via delete-and-rename would break a watch on the file's inode.
    #[cfg(feature = "watch")]
    fn run_watch(&self) -> miette::Result<()> {
        use notify::Watcher as _;

        let watch_paths = self.watch_targets()?;
        let targets: rustc_hash::FxHashSet<(PathBuf, OsString)> = watch_paths
            .iter()
            .filter_map(|p| {
                p.file_name()
                    .map(|name| (Self::canonical_parent_dir(p), name.to_os_string()))
            })
            .collect();

        eprintln!(
            "{} Watching for changes. Press Ctrl-C to stop.",
            Self::watch_badge(&watch_paths)
        );
        self.run_once_watch();

        let (tx, rx) = mpsc::channel::<PathBuf>();
        let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
            if let Ok(event) = res {
                for path in event.paths {
                    let _ = tx.send(path);
                }
            }
        })
        .map_err(|e| miette!("Failed to start file watcher: {e}"))?;

        let mut watched_dirs = BTreeSet::new();
        for path in &watch_paths {
            let dir = Self::canonical_parent_dir(path);
            if watched_dirs.insert(dir.clone()) {
                watcher
                    .watch(&dir, notify::RecursiveMode::NonRecursive)
                    .map_err(|e| miette!("Failed to watch {}: {e}", dir.display()))?;
            }
        }

        loop {
            let Ok(first) = rx.recv() else {
                return Ok(());
            };

            // Debounce: a single save often fires several fs events in quick
            // succession (write + rename, etc.); coalesce them into one re-run.
            let mut changed = vec![first];
            while let Ok(path) = rx.recv_timeout(Duration::from_millis(150)) {
                changed.push(path);
            }

            let relevant = changed.iter().any(|p| {
                p.file_name()
                    .is_some_and(|name| targets.contains(&(Self::canonical_parent_dir(p), name.to_os_string())))
            });

            if relevant {
                eprintln!(
                    "\n{}\n{} Changed, re-running...",
                    Self::watch_divider(),
                    Self::watch_badge(&watch_paths)
                );
                self.run_once_watch();
            }
        }
    }

    fn process_batch(&self) -> Result<(), miette::Error> {
        let query = self.get_query()?;
        let files = self.read_contents()?;

        if self.output.count {
            return self.process_batch_count(&query, &files);
        }

        if self.input.eval_all {
            return self.execute_eval_all(&query, &files);
        }

        if files.len() > self.parallel_threshold {
            files.par_iter().try_for_each(|(file, content)| {
                let mut engine = self.create_engine()?;
                self.execute(&mut engine, &query, file, content)
            })?;
        } else {
            let mut engine = self.create_engine()?;

            // Pre-compile query if all files share the same effective query (same prefix)
            if files.len() > 1 && self.all_files_same_prefix(&files) && self.output.separator.is_none() {
                let effective = self.effective_query(&query, &files[0].0);
                let program = engine.compile(&effective).map_err(|e| *e)?;
                for (file, content) in &files {
                    self.execute_compiled(&mut engine, &program, file, content)?;
                }
            } else {
                files
                    .iter()
                    .try_for_each(|(file, content)| self.execute(&mut engine, &query, file, content))?;
            }
        }

        Ok(())
    }

    /// `__FILE__`-family vars aren't set here: no single file is "current" once combined.
    fn execute_eval_all(&self, query: &str, files: &[(Option<PathBuf>, ContentData)]) -> miette::Result<()> {
        if !self.all_files_same_prefix(files) {
            return Err(miette!(
                "--eval-all requires all input files to use the same input format"
            ));
        }

        let effective_query = self.effective_query(query, files.first().map(|(f, _)| f).unwrap_or(&None));
        let mut engine = self.create_engine()?;

        let mut combined_input = Vec::new();
        for (file, content) in files {
            combined_input.extend(self.resolve_input(file, content)?);
        }

        let is_grep = matches!(self.output.output_format, OutputFormat::Grep);
        let grep_input: Option<Vec<mq_lang::RuntimeValue>> = is_grep.then(|| combined_input.clone());

        let runtime_values = engine
            .eval(&effective_query, combined_input.into_iter())
            .map_err(|e| *e)?;

        self.emit_results(runtime_values, grep_input, &None)
    }

    fn execute_compiled(
        &self,
        engine: &mut mq_lang::DefaultEngine,
        program: &mq_lang::CompiledProgram,
        file: &Option<PathBuf>,
        content: &ContentData,
    ) -> miette::Result<()> {
        if let Some(f) = file {
            self.set_file_vars(engine, f);
        }

        let input = self.resolve_input(file, content)?;
        let is_grep = matches!(self.output.output_format, OutputFormat::Grep);
        let grep_input: Option<Vec<mq_lang::RuntimeValue>> = is_grep.then(|| input.clone());

        let runtime_values = if self.output.update {
            let results = engine
                .eval_compiled(program, input.clone().into_iter())
                .map_err(|e| *e)?;
            self.apply_update(input, results)?
        } else {
            engine.eval_compiled(program, input.into_iter()).map_err(|e| *e)?
        };

        if self.output.update && self.output.diff {
            return self.emit_diff(&runtime_values, file, content);
        }

        self.emit_results(runtime_values, grep_input, file)
    }

    fn count_file(
        &self,
        engine: &mut mq_lang::DefaultEngine,
        query: &str,
        file: &Option<PathBuf>,
        content: &ContentData,
    ) -> miette::Result<usize> {
        let effective_query;
        let query = match self.auto_query_prefix(file) {
            Some(prefix) => {
                effective_query = format!("{} | {}", prefix, query);
                effective_query.as_str()
            }
            None => query,
        };
        if let Some(f) = file {
            self.set_file_vars(engine, f);
        }
        let input = self.resolve_input(file, content)?;
        let runtime_values = engine.eval(query, input.into_iter()).map_err(|e| *e)?;
        Ok(self.output.paginate(runtime_values.compact()).len())
    }

    fn process_batch_count(&self, query: &str, files: &[(Option<PathBuf>, ContentData)]) -> miette::Result<()> {
        let multiple_files = files.len() > 1;
        let mut total = 0usize;
        let mut engine = self.create_engine()?;

        let stdout = io::stdout();
        let mut handle: Box<dyn Write> = if let Some(output_file) = &self.output.output_file {
            let file = fs::File::create(output_file).into_diagnostic()?;
            Box::new(BufWriter::new(file))
        } else if self.output.unbuffered {
            Box::new(stdout.lock())
        } else {
            Box::new(BufWriter::new(stdout.lock()))
        };

        for (file, content) in files {
            let count = self.count_file(&mut engine, query, file, content)?;
            total += count;
            if multiple_files {
                let name = file
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|| "(stdin)".to_string());
                Self::write_ignore_pipe(&mut handle, format!("{}: {}\n", name, count).as_bytes())?;
            }
        }

        if multiple_files {
            Self::write_ignore_pipe(&mut handle, format!("total: {}\n", total).as_bytes())?;
        } else {
            Self::write_ignore_pipe(&mut handle, format!("{}\n", total).as_bytes())?;
        }

        if !self.output.unbuffered
            && let Err(e) = handle.flush()
            && e.kind() != std::io::ErrorKind::BrokenPipe
        {
            return Err(miette!(e));
        }

        Ok(())
    }

    fn process_streaming(&self) -> miette::Result<()> {
        if self.is_binary_format() {
            return Err(miette!(
                "Streaming mode is not supported for binary input formats (bytes, cbor)"
            ));
        }
        let query = self.get_query()?;
        let mut engine = self.create_engine()?;

        self.process_lines(|file, line| self.execute(&mut engine, &query, &file.cloned(), &line.into()))
    }

    fn process_lines<F>(&self, mut process: F) -> miette::Result<()>
    where
        F: FnMut(Option<&PathBuf>, String) -> miette::Result<()>,
    {
        // If files are specified, process each file line by line
        if let Some(files) = &self.files {
            for file in files {
                let file_handle = fs::File::open(file).into_diagnostic()?;
                let reader = io::BufReader::new(file_handle);
                for line_result in reader.lines() {
                    let line = line_result.into_diagnostic()?;
                    process(Some(file), line)?;
                }
            }
        } else {
            // Otherwise, process stdin line by line
            let stdin = io::stdin();
            let reader = io::BufReader::new(stdin.lock());
            for line_result in reader.lines() {
                let line = line_result.into_diagnostic()?;
                process(None, line)?;
            }
        }
        Ok(())
    }

    fn is_binary_format(&self) -> bool {
        matches!(
            self.input.input_format,
            Some(InputFormat::Bytes) | Some(InputFormat::Cbor)
        )
    }

    fn needs_binary_read_for_file(&self, file: &Path) -> bool {
        self.input
            .input_format
            .as_ref()
            .map(|fmt| fmt.needs_binary_read())
            .unwrap_or_else(|| {
                let ext = file.extension().unwrap_or_default().to_string_lossy().to_lowercase();
                InputFormat::from_extension(&ext).needs_binary_read()
            })
    }

    /// Reads each file's raw content, choosing binary or text mode per-file based on its
    /// detected format. Shared by `read_contents` and the `repl` subcommand's file-seeding.
    fn read_files_content(&self, files: &[PathBuf]) -> miette::Result<Vec<(Option<PathBuf>, ContentData)>> {
        files
            .iter()
            .map(|file| {
                let content: ContentData = if self.needs_binary_read_for_file(file) {
                    fs::read(file).map(Into::into).into_diagnostic()?
                } else {
                    fs::read_to_string(file).map(Into::into).into_diagnostic()?
                };
                Ok((Some(file.clone()), content))
            })
            .collect()
    }

    fn read_contents(&self) -> miette::Result<Vec<(Option<PathBuf>, ContentData)>> {
        if matches!(self.input.input_format, Some(InputFormat::Null)) {
            return Ok(vec![(None, ContentData::empty())]);
        }

        self.files
            .clone()
            .map(|files| self.read_files_content(&files))
            .unwrap_or_else(|| {
                if io::stdin().is_terminal() {
                    return Ok(vec![(None, ContentData::empty())]);
                }

                if self.is_binary_format() {
                    let mut buf = Vec::new();
                    io::stdin().read_to_end(&mut buf).into_diagnostic()?;
                    Ok(vec![(None, buf.into())])
                } else {
                    let mut input = String::new();
                    io::stdin().read_to_string(&mut input).into_diagnostic()?;
                    Ok(vec![(None, input.into())])
                }
            })
    }

    /// Returns `true` if the `NO_COLOR` environment variable is set and non-empty.
    fn is_no_color() -> bool {
        std::env::var("NO_COLOR").is_ok_and(|v| !v.is_empty())
    }

    #[inline(always)]
    fn write_ignore_pipe<W: Write>(handle: &mut W, data: &[u8]) -> miette::Result<()> {
        match handle.write_all(data) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => Ok(()),
            Err(e) => Err(miette!(e)),
        }
    }

    /// Recursively collects Markdown nodes from a `RuntimeValue`.
    ///
    /// Flattens nested `Array` values so that any Markdown nodes contained
    /// within are returned as a flat list.
    fn collect_markdown_nodes(value: &mq_lang::RuntimeValue, nodes: &mut Vec<mq_markdown::Node>) {
        match value {
            mq_lang::RuntimeValue::Markdown(node, _) => nodes.push((**node).clone()),
            mq_lang::RuntimeValue::Array(items) => {
                for item in items.iter() {
                    Self::collect_markdown_nodes(item, nodes);
                }
            }
            _ => {}
        }
    }

    /// Returns `true` if the dict is a known expandable typed dict (has `type: :symbol`).
    fn is_typed_dict(map: &std::collections::BTreeMap<mq_lang::Ident, mq_lang::RuntimeValue>) -> bool {
        let type_key = mq_lang::Ident::new("type");
        matches!(
            map.get(&type_key),
            Some(mq_lang::RuntimeValue::Symbol(s)) if matches!(s.as_str().as_str(), "section" | "table")
        )
    }

    /// Expands a typed dict (one with `type: :symbol`) into Markdown nodes.
    ///
    /// Returns `None` if the dict is not a known expandable type.
    /// To add support for a new type, add a match arm for the type name.
    fn expand_typed_dict(
        map: &std::collections::BTreeMap<mq_lang::Ident, mq_lang::RuntimeValue>,
    ) -> Option<Vec<mq_markdown::Node>> {
        let type_key = mq_lang::Ident::new("type");
        match map.get(&type_key) {
            Some(mq_lang::RuntimeValue::Symbol(s)) => match s.as_str().as_str() {
                "section" => {
                    let mut nodes = Vec::new();
                    if let Some(header) = map.get(&mq_lang::Ident::new("header")) {
                        Self::collect_markdown_nodes(header, &mut nodes);
                    }
                    if let Some(children) = map.get(&mq_lang::Ident::new("children")) {
                        Self::collect_markdown_nodes(children, &mut nodes);
                    }
                    Some(nodes)
                }
                "table" => {
                    // Reconstruct table nodes in the same order as table::to_markdown():
                    // header cells + align row + flattened data rows
                    let mut nodes = Vec::new();
                    if let Some(header) = map.get(&mq_lang::Ident::new("header")) {
                        Self::collect_markdown_nodes(header, &mut nodes);
                    }
                    if let Some(align) = map.get(&mq_lang::Ident::new("align")) {
                        Self::collect_markdown_nodes(align, &mut nodes);
                    }
                    if let Some(rows) = map.get(&mq_lang::Ident::new("rows")) {
                        Self::collect_markdown_nodes(rows, &mut nodes);
                    }
                    Some(nodes)
                }
                // To add a new expandable type: add a match arm here.
                _ => None,
            },
            _ => None,
        }
    }

    /// Returns true if a RuntimeValue is considered "falsy" for --exit-status.
    /// Mirrors jq's definition (false and null are falsy) but also treats
    /// empty values as falsy: `select()` on markdown input doesn't drop
    /// non-matching nodes, it replaces them with an empty `Markdown` value,
    /// so a plain `None`/`Boolean(false)` check alone would never observe
    /// the common "no match" case.
    fn is_falsy(value: &mq_lang::RuntimeValue) -> bool {
        matches!(value, mq_lang::RuntimeValue::Boolean(false)) || value.is_empty()
    }

    /// Converts a `RuntimeValue` into a list of Markdown nodes.
    fn runtime_value_to_nodes(runtime_value: &mq_lang::RuntimeValue) -> Vec<mq_markdown::Node> {
        match runtime_value {
            mq_lang::RuntimeValue::Markdown(node, _) => vec![(**node).clone()],
            mq_lang::RuntimeValue::Dict(map) => {
                Self::expand_typed_dict(map).unwrap_or_else(|| vec![runtime_value.to_string().into()])
            }
            mq_lang::RuntimeValue::Array(items) => {
                let has_expandable = items.iter().any(|v| match v {
                    mq_lang::RuntimeValue::Markdown(_, _) => true,
                    mq_lang::RuntimeValue::Dict(m) => Self::is_typed_dict(m),
                    _ => false,
                });
                if has_expandable {
                    items.iter().flat_map(Self::runtime_value_to_nodes).collect()
                } else if items.is_empty() {
                    vec![]
                } else {
                    vec![runtime_value.to_string().into()]
                }
            }
            _ => vec![runtime_value.to_string().into()],
        }
    }

    /// Clears position information from a Markdown value's node (recursively);
    /// other value kinds are passed through unchanged. Used by `--no-position`.
    fn strip_markdown_position(value: mq_lang::RuntimeValue) -> mq_lang::RuntimeValue {
        match value {
            mq_lang::RuntimeValue::Markdown(mut node, meta) => {
                node.strip_positions();
                mq_lang::RuntimeValue::Markdown(node, meta)
            }
            other => other,
        }
    }

    fn build_markdown(&self, runtime_values: &[mq_lang::RuntimeValue]) -> mq_markdown::Markdown {
        let mut markdown =
            mq_markdown::Markdown::new(runtime_values.iter().flat_map(Self::runtime_value_to_nodes).collect());
        markdown.set_options(mq_markdown::RenderOptions {
            list_style: match self.output.list_style.clone() {
                ListStyle::Dash => mq_markdown::ListStyle::Dash,
                ListStyle::Plus => mq_markdown::ListStyle::Plus,
                ListStyle::Star => mq_markdown::ListStyle::Star,
            },
            link_title_style: match self.output.link_title_style.clone() {
                LinkTitleStyle::Double => mq_markdown::TitleSurroundStyle::Double,
                LinkTitleStyle::Single => mq_markdown::TitleSurroundStyle::Single,
                LinkTitleStyle::Paren => mq_markdown::TitleSurroundStyle::Paren,
            },
            link_url_style: match self.output.link_url_style.clone() {
                LinkUrlStyle::None => mq_markdown::UrlSurroundStyle::None,
                LinkUrlStyle::Angle => mq_markdown::UrlSurroundStyle::Angle,
            },
        });
        markdown
    }

    /// Renders `runtime_values` to a byte buffer without writing anywhere.
    /// `emit_diff` always passes `colorize: false` — it needs plain text to diff
    /// against the uncolored original, and colors the diff lines itself.
    fn render(&self, runtime_values: &[mq_lang::RuntimeValue], colorize: bool) -> miette::Result<Vec<u8>> {
        let mut buf = Vec::new();

        match self.output.output_format {
            OutputFormat::Raw => {
                for value in runtime_values {
                    match value {
                        mq_lang::RuntimeValue::Bytes(b) => buf.extend_from_slice(b),
                        _ => buf.extend_from_slice(value.to_string().as_bytes()),
                    }
                }
            }
            OutputFormat::Json => {
                let theme = colorize.then(mq_markdown::ColorTheme::from_env);
                let json_str = crate::output::json::runtime_values_to_json(runtime_values, theme.as_ref())?;
                buf.extend_from_slice(json_str.as_bytes());
            }
            OutputFormat::Html => {
                let markdown = self.build_markdown(runtime_values);
                buf.extend_from_slice(markdown.to_html().as_bytes());
            }
            OutputFormat::Text => {
                let markdown = self.build_markdown(runtime_values);
                buf.extend_from_slice(markdown.to_text().as_bytes());
            }
            OutputFormat::Markdown if colorize => {
                let markdown = self.build_markdown(runtime_values);
                let theme = mq_markdown::ColorTheme::from_env();
                buf.extend_from_slice(markdown.to_colored_string_with_theme(&theme).as_bytes());
            }
            OutputFormat::Markdown => {
                let markdown = self.build_markdown(runtime_values);
                buf.extend_from_slice(markdown.to_string().as_bytes());
            }
            OutputFormat::Table => {
                let theme = colorize.then(mq_markdown::ColorTheme::from_env);
                let table = crate::output::table::runtime_values_to_table(runtime_values, theme.as_ref());
                buf.extend_from_slice(format!("{}\n", table).as_bytes());
            }
            OutputFormat::Grep => {
                let markdown = self.build_markdown(runtime_values);
                buf.extend_from_slice(markdown.to_string().as_bytes());
            }
            OutputFormat::Gron => {
                let gron_str = crate::output::gron::runtime_values_to_gron(runtime_values);
                buf.extend_from_slice(gron_str.as_bytes());
            }
            OutputFormat::Csv => {
                let csv_str = crate::output::csv::runtime_values_to_csv(runtime_values)?;
                buf.extend_from_slice(csv_str.as_bytes());
            }
            OutputFormat::Toml => {
                let toml_str = crate::output::toml::runtime_values_to_toml(runtime_values)?;
                buf.extend_from_slice(toml_str.as_bytes());
            }
            OutputFormat::Toon => {
                let toon_str = crate::output::toon::runtime_values_to_toon(runtime_values)?;
                buf.extend_from_slice(toon_str.as_bytes());
            }
            OutputFormat::Xml => {
                let xml_str = crate::output::xml::runtime_values_to_xml(runtime_values)?;
                buf.extend_from_slice(xml_str.as_bytes());
            }
            OutputFormat::Yaml => {
                let yaml_str = crate::output::yaml::runtime_values_to_yaml(runtime_values)?;
                buf.extend_from_slice(yaml_str.as_bytes());
            }
            OutputFormat::Shell => {
                let shell_str = crate::output::shell::runtime_values_to_shell(runtime_values);
                buf.extend_from_slice(shell_str.as_bytes());
            }
            OutputFormat::None => {}
        }

        Ok(buf)
    }

    fn print(&self, runtime_values: mq_lang::RuntimeValues) -> miette::Result<()> {
        let stdout = io::stdout();
        let mut handle: Box<dyn Write> = if let Some(output_file) = &self.output.output_file {
            let file = fs::File::create(output_file).into_diagnostic()?;
            Box::new(BufWriter::new(file))
        } else if self.output.unbuffered {
            Box::new(stdout.lock())
        } else {
            Box::new(BufWriter::new(stdout.lock()))
        };
        let stripped_values: Option<Vec<mq_lang::RuntimeValue>> = self.output.no_position.then(|| {
            runtime_values
                .values()
                .iter()
                .cloned()
                .map(Self::strip_markdown_position)
                .collect()
        });
        let runtime_values: &[mq_lang::RuntimeValue] = stripped_values.as_deref().unwrap_or(runtime_values.values());

        // Track truthy output for --exit-status.
        if self.output.exit_status && runtime_values.iter().any(|v| !Self::is_falsy(v)) {
            HAD_TRUTHY_OUTPUT.store(true, Ordering::Relaxed);
        }

        let colorize = self.output.color_output && !Self::is_no_color();
        let buf = self.render(runtime_values, colorize)?;
        Self::write_ignore_pipe(&mut handle, &buf)?;

        if !self.output.unbuffered
            && let Err(e) = handle.flush()
            && e.kind() != std::io::ErrorKind::BrokenPipe
        {
            return Err(miette!(e));
        }

        Ok(())
    }

    /// Renders what `--update` would print and diffs it against the original input.
    fn emit_diff(
        &self,
        runtime_values: &mq_lang::RuntimeValues,
        file: &Option<PathBuf>,
        content: &ContentData,
    ) -> miette::Result<()> {
        let original = content.as_str().unwrap_or("");
        let rendered = self.render(runtime_values.values(), false)?;
        let rendered = String::from_utf8_lossy(&rendered);

        if original != rendered {
            HAD_DIFF.store(true, Ordering::Relaxed);
            self.print_unified_diff(original, &rendered, file)?;
        }

        Ok(())
    }

    /// Prints a unified diff of `original` vs `rendered` to stdout (or `-o`), headed
    /// by the file path (or `<stdin>` when there is none). Colorizes `+`/`-`/`@@`
    /// lines when `-C`/`--color-output` is set and `NO_COLOR` isn't.
    fn print_unified_diff(&self, original: &str, rendered: &str, file: &Option<PathBuf>) -> miette::Result<()> {
        let stdout = io::stdout();
        let mut handle: Box<dyn Write> = if let Some(output_file) = &self.output.output_file {
            let file = fs::File::create(output_file).into_diagnostic()?;
            Box::new(BufWriter::new(file))
        } else if self.output.unbuffered {
            Box::new(stdout.lock())
        } else {
            Box::new(BufWriter::new(stdout.lock()))
        };

        let label = file
            .as_ref()
            .map(|f| f.display().to_string())
            .unwrap_or_else(|| "<stdin>".to_string());

        let diff_text = similar::TextDiff::from_lines(original, rendered)
            .unified_diff()
            .header(&label, &label)
            .to_string();

        // Raw ANSI, not `colored::Colorize` — it auto-disables on non-tty stdout, but -C should force color.
        let colorize = self.output.color_output && !Self::is_no_color();
        let mut out = String::with_capacity(diff_text.len());
        for line in diff_text.lines() {
            if colorize && line.starts_with('+') && !line.starts_with("+++") {
                out.push_str("\x1b[32m");
                out.push_str(line);
                out.push_str("\x1b[0m");
            } else if colorize && line.starts_with('-') && !line.starts_with("---") {
                out.push_str("\x1b[31m");
                out.push_str(line);
                out.push_str("\x1b[0m");
            } else if colorize && line.starts_with("@@") {
                out.push_str("\x1b[36m");
                out.push_str(line);
                out.push_str("\x1b[0m");
            } else {
                out.push_str(line);
            }
            out.push('\n');
        }

        Self::write_ignore_pipe(&mut handle, out.as_bytes())?;

        if !self.output.unbuffered
            && let Err(e) = handle.flush()
            && e.kind() != std::io::ErrorKind::BrokenPipe
        {
            return Err(miette!(e));
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use scopeguard::defer;
    use std::io::Write;
    use std::{fs::File, path::PathBuf};

    use super::*;

    fn create_file(name: &str, content: &str) -> (PathBuf, PathBuf) {
        let temp_dir = std::env::temp_dir();
        let temp_file_path = temp_dir.join(name);
        let mut file = File::create(&temp_file_path).expect("Failed to create temp file");
        file.write_all(content.as_bytes())
            .expect("Failed to write to temp file");

        (temp_dir, temp_file_path)
    }

    #[test]
    fn test_cli_null_input() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some("self".to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_allow_read_flag_gates_read_file() {
        let (_, temp_file_path) = create_file("test_allow_read.md", "hello");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).expect("Failed to delete temp file");
            }
        }

        let query = format!("read_file(\"{}\")", temp_file_path.to_string_lossy());

        let blocked_cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query.clone()),
            files: None,
            ..Cli::default()
        };
        assert!(
            blocked_cli.run().is_err(),
            "read_file should be blocked without --allow-read"
        );

        let allowed_cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                allow_read: Some(vec![]),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query),
            files: None,
            ..Cli::default()
        };
        assert!(allowed_cli.run().is_ok(), "read_file should succeed with --allow-read");
    }

    #[test]
    fn test_allow_run_flag_gates_system() {
        let query = "system(\"echo\", [\"hello\"])";

        let blocked_cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query.to_string()),
            files: None,
            ..Cli::default()
        };
        assert!(
            blocked_cli.run().is_err(),
            "system should be blocked without --allow-run"
        );

        let allowed_cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                allow_run: Some(vec![]),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query.to_string()),
            files: None,
            ..Cli::default()
        };
        assert!(allowed_cli.run().is_ok(), "system should succeed with --allow-run");

        let restricted_cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                allow_run: Some(vec!["ls".to_string()]),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query.to_string()),
            files: None,
            ..Cli::default()
        };
        assert!(
            restricted_cli.run().is_err(),
            "system should be blocked when --allow-run only names other commands"
        );
    }

    #[test]
    fn test_allow_env_flag_gates_var_interpolation() {
        // SAFETY: no other threads read/write this env var concurrently in this test.
        unsafe { std::env::set_var("MQ_ALLOW_ENV_TEST_VAR", "test_value") };
        defer! {
            unsafe { std::env::remove_var("MQ_ALLOW_ENV_TEST_VAR") };
        }

        let query = "$MQ_ALLOW_ENV_TEST_VAR";

        let blocked_cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query.to_string()),
            files: None,
            ..Cli::default()
        };
        assert!(blocked_cli.run().is_err(), "$VAR should be blocked without --allow-env");

        let allowed_cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                allow_env: Some(vec![]),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query.to_string()),
            files: None,
            ..Cli::default()
        };
        assert!(allowed_cli.run().is_ok(), "$VAR should succeed with --allow-env");

        let restricted_cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                allow_env: Some(vec!["MQ_OTHER_VAR".to_string()]),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query.to_string()),
            files: None,
            ..Cli::default()
        };
        assert!(
            restricted_cli.run().is_err(),
            "$VAR should be blocked when --allow-env only names other variables"
        );
    }

    #[test]
    fn test_allow_all_flag_grants_every_capability() {
        // SAFETY: no other threads read/write this env var concurrently in this test.
        unsafe { std::env::set_var("MQ_ALLOW_ALL_TEST_VAR", "test_value") };
        defer! {
            unsafe { std::env::remove_var("MQ_ALLOW_ALL_TEST_VAR") };
        }

        let base_cli = |query: &str, allow_all: bool| Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                allow_all,
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query.to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(
            base_cli("$MQ_ALLOW_ALL_TEST_VAR", false).run().is_err(),
            "$VAR should be blocked without --allow-all"
        );
        assert!(
            base_cli("$MQ_ALLOW_ALL_TEST_VAR", true).run().is_ok(),
            "$VAR should succeed with --allow-all"
        );

        let system_query = "system(\"echo\", [\"hi\"])";
        assert!(
            base_cli(system_query, false).run().is_err(),
            "system should be blocked without --allow-all"
        );
        assert!(
            base_cli(system_query, true).run().is_ok(),
            "system should succeed with --allow-all"
        );
    }

    #[rstest]
    #[case(&["mq", "--allow-all", "--allow-read=/tmp", "self"])]
    #[case(&["mq", "--allow-all", "--allow-write=/tmp", "self"])]
    #[case(&["mq", "--allow-all", "--allow-net=example.com", "self"])]
    #[case(&["mq", "--allow-all", "--allow-run", "self"])]
    #[case(&["mq", "--allow-all", "--allow-env", "self"])]
    #[case(&["mq", "--allow-all", "--allow-http-import", "self"])]
    fn test_allow_all_conflicts_with_individual_allow_flags(#[case] args: &[&str]) {
        assert!(
            Cli::try_parse_from(args).is_err(),
            "--allow-all should conflict with individual --allow-* flags"
        );
    }

    #[cfg(feature = "http-import")]
    #[test]
    fn test_http_import_disabled_by_default() {
        // No network call is made: resolution fails on the enabled-check before any
        // request, so this stays fast and deterministic regardless of connectivity.
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(r#"import "github.com/harehare/lisp""#.to_string()),
            files: None,
            ..Cli::default()
        };

        let err = cli.run().unwrap_err();
        assert!(
            err.to_string().contains("HTTP module imports are disabled"),
            "error was: {err}"
        );
    }

    #[cfg(feature = "http-import")]
    #[test]
    fn test_allowed_domain_alone_does_not_enable_http_import() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                allowed_domains: Some(vec!["example.com".to_string()]),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(r#"import "https://example.com/mod.mq""#.to_string()),
            files: None,
            ..Cli::default()
        };

        let err = cli.run().unwrap_err();
        assert!(
            err.to_string().contains("HTTP module imports are disabled"),
            "error was: {err}"
        );
    }

    #[cfg(feature = "http-import")]
    #[test]
    fn test_no_lockfile_conflicts_with_frozen() {
        assert!(
            Cli::try_parse_from(["mq", "--no-lockfile", "--frozen", "self"]).is_err(),
            "--no-lockfile should conflict with --frozen"
        );
    }

    #[rstest]
    #[case(0.0)]
    #[case(-1.0)]
    fn test_timeout_rejects_non_positive(#[case] secs: f64) {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some("1".to_string()),
            files: None,
            timeout: Some(secs),
            ..Cli::default()
        };

        assert!(cli.run().is_err());
    }

    #[test]
    fn test_timeout_aborts_infinite_loop() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some("while(true): 1;".to_string()),
            files: None,
            timeout: Some(0.001),
            ..Cli::default()
        };

        assert!(cli.run().is_err());
    }

    #[test]
    fn test_timeout_allows_normal_query() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some("1 + 1".to_string()),
            files: None,
            timeout: Some(5.0),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_cli_raw_input() {
        let (_, temp_file_path) = create_file("test1.md", "# test");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).expect("Failed to delete temp file");
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Text),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_cli_output_formats() {
        let (_, temp_file_path) = create_file("test2.md", "# test");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).expect("Failed to delete temp file");
            }
        }

        for format in [
            OutputFormat::Markdown,
            OutputFormat::Html,
            OutputFormat::Text,
            OutputFormat::Table,
            OutputFormat::Grep,
            OutputFormat::Gron,
            OutputFormat::Csv,
            OutputFormat::Xml,
            OutputFormat::Yaml,
            OutputFormat::Toon,
            OutputFormat::Shell,
        ] {
            let cli = Cli {
                input: InputArgs::default(),
                output: OutputArgs {
                    output_format: format.clone(),
                    ..Default::default()
                },
                commands: None,
                query: Some("self".to_string()),
                files: Some(vec![temp_file_path.clone()]),
                ..Cli::default()
            };

            assert!(cli.run().is_ok());
        }
    }

    #[test]
    fn test_cli_list_styles() {
        let (_, temp_file_path) = create_file("test3.md", "# test");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).expect("Failed to delete temp file");
            }
        }

        for style in [ListStyle::Dash, ListStyle::Plus, ListStyle::Star] {
            let cli = Cli {
                input: InputArgs::default(),
                output: OutputArgs {
                    list_style: style.clone(),
                    ..Default::default()
                },
                commands: None,
                query: Some("self".to_string()),
                files: Some(vec![temp_file_path.clone()]),
                ..Cli::default()
            };

            assert!(cli.run().is_ok());
        }
    }

    #[test]
    fn test_cli_color_output() {
        let (_, temp_file_path) = create_file("test_color.md", "# test");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).expect("Failed to delete temp file");
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                color_output: true,
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path.clone()]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_cli_update_flag() {
        let (_, temp_file_path) = create_file("test4.md", "# test");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).expect("Failed to delete temp file");
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                update: true,
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_cli_with_module_names() {
        let (temp_dir, temp_file_path) = create_file("math.mq", "def math(): 42;");
        let (_, temp_md_file_path) = create_file("test.md", "# test");
        let temp_md_file_path_clone = temp_md_file_path.clone();

        defer! {
            if temp_file_path.exists() {
                std::fs::remove_file(&temp_file_path).expect("Failed to delete temp file");
            }

            if temp_md_file_path_clone.exists() {
                std::fs::remove_file(&temp_md_file_path_clone).expect("Failed to delete temp file");
            }
        }

        let cli = Cli {
            input: InputArgs {
                module_names: Some(vec!["math".to_string()]),
                module_directories: Some(vec![temp_dir.clone()]),
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some("math".to_owned()),
            files: Some(vec![temp_md_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_find_external_commands() {
        // find_external_commands searches ~/.local/bin and PATH for mq-* files
        let commands = Cli::find_external_commands();
        // We can't assert specific commands, but we can check the function works
        assert!(commands.iter().all(|cmd| !cmd.is_empty()));
    }

    #[test]
    fn test_get_external_commands_dir() {
        // This test checks if the function returns a valid path or None
        let dir = Cli::get_external_commands_dir();
        if let Some(path) = dir {
            assert!(path.ends_with(".local/bin") || path.ends_with(".local\\bin"));
        }
    }

    #[test]
    #[cfg(unix)]
    fn test_collect_mq_commands_from_dir() {
        let temp_dir = std::env::temp_dir().join("mq-collect-test");
        fs::create_dir_all(&temp_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        // Create test files: mq-foo, mq-bar, a non-mq file, and a non-executable mq file
        fs::write(temp_dir.join("mq-foo"), "").expect("Failed to write file");
        fs::write(temp_dir.join("mq-bar"), "").expect("Failed to write file");
        fs::write(temp_dir.join("other-cmd"), "").expect("Failed to write file");
        fs::write(temp_dir.join("mq-noexec"), "").expect("Failed to write file");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            // Set executable bit on mq-foo and mq-bar, but not mq-noexec
            fs::set_permissions(temp_dir.join("mq-foo"), fs::Permissions::from_mode(0o755))
                .expect("Failed to set permissions");
            fs::set_permissions(temp_dir.join("mq-bar"), fs::Permissions::from_mode(0o755))
                .expect("Failed to set permissions");
        }

        let mut seen = std::collections::HashSet::new();
        Cli::collect_mq_commands_from_dir(&temp_dir, &mut seen);

        assert_eq!(seen.len(), 2);
        assert!(seen.contains("foo"));
        assert!(seen.contains("bar"));
        assert!(!seen.contains("other-cmd"));
        assert!(!seen.contains("noexec"));
    }

    #[test]
    #[cfg(unix)]
    fn test_collect_mq_commands_from_dir_deduplicates() {
        let dir1 = std::env::temp_dir().join("mq-dedup-test-1");
        let dir2 = std::env::temp_dir().join("mq-dedup-test-2");
        fs::create_dir_all(&dir1).expect("Failed to create test directory");
        fs::create_dir_all(&dir2).expect("Failed to create test directory");

        defer! {
            if dir1.exists() {
                std::fs::remove_dir_all(&dir1).ok();
            }
            if dir2.exists() {
                std::fs::remove_dir_all(&dir2).ok();
            }
        }

        // Same command in both directories
        fs::write(dir1.join("mq-dup"), "").expect("Failed to write file");
        fs::write(dir2.join("mq-dup"), "").expect("Failed to write file");
        fs::write(dir2.join("mq-unique"), "").expect("Failed to write file");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(dir1.join("mq-dup"), fs::Permissions::from_mode(0o755))
                .expect("Failed to set permissions");
            fs::set_permissions(dir2.join("mq-dup"), fs::Permissions::from_mode(0o755))
                .expect("Failed to set permissions");
            fs::set_permissions(dir2.join("mq-unique"), fs::Permissions::from_mode(0o755))
                .expect("Failed to set permissions");
        }

        let mut seen = std::collections::HashSet::new();
        Cli::collect_mq_commands_from_dir(&dir1, &mut seen);
        Cli::collect_mq_commands_from_dir(&dir2, &mut seen);

        assert_eq!(seen.len(), 2);
        assert!(seen.contains("dup"));
        assert!(seen.contains("unique"));
    }

    #[test]
    fn test_collect_mq_commands_from_nonexistent_dir() {
        let nonexistent = std::env::temp_dir().join("mq-nonexistent-dir");
        let mut seen = std::collections::HashSet::new();
        // Should not panic on nonexistent directory
        Cli::collect_mq_commands_from_dir(&nonexistent, &mut seen);
        assert!(seen.is_empty());
    }

    #[rstest]
    #[case("foo", "foo")]
    #[case("foo.exe", "foo.exe")]
    #[case("foo.cmd", "foo.cmd")]
    #[case("foo.bat", "foo.bat")]
    #[case("foo.sh", "foo.sh")]
    #[cfg(not(windows))]
    fn test_strip_executable_extension_unix(#[case] input: &str, #[case] expected: &str) {
        assert_eq!(Cli::strip_executable_extension(input), expected);
    }

    #[rstest]
    #[case("foo.exe", "foo")]
    #[case("foo.cmd", "foo")]
    #[case("foo.bat", "foo")]
    #[case("foo.com", "foo")]
    #[case("foo", "foo")]
    #[case("foo.sh", "foo.sh")]
    #[case("foo.txt", "foo.txt")]
    #[cfg(windows)]
    fn test_strip_executable_extension_windows(#[case] input: &str, #[case] expected: &str) {
        assert_eq!(Cli::strip_executable_extension(input), expected);
    }

    #[test]
    fn test_external_command_execution() {
        // Create a temporary directory for testing
        let temp_dir = std::env::temp_dir().join("mq-run-test");
        let bin_dir = temp_dir.join(".mq").join("bin");
        fs::create_dir_all(&bin_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        // Create a test external command
        let test_cmd_path = bin_dir.join("mq-testcmd");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::write(&test_cmd_path, "#!/bin/sh\necho 'test output'").expect("Failed to write test command");
            let mut perms = fs::metadata(&test_cmd_path)
                .expect("Failed to get metadata")
                .permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&test_cmd_path, perms).expect("Failed to set permissions");
        }
        #[cfg(not(unix))]
        {
            fs::write(&test_cmd_path, "@echo off\necho test output").expect("Failed to write test command");
        }

        // Note: We can't easily test execute_external_command without modifying HOME
        // This test just verifies the command file was created correctly
        assert!(test_cmd_path.exists());
    }

    #[test]
    fn test_input_format_mdx() {
        let (_, temp_file_path) = create_file("test_mdx.mdx", "# MDX test");
        let (_, output_file) = create_file("test_mdx_output.md", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Mdx),
                ..Default::default()
            },
            output: OutputArgs {
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(output_content.contains("# MDX test"), "Output should contain heading");
    }

    #[test]
    fn test_input_format_html() {
        let (_, temp_file_path) = create_file("test_html.html", "<h1>HTML test</h1>");
        let (_, output_file) = create_file("test_html_output.md", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Html),
                ..Default::default()
            },
            output: OutputArgs {
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(
            output_content.contains("# HTML test"),
            "Output should contain converted heading"
        );
    }

    #[test]
    fn test_output_format_json_markdown_input() {
        let (_, temp_file_path) = create_file("test_json_md_input.md", "# Test");
        let (_, output_file) = create_file("test_json_md_output.json", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Json,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        let parsed: serde_json::Value = serde_json::from_str(&output_content).expect("Output should be valid JSON");
        assert!(parsed.is_array(), "Markdown JSON output should be an array");
        let nodes = parsed.as_array().unwrap();
        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0]["type"], "Heading", "Markdown heading should have type=Heading");
        assert!(
            nodes[0].get("position").is_some(),
            "position should be present by default"
        );
    }

    #[test]
    fn test_output_format_json_markdown_input_no_position() {
        let (_, temp_file_path) = create_file("test_json_md_input_no_position.md", "# Test");
        let (_, output_file) = create_file("test_json_md_output_no_position.json", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Json,
                output_file: Some(output_file.clone()),
                no_position: true,
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        let parsed: serde_json::Value = serde_json::from_str(&output_content).expect("Output should be valid JSON");
        let nodes = parsed.as_array().unwrap();
        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0]["type"], "Heading");
        assert!(
            nodes[0].get("position").is_none(),
            "--no-position should omit position from the top-level node"
        );
        let children = nodes[0]["values"].as_array().expect("heading should have values");
        assert!(
            children.iter().all(|c| c.get("position").is_none()),
            "--no-position should omit position from child nodes too"
        );
    }

    #[test]
    fn test_output_format_json_with_json_object_input() {
        let (_, temp_file_path) = create_file("test_json_obj_input.json", r#"{"id": 1, "name": "Alice"}"#);
        let (_, output_file) = create_file("test_json_obj_output.json", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Json,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        let parsed: serde_json::Value = serde_json::from_str(&output_content).expect("Output should be valid JSON");
        assert!(parsed.is_object(), "JSON object input should output a JSON object");
        assert_eq!(parsed["id"], 1.0, "id field should be preserved");
        assert_eq!(parsed["name"], "Alice", "name field should be preserved");
        assert!(
            parsed.get("type").is_none(),
            "Output should not contain Markdown AST 'type' field"
        );
    }

    #[test]
    fn test_output_format_json_with_json_array_input() {
        let (_, temp_file_path) = create_file(
            "test_json_arr_input.json",
            r#"[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]"#,
        );
        let (_, output_file) = create_file("test_json_arr_output.json", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Json,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        let parsed: serde_json::Value = serde_json::from_str(&output_content).expect("Output should be valid JSON");
        assert!(parsed.is_array(), "JSON array input should output a JSON array");
        let arr = parsed.as_array().unwrap();
        assert_eq!(arr.len(), 2, "Array should have 2 elements");
        assert_eq!(arr[0]["id"], 1.0);
        assert_eq!(arr[0]["name"], "Alice");
        assert_eq!(arr[1]["id"], 2.0);
        assert_eq!(arr[1]["name"], "Bob");
        assert!(
            arr[0].get("type").is_none(),
            "Output should not contain Markdown AST fields"
        );
    }

    #[test]
    fn test_output_format_gron() {
        let (_, temp_file_path) = create_file("test_gron_output.md", "# Title\n");
        let (_, output_file) = create_file("test_gron_output.gron", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Gron,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(output_content.contains("json[0].type = \"Heading\";\n"));
        assert!(output_content.contains("json[0].depth = 1;\n"));
    }

    #[test]
    fn test_input_format_gron_reconstructs_data() {
        let (_, temp_file_path) = create_file(
            "test_gron_input.gron",
            "json = {};\njson.a = {};\njson.a.b = \"deep\";\njson.arr = [];\njson.arr[0] = 1;\njson.arr[1] = 2;\n",
        );
        let (_, output_file) = create_file("test_gron_input_output.json", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Json,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        let parsed: serde_json::Value = serde_json::from_str(&output_content).expect("Output should be valid JSON");
        assert_eq!(parsed["a"]["b"], "deep");
        assert_eq!(parsed["arr"][0], 1.0);
        assert_eq!(parsed["arr"][1], 2.0);
    }

    #[test]
    fn test_output_format_gron_then_input_format_gron_round_trip() {
        let (_, md_file) = create_file("test_gron_roundtrip.md", "# Title\n\nSome *text* here.\n");
        let (_, gron_file) = create_file("test_gron_roundtrip.gron", "");
        let (_, json_file) = create_file("test_gron_roundtrip.json", "");
        let md_file_clone = md_file.clone();
        let gron_file_clone = gron_file.clone();
        let json_file_clone = json_file.clone();

        defer! {
            if md_file_clone.exists() {
                std::fs::remove_file(&md_file_clone).ok();
            }
            if gron_file_clone.exists() {
                std::fs::remove_file(&gron_file_clone).ok();
            }
            if json_file_clone.exists() {
                std::fs::remove_file(&json_file_clone).ok();
            }
        }

        let to_gron = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Gron,
                output_file: Some(gron_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![md_file.clone()]),
            ..Cli::default()
        };
        assert!(to_gron.run().is_ok());

        let from_gron = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Json,
                output_file: Some(json_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![gron_file]),
            ..Cli::default()
        };
        assert!(from_gron.run().is_ok());

        let direct_json = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Json,
                output_file: Some(json_file.with_extension("direct.json")),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![md_file]),
            ..Cli::default()
        };
        assert!(direct_json.run().is_ok());

        let roundtrip_content = fs::read_to_string(&json_file).expect("Failed to read roundtrip output");
        let direct_content =
            fs::read_to_string(json_file.with_extension("direct.json")).expect("Failed to read direct output");
        fs::remove_file(json_file.with_extension("direct.json")).ok();

        let roundtrip_value: serde_json::Value =
            serde_json::from_str(&roundtrip_content).expect("Roundtrip output should be valid JSON");
        let direct_value: serde_json::Value =
            serde_json::from_str(&direct_content).expect("Direct output should be valid JSON");
        assert_eq!(roundtrip_value, direct_value);
    }

    #[test]
    fn test_output_format_raw() {
        let (_, output_file) = create_file("test_raw_output.bin", "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some(r#"to_bytes("hello")"#.to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_bytes = fs::read(&output_file).expect("Failed to read output");
        assert_eq!(output_bytes, b"hello");
    }

    #[rstest]
    #[case::from_string("raw_from_string", r#"to_bytes("hello")"#, b"hello" as &[u8])]
    #[case::from_number_array("raw_from_array", "to_bytes([104, 101, 108, 108, 111])", b"hello")]
    #[case::binary_data("raw_binary", "to_bytes([0, 255, 128, 1])", &[0u8, 255, 128, 1])]
    #[case::non_bytes_string("raw_string_value", r#""hello""#, b"hello")]
    #[case::utf8("raw_utf8", r#"to_bytes("あ")"#, &[0xe3u8, 0x81, 0x82])]
    #[case::empty("raw_empty", "to_bytes([])", b"")]
    fn test_output_format_raw_bytes(#[case] suffix: &str, #[case] query: &str, #[case] expected: &[u8]) {
        let (_, output_file) = create_file(&format!("test_{}.bin", suffix), "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some(query.to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_bytes = fs::read(&output_file).expect("Failed to read output");
        assert_eq!(output_bytes, expected);
    }

    #[test]
    fn test_output_format_none() {
        let (_, temp_file_path) = create_file("test_none.md", "# Test");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::None,
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_output_format_table_single_column() {
        let (_, temp_file_path) = create_file("test_table.md", "# Test\n\nContent");
        let (_, output_file) = create_file("test_table_output.md", "");
        let temp_file_path_clone = temp_file_path.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Table,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(output_content.contains("value"), "Table should have value header");
        assert!(output_content.contains("Test"), "Table should contain node text");
    }

    #[test]
    fn test_output_format_table_dict() {
        let (_, output_file) = create_file("test_table_dict_output.md", "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Table,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some(r#"{name: "Alice", age: "30"}"#.to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(output_content.contains("name"), "Table should contain name column");
        assert!(output_content.contains("age"), "Table should contain age column");
        assert!(output_content.contains("Alice"), "Table should contain Alice");
        assert!(output_content.contains("30"), "Table should contain 30");
    }

    #[test]
    fn test_output_format_table_nested_dict() {
        let (_, output_file) = create_file("test_table_nested_dict_output.md", "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Table,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some(r#"{name: "Alice", addr: {city: "Tokyo", zip: "100"}}"#.to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(output_content.contains("addr"), "Table should contain addr column");
        assert!(output_content.contains("name"), "Table should contain name column");
        assert!(output_content.contains("Alice"), "Table should contain Alice");
        assert!(output_content.contains("city"), "Nested table should contain city key");
        assert!(output_content.contains("Tokyo"), "Nested table should contain Tokyo");
        assert!(output_content.contains("zip"), "Nested table should contain zip key");
        assert!(output_content.contains("100"), "Nested table should contain 100");
        assert!(!output_content.contains("addr.city"), "Dot notation must not appear");
    }

    #[test]
    fn test_output_format_table_array_value() {
        let (_, output_file) = create_file("test_table_array_value_output.md", "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Table,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some(r#"{name: "Alice", tags: ["a", "b"]}"#.to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(output_content.contains("tags"), "Table should contain tags column");
        assert!(output_content.contains('a'), "Nested table should contain a");
        assert!(output_content.contains('b'), "Nested table should contain b");
        assert!(output_content.contains("Alice"), "Table should contain Alice");
        assert!(!output_content.contains(r#"["a""#), "Raw array repr must not appear");
    }

    #[test]
    fn test_output_format_table_array_input() {
        let (_, output_file) = create_file("test_table_array_input_output.md", "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Table,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some(r#"[{a: "1"}, {a: "2"}]"#.to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(output_content.contains('a'), "Table should have column 'a'");
        assert!(output_content.contains('1'), "Row 1 value should appear");
        assert!(output_content.contains('2'), "Row 2 value should appear");
        assert!(
            !output_content.contains("value"),
            "Should not fall back to 'value' column"
        );
    }

    #[test]
    fn test_link_title_styles() {
        let (_, temp_file_path) = create_file("test_link_title.md", "[link](url \"title\")");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
        }

        for (style, expected_char) in [
            (LinkTitleStyle::Double, '"'),
            (LinkTitleStyle::Single, '\''),
            (LinkTitleStyle::Paren, '('),
        ] {
            let (_, output_file) = create_file(&format!("test_link_title_{:?}.md", style), "");
            let output_file_clone = output_file.clone();

            defer! {
                if output_file_clone.exists() {
                    std::fs::remove_file(&output_file_clone).ok();
                }
            }

            let cli = Cli {
                input: InputArgs::default(),
                output: OutputArgs {
                    link_title_style: style.clone(),
                    output_file: Some(output_file.clone()),
                    ..Default::default()
                },
                commands: None,
                query: Some("self".to_string()),
                files: Some(vec![temp_file_path.clone()]),
                ..Cli::default()
            };

            assert!(cli.run().is_ok());
            let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
            if style == LinkTitleStyle::Paren {
                assert!(
                    output_content.contains("(title)"),
                    "Paren style should wrap title with parens"
                );
            } else {
                assert!(
                    output_content.contains(expected_char),
                    "Link title should use {:?} style",
                    style
                );
            }
        }
    }

    #[test]
    fn test_link_url_styles() {
        let (_, temp_file_path) = create_file("test_link_url.md", "[link](https://example.com)");
        let temp_file_path_clone = temp_file_path.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
        }

        for style in [LinkUrlStyle::None, LinkUrlStyle::Angle] {
            let (_, output_file) = create_file(&format!("test_link_url_{:?}.md", style), "");
            let output_file_clone = output_file.clone();

            defer! {
                if output_file_clone.exists() {
                    std::fs::remove_file(&output_file_clone).ok();
                }
            }

            let cli = Cli {
                input: InputArgs::default(),
                output: OutputArgs {
                    link_url_style: style.clone(),
                    output_file: Some(output_file.clone()),
                    ..Default::default()
                },
                commands: None,
                query: Some("self".to_string()),
                files: Some(vec![temp_file_path.clone()]),
                ..Cli::default()
            };

            assert!(cli.run().is_ok());
            let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
            if style == LinkUrlStyle::Angle {
                assert!(
                    output_content.contains("<https://example.com>"),
                    "Angle style should wrap URL with angle brackets"
                );
            } else {
                assert!(
                    output_content.contains("(https://example.com)"),
                    "None style should not wrap URL"
                );
            }
        }
    }

    #[test]
    fn test_aggregate_flag() {
        let (_, temp_file1) = create_file("test_agg1.md", "# Test 1");
        let (_, temp_file2) = create_file("test_agg2.md", "# Test 2");
        let (_, output_file) = create_file("test_agg_output.md", "");
        let temp_file1_clone = temp_file1.clone();
        let temp_file2_clone = temp_file2.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file1_clone.exists() {
                std::fs::remove_file(&temp_file1_clone).ok();
            }
            if temp_file2_clone.exists() {
                std::fs::remove_file(&temp_file2_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                aggregate: true,
                ..Default::default()
            },
            output: OutputArgs {
                output_file: Some(output_file.clone()),
                output_format: OutputFormat::Text,
                ..Default::default()
            },
            commands: None,
            query: Some("len()".to_string()),
            files: Some(vec![temp_file1, temp_file2]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(!output_content.is_empty(), "Aggregated output should not be empty");
    }

    #[test]
    fn test_eval_all_combines_nodes_across_files() {
        let (_, temp_file1) = create_file("test_eval_all1.md", "# File One\n\n## Sub A");
        let (_, temp_file2) = create_file("test_eval_all2.md", "# File Two\n\n## Sub B");
        let (_, output_file) = create_file("test_eval_all_output.md", "");
        let temp_file1_clone = temp_file1.clone();
        let temp_file2_clone = temp_file2.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file1_clone.exists() {
                std::fs::remove_file(&temp_file1_clone).ok();
            }
            if temp_file2_clone.exists() {
                std::fs::remove_file(&temp_file2_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        // -A alone aggregates per file (2 separate counts); --eval-all -A must combine
        // both files into a single collection before "nodes" runs, giving one total.
        let cli = Cli {
            input: InputArgs {
                aggregate: true,
                eval_all: true,
                ..Default::default()
            },
            output: OutputArgs {
                output_file: Some(output_file.clone()),
                output_format: OutputFormat::Text,
                ..Default::default()
            },
            commands: None,
            query: Some(".h | len".to_string()),
            files: Some(vec![temp_file1, temp_file2]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert_eq!(
            output_content.trim(),
            "4",
            "should count headings across both files as one"
        );
    }

    #[test]
    fn test_eval_all_rejects_mixed_input_formats() {
        let (_, temp_md) = create_file("test_eval_all_mixed.md", "# Test");
        let (_, temp_json) = create_file("test_eval_all_mixed.json", r#"{"a":1}"#);
        let temp_md_clone = temp_md.clone();
        let temp_json_clone = temp_json.clone();

        defer! {
            if temp_md_clone.exists() {
                std::fs::remove_file(&temp_md_clone).ok();
            }
            if temp_json_clone.exists() {
                std::fs::remove_file(&temp_json_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                eval_all: true,
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_md, temp_json]),
            ..Cli::default()
        };

        let err = cli.run().unwrap_err();
        assert!(err.to_string().contains("--eval-all requires"));
    }

    #[test]
    fn test_from_file_flag() {
        let (_, query_file) = create_file("test_query.mq", "self");
        let (_, input_file) = create_file("test_from_file.md", "# Test");
        let query_file_clone = query_file.clone();
        let input_file_clone = input_file.clone();

        defer! {
            if query_file_clone.exists() {
                std::fs::remove_file(&query_file_clone).ok();
            }
            if input_file_clone.exists() {
                std::fs::remove_file(&input_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                from_file: true,
                ..Default::default()
            },
            output: OutputArgs::default(),
            commands: None,
            query: Some(query_file.to_string_lossy().to_string()),
            files: Some(vec![input_file]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_separator_flag() {
        let (_, temp_file1) = create_file("test_sep1.md", "# Test 1");
        let (_, temp_file2) = create_file("test_sep2.md", "# Test 2");
        let (_, output_file) = create_file("test_sep_output.md", "");
        let temp_file1_clone = temp_file1.clone();
        let temp_file2_clone = temp_file2.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file1_clone.exists() {
                std::fs::remove_file(&temp_file1_clone).ok();
            }
            if temp_file2_clone.exists() {
                std::fs::remove_file(&temp_file2_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                separator: Some("\"---\"".to_string()),
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file1, temp_file2]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let output_content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(!output_content.is_empty(), "Output should not be empty");
        assert!(output_content.contains("# Test"), "File content should be present");
    }

    #[test]
    fn test_output_file_flag() {
        let (_, temp_input) = create_file("test_input_out.md", "# Test Output");
        let temp_output = std::env::temp_dir().join("test_output_file.md");
        let temp_input_clone = temp_input.clone();
        let temp_output_clone = temp_output.clone();

        defer! {
            if temp_input_clone.exists() {
                std::fs::remove_file(&temp_input_clone).ok();
            }
            if temp_output_clone.exists() {
                std::fs::remove_file(&temp_output_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_file: Some(temp_output.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_input]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        assert!(temp_output.exists(), "Output file should exist");
        let output_content = fs::read_to_string(&temp_output).expect("Failed to read output");
        assert!(
            output_content.contains("# Test Output"),
            "Output content should match input"
        );
    }

    #[test]
    fn test_unbuffered_output() {
        let (_, temp_file) = create_file("test_unbuf.md", "# Test");
        let temp_file_clone = temp_file.clone();

        defer! {
            if temp_file_clone.exists() {
                std::fs::remove_file(&temp_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                unbuffered: true,
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_update_with_non_markdown_input() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Html),
                ..Default::default()
            },
            output: OutputArgs {
                update: true,
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: None,
            ..Cli::default()
        };

        assert!(cli.run().is_err());
    }

    #[test]
    fn test_list_commands() {
        let cli = Cli {
            list: true,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[test]
    fn test_parallel_threshold() {
        let files: Vec<PathBuf> = (0..15)
            .map(|i| {
                let (_, path) = create_file(&format!("test_parallel_{}.md", i), "# Test");
                path
            })
            .collect();

        let files_clone = files.clone();
        defer! {
            for file in &files_clone {
                if file.exists() {
                    std::fs::remove_file(file).ok();
                }
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs::default(),
            commands: None,
            query: Some("self".to_string()),
            files: Some(files),
            parallel_threshold: 10,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
    }

    #[rstest]
    #[case("mq-exec-owner", 0o700, true)]
    #[case("mq-exec-group", 0o010, true)]
    #[case("mq-exec-other", 0o001, true)]
    #[case("mq-exec-all", 0o755, true)]
    #[case("mq-noexec-rw", 0o644, false)]
    #[case("mq-noexec-ro", 0o444, false)]
    #[cfg(unix)]
    fn test_is_executable_file_unix(#[case] filename: &str, #[case] mode: u32, #[case] expected: bool) {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = std::env::temp_dir().join(format!("mq-exec-test-{filename}"));
        fs::create_dir_all(&temp_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        let file_path = temp_dir.join(filename);
        fs::write(&file_path, "#!/bin/sh\necho test").expect("Failed to write file");
        fs::set_permissions(&file_path, fs::Permissions::from_mode(mode)).expect("Failed to set permissions");

        let entry = fs::read_dir(&temp_dir)
            .expect("Failed to read dir")
            .find(|e| e.as_ref().unwrap().file_name().to_str() == Some(filename))
            .unwrap()
            .unwrap();

        assert_eq!(
            Cli::is_executable_file(&entry),
            expected,
            "File with mode {mode:#o} should return {expected}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_is_executable_file_unix_directory() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = std::env::temp_dir().join("mq-dir-test-unix");
        let sub_dir = temp_dir.join("mq-subdir");
        fs::create_dir_all(&sub_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        fs::set_permissions(&sub_dir, fs::Permissions::from_mode(0o755)).expect("Failed to set permissions");

        let entry = fs::read_dir(&temp_dir)
            .expect("Failed to read dir")
            .find(|e| e.as_ref().unwrap().file_name() == "mq-subdir")
            .unwrap()
            .unwrap();

        assert!(!Cli::is_executable_file(&entry), "Directory should return false");
    }

    #[rstest]
    #[case("mq-test.exe", true)]
    #[case("mq-test.cmd", true)]
    #[case("mq-test.bat", true)]
    #[case("mq-test.com", true)]
    #[case("mq-test.EXE", true)]
    #[case("mq-test.Bat", true)]
    #[case("mq-test.txt", false)]
    #[case("mq-test.sh", false)]
    #[case("mq-test", false)]
    #[cfg(windows)]
    fn test_is_executable_file_windows(#[case] filename: &str, #[case] expected: bool) {
        let temp_dir = std::env::temp_dir().join(format!("mq-exec-test-win-{}", filename.replace('.', "-")));
        fs::create_dir_all(&temp_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        let file_path = temp_dir.join(filename);
        fs::write(&file_path, "test").expect("Failed to write file");

        let entry = fs::read_dir(&temp_dir)
            .expect("Failed to read dir")
            .find(|e| e.as_ref().unwrap().file_name().to_str() == Some(filename))
            .unwrap()
            .unwrap();

        assert_eq!(
            Cli::is_executable_file(&entry),
            expected,
            "File '{filename}' should return {expected}"
        );
    }

    #[test]
    #[cfg(windows)]
    fn test_is_executable_file_windows_directory() {
        let temp_dir = std::env::temp_dir().join("mq-dir-test-windows");
        let sub_dir = temp_dir.join("mq-subdir");
        fs::create_dir_all(&sub_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        let entry = fs::read_dir(&temp_dir)
            .expect("Failed to read dir")
            .find(|e| e.as_ref().unwrap().file_name() == "mq-subdir")
            .unwrap()
            .unwrap();

        assert!(!Cli::is_executable_file(&entry), "Directory should return false");
    }

    #[test]
    #[cfg(not(any(unix, windows)))]
    fn test_is_executable_file_other_os() {
        let temp_dir = std::env::temp_dir().join("mq-other-test");
        fs::create_dir_all(&temp_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        let file = temp_dir.join("mq-test");
        fs::write(&file, "test").expect("Failed to write file");

        let entry = fs::read_dir(&temp_dir)
            .expect("Failed to read dir")
            .find(|e| e.as_ref().unwrap().file_name() == "mq-test")
            .unwrap()
            .unwrap();

        assert!(
            Cli::is_executable_file(&entry),
            "Regular file should return true on other OS"
        );
    }

    #[test]
    #[cfg(not(any(unix, windows)))]
    fn test_is_executable_file_other_os_directory() {
        let temp_dir = std::env::temp_dir().join("mq-dir-other-test");
        let sub_dir = temp_dir.join("mq-subdir");
        fs::create_dir_all(&sub_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        let entry = fs::read_dir(&temp_dir)
            .expect("Failed to read dir")
            .find(|e| e.as_ref().unwrap().file_name() == "mq-subdir")
            .unwrap()
            .unwrap();

        assert!(
            !Cli::is_executable_file(&entry),
            "Directory should return false on other OS"
        );
    }

    /// Test that Windows deduplicates commands with different executable extensions.
    /// e.g., mq-foo.bat and mq-foo.exe in the same directory should produce only "foo".
    #[test]
    #[cfg(windows)]
    fn test_collect_mq_commands_deduplicates_windows_extensions() {
        let temp_dir = std::env::temp_dir().join("mq-win-dedup-ext-test");
        fs::create_dir_all(&temp_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        // Create the same subcommand with multiple Windows executable extensions
        fs::write(temp_dir.join("mq-foo.exe"), "test").expect("Failed to write file");
        fs::write(temp_dir.join("mq-foo.bat"), "@echo test").expect("Failed to write file");
        fs::write(temp_dir.join("mq-foo.cmd"), "@echo test").expect("Failed to write file");
        fs::write(temp_dir.join("mq-bar.exe"), "test").expect("Failed to write file");

        let mut seen = std::collections::HashSet::new();
        Cli::collect_mq_commands_from_dir(&temp_dir, &mut seen);

        assert_eq!(seen.len(), 2, "Should have exactly 2 unique commands");
        assert!(seen.contains("foo"), "Should contain 'foo'");
        assert!(seen.contains("bar"), "Should contain 'bar'");
    }

    /// Test that Windows deduplicates commands with different extensions across directories.
    /// e.g., mq-foo.bat in dir1 and mq-foo.exe in dir2 should produce only "foo".
    #[test]
    #[cfg(windows)]
    fn test_collect_mq_commands_deduplicates_across_dirs_windows() {
        let dir1 = std::env::temp_dir().join("mq-win-cross-dedup-1");
        let dir2 = std::env::temp_dir().join("mq-win-cross-dedup-2");
        fs::create_dir_all(&dir1).expect("Failed to create test directory");
        fs::create_dir_all(&dir2).expect("Failed to create test directory");

        defer! {
            if dir1.exists() {
                std::fs::remove_dir_all(&dir1).ok();
            }
            if dir2.exists() {
                std::fs::remove_dir_all(&dir2).ok();
            }
        }

        fs::write(dir1.join("mq-foo.bat"), "@echo test").expect("Failed to write file");
        fs::write(dir2.join("mq-foo.exe"), "test").expect("Failed to write file");
        fs::write(dir2.join("mq-unique.cmd"), "@echo test").expect("Failed to write file");

        let mut seen = std::collections::HashSet::new();
        Cli::collect_mq_commands_from_dir(&dir1, &mut seen);
        Cli::collect_mq_commands_from_dir(&dir2, &mut seen);

        assert_eq!(seen.len(), 2, "Should have exactly 2 unique commands");
        assert!(seen.contains("foo"), "Should contain 'foo'");
        assert!(seen.contains("unique"), "Should contain 'unique'");
    }

    /// Test that collect_mq_commands_from_dir handles an empty directory correctly.
    #[test]
    fn test_collect_mq_commands_from_empty_dir() {
        let temp_dir = std::env::temp_dir().join("mq-empty-dir-test");
        fs::create_dir_all(&temp_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        let mut seen = std::collections::HashSet::new();
        Cli::collect_mq_commands_from_dir(&temp_dir, &mut seen);
        assert!(seen.is_empty(), "Empty directory should yield no commands");
    }

    /// Test that files without the mq- prefix are ignored even if executable.
    #[test]
    fn test_collect_mq_commands_ignores_non_mq_prefix() {
        let temp_dir = std::env::temp_dir().join("mq-prefix-test");
        fs::create_dir_all(&temp_dir).expect("Failed to create test directory");

        defer! {
            if temp_dir.exists() {
                std::fs::remove_dir_all(&temp_dir).ok();
            }
        }

        // Create files without mq- prefix
        fs::write(temp_dir.join("foo"), "test").expect("Failed to write file");
        fs::write(temp_dir.join("bar-mq"), "test").expect("Failed to write file");
        fs::write(temp_dir.join("mqfoo"), "test").expect("Failed to write file");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            for name in &["foo", "bar-mq", "mqfoo"] {
                fs::set_permissions(temp_dir.join(name), fs::Permissions::from_mode(0o755))
                    .expect("Failed to set permissions");
            }
        }

        let mut seen = std::collections::HashSet::new();
        Cli::collect_mq_commands_from_dir(&temp_dir, &mut seen);
        assert!(seen.is_empty(), "Files without mq- prefix should be ignored");
    }

    #[rstest]
    #[case("md", InputFormat::Markdown)]
    #[case("MD", InputFormat::Markdown)]
    #[case("markdown", InputFormat::Markdown)]
    #[case("mdx", InputFormat::Mdx)]
    #[case("html", InputFormat::Html)]
    #[case("htm", InputFormat::Html)]
    #[case("txt", InputFormat::Raw)]
    #[case("log", InputFormat::Raw)]
    #[case("csv", InputFormat::Csv)]
    #[case("gron", InputFormat::Gron)]
    #[case("psv", InputFormat::Psv)]
    #[case("tsv", InputFormat::Tsv)]
    #[case("json", InputFormat::Json)]
    #[case("toml", InputFormat::Toml)]
    #[case("yaml", InputFormat::Yaml)]
    #[case("yml", InputFormat::Yaml)]
    #[case("xml", InputFormat::Xml)]
    #[case("jsonl", InputFormat::Text)]
    #[case("ndjson", InputFormat::Text)]
    #[case("cbor", InputFormat::Cbor)]
    #[case("unknown", InputFormat::Markdown)] // default fallback
    fn test_from_extension(#[case] ext: &str, #[case] expected: InputFormat) {
        assert_eq!(InputFormat::from_extension(ext), expected);
    }

    #[rstest]
    #[case("file.json", Some(r#"import "json" | json::json_parse()"#))]
    #[case("file.gron", Some(r#"import "gron" | gron::gron_parse()"#))]
    #[case("file.yaml", Some(r#"import "yaml" | yaml::yaml_parse()"#))]
    #[case("file.yml", Some(r#"import "yaml" | yaml::yaml_parse()"#))]
    #[case("file.toml", Some(r#"import "toml" | toml::toml_parse()"#))]
    #[case("file.xml", Some(r#"import "xml" | xml::xml_parse()"#))]
    #[case("file.toon", Some(r#"import "toon" | toon::toon_parse()"#))]
    #[case("file.csv", Some(r#"import "csv" | csv::csv_parse(true)"#))]
    #[case("file.tsv", Some(r#"import "csv" | csv::tsv_parse(true)"#))]
    #[case("file.psv", Some(r#"import "csv" | csv::psv_parse(true)"#))]
    #[case("file.cbor", Some(r#"import "cbor" | cbor::cbor_parse()"#))]
    #[case("file.md", None)]
    #[case("file.txt", None)]
    fn test_auto_query_prefix(#[case] filename: &str, #[case] expected: Option<&str>) {
        let cli = Cli {
            input: InputArgs::default(),
            ..Cli::default()
        };
        let file = Some(PathBuf::from(filename));
        assert_eq!(cli.auto_query_prefix(&file).as_deref(), expected);
    }

    #[test]
    fn test_auto_query_prefix_disabled_when_input_format_set() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Raw),
                ..Default::default()
            },
            ..Cli::default()
        };
        let file = Some(PathBuf::from("file.json"));
        assert_eq!(cli.auto_query_prefix(&file), None);
    }

    #[test]
    fn test_auto_query_prefix_none_for_no_file() {
        let cli = Cli {
            input: InputArgs::default(),
            ..Cli::default()
        };
        assert_eq!(cli.auto_query_prefix(&None), None);
    }

    #[test]
    fn test_json_auto_parse() {
        let (_, temp_file_path) = create_file("auto_parse_test.json", r#"{"key": "value"}"#);
        let temp_file_path_clone = temp_file_path.clone();
        let (_, output_file) = create_file("auto_parse_output.md", "");
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(content.contains("value"), "JSON should be parsed automatically");
    }

    #[test]
    fn test_csv_auto_parse() {
        let (_, temp_file_path) = create_file("auto_parse_test.csv", "name,age\nAlice,30\n");
        let temp_file_path_clone = temp_file_path.clone();
        let (_, output_file) = create_file("auto_parse_csv_output.md", "");
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() {
                std::fs::remove_file(&temp_file_path_clone).ok();
            }
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            commands: None,
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(content.contains("Alice"), "CSV should be parsed automatically");
        assert!(content.contains("name"), "CSV header should be parsed");
    }

    fn create_binary_file(name: &str, content: &[u8]) -> (PathBuf, PathBuf) {
        let temp_dir = std::env::temp_dir();
        let temp_file_path = temp_dir.join(name);
        let mut file = File::create(&temp_file_path).expect("Failed to create temp file");
        file.write_all(content).expect("Failed to write to temp file");
        (temp_dir, temp_file_path)
    }

    #[test]
    fn test_content_data_empty() {
        let c = ContentData::empty();
        assert_eq!(c.as_str(), Some(""));
        assert_eq!(c.as_bytes(), b"");
    }

    #[rstest]
    #[case(ContentData::Text("hello".to_string()), Some("hello"))]
    #[case(ContentData::Text("".to_string()), Some(""))]
    #[case(ContentData::Bytes(vec![0xde, 0xad]), None)]
    #[case(ContentData::Bytes(vec![]), None)]
    fn test_content_data_as_str(#[case] input: ContentData, #[case] expected: Option<&str>) {
        assert_eq!(input.as_str(), expected);
    }

    #[rstest]
    #[case(ContentData::Text("abc".to_string()), b"abc".as_ref())]
    #[case(ContentData::Text("".to_string()), b"".as_ref())]
    #[case(ContentData::Bytes(vec![0xde, 0xad, 0xbe, 0xef]), &[0xde, 0xad, 0xbe, 0xef])]
    #[case(ContentData::Bytes(vec![]), b"".as_ref())]
    fn test_content_data_as_bytes(#[case] input: ContentData, #[case] expected: &[u8]) {
        assert_eq!(input.as_bytes(), expected);
    }

    #[rstest]
    #[case("hello".to_string(), Some("hello"))]
    #[case("".to_string(), Some(""))]
    fn test_content_data_from_string(#[case] s: String, #[case] expected_str: Option<&str>) {
        let c: ContentData = s.into();
        assert_eq!(c.as_str(), expected_str);
    }

    #[rstest]
    #[case(vec![0x01, 0x02, 0x03])]
    #[case(vec![])]
    fn test_content_data_from_vec_u8(#[case] bytes: Vec<u8>) {
        let expected = bytes.clone();
        let c: ContentData = bytes.into();
        assert_eq!(c.as_str(), None);
        assert_eq!(c.as_bytes(), expected.as_slice());
    }

    #[rstest]
    #[case(Some(InputFormat::Bytes), true)]
    #[case(Some(InputFormat::Cbor), true)]
    #[case(Some(InputFormat::Json), false)]
    #[case(Some(InputFormat::Yaml), false)]
    #[case(Some(InputFormat::Toml), false)]
    #[case(Some(InputFormat::Markdown), false)]
    #[case(Some(InputFormat::Raw), false)]
    #[case(Some(InputFormat::Text), false)]
    #[case(Some(InputFormat::Null), false)]
    #[case(None, false)]
    fn test_is_binary_format(#[case] fmt: Option<InputFormat>, #[case] expected: bool) {
        let cli = Cli {
            input: InputArgs {
                input_format: fmt,
                ..Default::default()
            },
            ..Cli::default()
        };
        assert_eq!(cli.is_binary_format(), expected);
    }

    #[rstest]
    #[case(InputFormat::Bytes, None)]
    #[case(InputFormat::Cbor, Some(r#"import "cbor" | cbor::cbor_parse()"#))]
    #[case(InputFormat::Gron, Some(r#"import "gron" | gron::gron_parse()"#))]
    #[case(InputFormat::Json, Some(r#"import "json" | json::json_parse()"#))]
    #[case(InputFormat::Markdown, None)]
    #[case(InputFormat::Raw, None)]
    fn test_module_query_prefix(#[case] fmt: InputFormat, #[case] expected: Option<&str>) {
        assert_eq!(fmt.module_query_prefix(), expected);
    }

    #[rstest]
    #[case(InputFormat::Bytes)]
    #[case(InputFormat::Cbor)]
    fn test_binary_format_streaming_returns_error(#[case] fmt: InputFormat) {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(fmt),
                stream: true,
                ..Default::default()
            },
            query: Some("self".to_string()),
            ..Cli::default()
        };
        assert!(cli.run().is_err());
    }

    #[rstest]
    #[case(&[0x01, 0x02, 0x03, 0xff], "self", "bytes_self")]
    #[case(&[0xca, 0xfe, 0xba, 0xbe], "self", "bytes_self2")]
    fn test_bytes_input_self_roundtrip(#[case] data: &[u8], #[case] query: &str, #[case] suffix: &str) {
        let (_, temp_file_path) = create_binary_file(&format!("test_{suffix}.bin"), data);
        let temp_file_path_clone = temp_file_path.clone();
        let (_, output_file) = create_file(&format!("test_{suffix}_out.md"), "");
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() { std::fs::remove_file(&temp_file_path_clone).ok(); }
            if output_file_clone.exists() { std::fs::remove_file(&output_file_clone).ok(); }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Bytes),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some(query.to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read(&output_file).expect("Failed to read output");
        assert_eq!(result, data);
    }

    #[rstest]
    #[case(&[0xca, 0xfe, 0xba, 0xbe], "4")]
    #[case(&[0x01], "1")]
    #[case(&[], "0")]
    fn test_bytes_input_len(#[case] data: &[u8], #[case] expected_len: &str) {
        let suffix = format!("bytes_len_{}", data.len());
        let (_, temp_file_path) = create_binary_file(&format!("test_{suffix}.bin"), data);
        let temp_file_path_clone = temp_file_path.clone();
        let (_, output_file) = create_file(&format!("test_{suffix}_out.md"), "");
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() { std::fs::remove_file(&temp_file_path_clone).ok(); }
            if output_file_clone.exists() { std::fs::remove_file(&output_file_clone).ok(); }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Bytes),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some("len()".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert_eq!(result.trim(), expected_len);
    }

    #[rstest]
    // CBOR text string "hello": major 3 (text), len 5
    #[case(&[0x65, 0x68, 0x65, 0x6c, 0x6c, 0x6f], None, "hello", "cbor_auto_hello")]
    // CBOR integer 42: 0x18 0x2a
    #[case(&[0x18, 0x2a], Some(InputFormat::Cbor), "42", "cbor_explicit_42")]
    // CBOR integer 0: 0x00
    #[case(&[0x00], Some(InputFormat::Cbor), "0", "cbor_explicit_0")]
    fn test_cbor_parse(
        #[case] cbor_bytes: &[u8],
        #[case] fmt: Option<InputFormat>,
        #[case] expected: &str,
        #[case] suffix: &str,
    ) {
        let ext = if fmt.is_none() { "cbor" } else { "bin" };
        let (_, temp_file_path) = create_binary_file(&format!("test_{suffix}.{ext}"), cbor_bytes);
        let temp_file_path_clone = temp_file_path.clone();
        let (_, output_file) = create_file(&format!("test_{suffix}_out.md"), "");
        let output_file_clone = output_file.clone();

        defer! {
            if temp_file_path_clone.exists() { std::fs::remove_file(&temp_file_path_clone).ok(); }
            if output_file_clone.exists() { std::fs::remove_file(&output_file_clone).ok(); }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: fmt,
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some("self".to_string()),
            files: Some(vec![temp_file_path]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(
            result.trim().contains(expected),
            "expected '{}' in output, got '{}'",
            expected,
            result.trim()
        );
    }

    #[rstest]
    #[case::data_only(
        "data_only",
        None,
        Some(vec!["x".to_string(), "y".to_string(), "z".to_string()]),
        "ARGS",
        r#"{"positional": ["x", "y", "z"], "named": {}}"#
    )]
    #[case::args_only(
        "args_only",
        Some(vec!["name".to_string(), "Alice".to_string()]),
        None,
        "ARGS",
        r#"{"positional": [], "named": {"name": "Alice"}}"#
    )]
    #[case::args_and_data(
        "args_and_data",
        Some(vec!["name".to_string(), "Alice".to_string()]),
        Some(vec!["x".to_string(), "y".to_string()]),
        "ARGS",
        r#"{"positional": ["x", "y"], "named": {"name": "Alice"}}"#
    )]
    #[case::positional_access(
        "positional_access",
        None,
        Some(vec!["a".to_string(), "b".to_string()]),
        r#"ARGS | ."positional""#,
        r#"["a", "b"]"#
    )]
    #[case::named_access(
        "named_access",
        Some(vec!["key".to_string(), "val".to_string()]),
        None,
        r#"ARGS | ."named""#,
        r#"{"key": "val"}"#
    )]
    #[case::named_individual_var(
        "named_individual_var",
        Some(vec!["greeting".to_string(), "hello".to_string()]),
        None,
        "greeting",
        "hello"
    )]
    fn test_args_and_data(
        #[case] suffix: &str,
        #[case] args: Option<Vec<String>>,
        #[case] argv: Option<Vec<String>>,
        #[case] query: &str,
        #[case] expected: &str,
    ) {
        let (_, output_file) = create_file(&format!("test_args_data_{suffix}.md"), "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                args,
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some(query.to_string()),
            argv,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert_eq!(result.trim(), expected, "query: {}", query);
    }

    #[rstest]
    #[case::string_value(
        "string_value",
        vec!["name".to_string(), r#""Alice""#.to_string()],
        "name",
        "Alice"
    )]
    #[case::number_value(
        "number_value",
        vec!["count".to_string(), "42".to_string()],
        "count",
        "42"
    )]
    #[case::bool_value(
        "bool_value",
        vec!["flag".to_string(), "true".to_string()],
        "flag",
        "true"
    )]
    #[case::null_value(
        "null_value",
        vec!["n".to_string(), "null".to_string()],
        "n",
        ""
    )]
    #[case::array_value(
        "array_value",
        vec!["list".to_string(), "[1,2,3]".to_string()],
        "list",
        r#"[1, 2, 3]"#
    )]
    #[case::object_value(
        "object_value",
        vec!["obj".to_string(), r#"{"a":1}"#.to_string()],
        "obj",
        r#"{"a": 1}"#
    )]
    #[case::args_named_access(
        "args_named_access",
        vec!["count".to_string(), "42".to_string()],
        r#"ARGS | ."named""#,
        r#"{"count": 42}"#
    )]
    fn test_argjson(#[case] suffix: &str, #[case] argjson: Vec<String>, #[case] query: &str, #[case] expected: &str) {
        let (_, output_file) = create_file(&format!("test_argjson_{suffix}.md"), "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                argjson: Some(argjson),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some(query.to_string()),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert_eq!(result.trim(), expected, "query: {}", query);
    }

    #[test]
    fn test_argjson_invalid_json_errors() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                argjson: Some(vec!["name".to_string(), "not valid json".to_string()]),
                ..Default::default()
            },
            query: Some("name".to_string()),
            ..Cli::default()
        };

        assert!(
            cli.run().is_err(),
            "--argjson with malformed JSON should return an error"
        );
    }

    #[test]
    fn test_argjson_combined_with_args_and_argv() {
        let (_, output_file) = create_file("test_argjson_combined.md", "");
        let output_file_clone = output_file.clone();

        defer! {
            if output_file_clone.exists() {
                std::fs::remove_file(&output_file_clone).ok();
            }
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                args: Some(vec!["name".to_string(), "Alice".to_string()]),
                argjson: Some(vec!["count".to_string(), "42".to_string()]),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some(r#"ARGS | ."named""#.to_string()),
            argv: Some(vec!["x".to_string()]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        // `named` is backed by a `BTreeMap<Ident, _>`, whose key order depends on the
        // global string interner's symbol assignment order rather than the key text,
        // so compare parsed JSON values instead of the raw serialized string.
        let actual: serde_json::Value = serde_json::from_str(result.trim()).expect("output should be valid JSON");
        let expected: serde_json::Value = serde_json::from_str(r#"{"count": 42, "name": "Alice"}"#).unwrap();
        assert_eq!(actual, expected);
    }

    #[rstest]
    #[case::single_object("single_object", r#"{"a": 1}"#, "data", r#"[{"a": 1}]"#)]
    #[case::single_array("single_array", "[1, 2, 3]", "data", r#"[[1, 2, 3]]"#)]
    #[case::multiple_concatenated_values("multiple_values", "1 2 3", "data", "[1, 2, 3]")]
    fn test_slurpfile(#[case] suffix: &str, #[case] file_content: &str, #[case] query: &str, #[case] expected: &str) {
        let (_, data_file) = create_file(&format!("test_slurpfile_{suffix}.json"), file_content);
        let (_, output_file) = create_file(&format!("test_slurpfile_{suffix}_out.md"), "");
        let data_file_clone = data_file.clone();
        let output_file_clone = output_file.clone();

        defer! {
            std::fs::remove_file(&data_file_clone).ok();
            std::fs::remove_file(&output_file_clone).ok();
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                slurp_file: Some(vec!["data".to_string(), data_file.to_string_lossy().to_string()]),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some(query.to_string()),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert_eq!(result.trim(), expected, "query: {}", query);
    }

    #[test]
    fn test_slurpfile_invalid_json_errors() {
        let (_, data_file) = create_file("test_slurpfile_invalid.json", "not valid json");
        let data_file_clone = data_file.clone();

        defer! {
            std::fs::remove_file(&data_file_clone).ok();
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                slurp_file: Some(vec!["data".to_string(), data_file.to_string_lossy().to_string()]),
                ..Default::default()
            },
            query: Some("data".to_string()),
            ..Cli::default()
        };

        assert!(
            cli.run().is_err(),
            "--slurpfile with malformed JSON should return an error"
        );
    }

    #[test]
    fn test_slurpfile_missing_file_errors() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                slurp_file: Some(vec!["data".to_string(), "/nonexistent/path/to/file.json".to_string()]),
                ..Default::default()
            },
            query: Some("data".to_string()),
            ..Cli::default()
        };

        assert!(
            cli.run().is_err(),
            "--slurpfile with a missing file should return an error"
        );
    }

    #[test]
    fn test_slurpfile_combined_with_args_and_argjson() {
        let (_, data_file) = create_file("test_slurpfile_combined.json", r#"{"c": 3}"#);
        let (_, output_file) = create_file("test_slurpfile_combined_out.md", "");
        let data_file_clone = data_file.clone();
        let output_file_clone = output_file.clone();

        defer! {
            std::fs::remove_file(&data_file_clone).ok();
            std::fs::remove_file(&output_file_clone).ok();
        }

        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                args: Some(vec!["name".to_string(), "Alice".to_string()]),
                argjson: Some(vec!["count".to_string(), "42".to_string()]),
                slurp_file: Some(vec!["data".to_string(), data_file.to_string_lossy().to_string()]),
                ..Default::default()
            },
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some("data".to_string()),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert_eq!(result.trim(), r#"[{"c": 3}]"#, "query: data");
    }

    #[test]
    fn test_files_without_data_single_file() {
        let (_, input_file) = create_file("test_files_no_data_single.md", "# hello");
        let (_, output_file) = create_file("test_files_no_data_single_out.md", "");
        let input_file_clone = input_file.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if input_file_clone.exists() { std::fs::remove_file(&input_file_clone).ok(); }
            if output_file_clone.exists() { std::fs::remove_file(&output_file_clone).ok(); }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Text,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some("self".to_string()),
            files: Some(vec![input_file]),
            argv: None,
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(result.contains("hello"), "file content should be processed");
    }

    #[test]
    fn test_files_without_data_multiple_files() {
        // Verify each file is processed independently; output_file is per-run so check each separately.
        let (_, file1) = create_file("test_files_no_data_multi1.md", "# file1");
        let (_, file2) = create_file("test_files_no_data_multi2.md", "# file2");
        let (_, out1) = create_file("test_files_no_data_multi_out1.md", "");
        let (_, out2) = create_file("test_files_no_data_multi_out2.md", "");
        let file1_clone = file1.clone();
        let file2_clone = file2.clone();
        let out1_clone = out1.clone();
        let out2_clone = out2.clone();

        defer! {
            if file1_clone.exists() { std::fs::remove_file(&file1_clone).ok(); }
            if file2_clone.exists() { std::fs::remove_file(&file2_clone).ok(); }
            if out1_clone.exists() { std::fs::remove_file(&out1_clone).ok(); }
            if out2_clone.exists() { std::fs::remove_file(&out2_clone).ok(); }
        }

        for (input, output, expected) in [(&file1, &out1, "file1"), (&file2, &out2, "file2")] {
            let cli = Cli {
                input: InputArgs::default(),
                output: OutputArgs {
                    output_format: OutputFormat::Text,
                    output_file: Some(output.clone()),
                    ..Default::default()
                },
                query: Some("self".to_string()),
                files: Some(vec![input.clone()]),
                argv: None,
                ..Cli::default()
            };
            assert!(cli.run().is_ok());
            let result = fs::read_to_string(output).expect("Failed to read output");
            assert!(result.contains(expected), "file content '{}' should appear", expected);
        }

        // Also verify multi-file run (no output_file) succeeds without error
        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs::default(),
            query: Some("self".to_string()),
            files: Some(vec![file1, file2]),
            argv: None,
            ..Cli::default()
        };
        assert!(cli.run().is_ok(), "multi-file run without --argv should succeed");
    }

    #[test]
    fn test_files_with_data_does_not_mix() {
        // --argv values must not be treated as files, and files must not appear in ARGS
        let (_, input_file) = create_file("test_files_with_data.md", "# content");
        let (_, output_file) = create_file("test_files_with_data_out.md", "");
        let input_file_clone = input_file.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if input_file_clone.exists() { std::fs::remove_file(&input_file_clone).ok(); }
            if output_file_clone.exists() { std::fs::remove_file(&output_file_clone).ok(); }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Raw,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some("ARGS".to_string()),
            files: Some(vec![input_file]),
            argv: Some(vec!["alpha".to_string(), "beta".to_string()]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(result.contains("alpha"), "ARGS.positional should contain 'alpha'");
        assert!(result.contains("beta"), "ARGS.positional should contain 'beta'");
        assert!(!result.contains("content"), "file content must not appear in ARGS");
    }

    #[test]
    fn test_files_without_data_args_undefined() {
        // Without --argv or --args, ARGS must be undefined (runtime error expected)
        let (_, input_file) = create_file("test_files_no_args_undefined.md", "# x");
        let input_file_clone = input_file.clone();

        defer! {
            if input_file_clone.exists() { std::fs::remove_file(&input_file_clone).ok(); }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs::default(),
            query: Some("ARGS".to_string()),
            files: Some(vec![input_file]),
            argv: None,
            ..Cli::default()
        };

        assert!(
            cli.run().is_err(),
            "ARGS should be undefined when neither --args nor --argv is given"
        );
    }

    #[test]
    fn test_files_with_data_file_content_processed() {
        // File content is still processed even when --argv is given
        let (_, input_file) = create_file("test_files_data_content.md", "# heading");
        let (_, output_file) = create_file("test_files_data_content_out.md", "");
        let input_file_clone = input_file.clone();
        let output_file_clone = output_file.clone();

        defer! {
            if input_file_clone.exists() { std::fs::remove_file(&input_file_clone).ok(); }
            if output_file_clone.exists() { std::fs::remove_file(&output_file_clone).ok(); }
        }

        let cli = Cli {
            input: InputArgs::default(),
            output: OutputArgs {
                output_format: OutputFormat::Text,
                output_file: Some(output_file.clone()),
                ..Default::default()
            },
            query: Some("self".to_string()),
            files: Some(vec![input_file]),
            argv: Some(vec!["x".to_string()]),
            ..Cli::default()
        };

        assert!(cli.run().is_ok());
        let result = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(
            result.contains("heading"),
            "file content should still be processed when --argv is given"
        );
    }

    #[test]
    fn test_args_pair_works() {
        let cli = Cli {
            input: InputArgs {
                input_format: Some(InputFormat::Null),
                args: Some(vec!["name".to_string(), "Alice".to_string()]),
                ..Default::default()
            },
            query: Some("name".to_string()),
            ..Cli::default()
        };
        assert!(cli.run().is_ok(), "--args with a valid NAME VALUE pair should succeed");
    }

    #[cfg(feature = "watch")]
    #[test]
    fn test_watch_targets_requires_a_file() {
        let cli = Cli {
            files: None,
            query: Some("self".to_string()),
            ..Cli::default()
        };
        assert!(
            cli.watch_targets().is_err(),
            "--watch on stdin (no files) should be rejected"
        );
    }

    #[cfg(feature = "watch")]
    #[test]
    fn test_watch_targets_includes_input_files() {
        let file = PathBuf::from("input.md");
        let cli = Cli {
            files: Some(vec![file.clone()]),
            query: Some("self".to_string()),
            ..Cli::default()
        };
        assert_eq!(cli.watch_targets().unwrap(), vec![file]);
    }

    #[cfg(feature = "watch")]
    #[test]
    fn test_watch_targets_includes_query_file_when_from_file() {
        let input_file = PathBuf::from("input.md");
        let query_file = "query.mq";
        let cli = Cli {
            input: InputArgs {
                from_file: true,
                ..Default::default()
            },
            files: Some(vec![input_file.clone()]),
            query: Some(query_file.to_string()),
            ..Cli::default()
        };
        assert_eq!(
            cli.watch_targets().unwrap(),
            vec![input_file, PathBuf::from(query_file)]
        );
    }
}